diff --git a/.coveragerc b/.coveragerc new file mode 100644 index 0000000000..e7df5c4479 --- /dev/null +++ b/.coveragerc @@ -0,0 +1,6 @@ +[run] +branch = True +[report] +exclude_lines = + pragma: no cover + raise NotImplementedError.* diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000000..f4ae26a85e --- /dev/null +++ b/.flake8 @@ -0,0 +1,4 @@ +[flake8] +max-line-length = 120 +ignore = E126 +exclude = samcli/local/init/templates \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..82b6163fd5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,36 @@ + + +**Description:** + + + +**Steps to reproduce the issue:** +1. +2. +3. + +**Observed result:** + +**Expected result:** + +**Additional environment details (Ex: Windows, Mac, Amazon Linux etc)** + +**Output of `sam --version`**: + +**Optional Debug logs**: + +`Add --debug flag to command you are running` diff --git a/.gitignore b/.gitignore index 9e9a7e00ce..5dbf0258cf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,383 @@ + +# Created by https://www.gitignore.io/api/osx,node,macos,linux,python,windows,pycharm,intellij,sublimetext,visualstudiocode + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries +.idea + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Ruby plugin and RubyMine +/.rakeTasks + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +*.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + + +### OSX ### + +# Icon must end with two \r + +# Thumbnails + +# Files that might appear in the root of a volume + +# Directories potentially created on remote AFP share + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: + +# Sensitive or high-churn files: + +# Gradle: + +# CMake + +# Mongo Explorer plugin: + +## File-based project format: + +## Plugin-specific files: + +# IntelliJ + +# mpeltonen/sbt-idea plugin + +# JIRA plugin + +# Cursive Clojure plugin + +# Ruby plugin and RubyMine + +# Crashlytics plugin (for Android Studio and IntelliJ) + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ dist/ -.idea/ -.vscode/ -.cache/ -./aws-sam-local -debug +downloads/ +eggs/ +.eggs/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### SublimeText ### +# cache files for sublime text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# workspace files are user-specific +*.sublime-workspace + +# project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using SublimeText +# *.sublime-project + +# sftp configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,node,macos,linux,python,windows,pycharm,intellij,sublimetext,visualstudiocode diff --git a/.goreleaser.yml b/.goreleaser.yml deleted file mode 100644 index 4f833f71aa..0000000000 --- a/.goreleaser.yml +++ /dev/null @@ -1,59 +0,0 @@ -# Build customization -project_name: sam -builds: - - - binary: sam - goos: - - windows - - darwin - - linux - goarch: - - amd64 - - 386 - - #hooks: - # post: ./distribution/npm/npm-release.sh - -archive: - format: tar.gz - files: - - LICENSE - - NOTICE - -# Publish to Github Releases -release: - github: - owner: awslabs - name: aws-sam-local - - # Don't auto-publish the release. Admin has to manually publish at right time - # Setting to true will also prevent brew from being published - draft: false - -# homebrew release -#brew: -# -# # repository to push the tap to. -# folder: Formula -# github: -# owner: awslabs -# name: homebrew-tap -# -# homepage: "https://github.com/awslabs/aws-sam-local" -# description: "Develop and test your serverless applications locally without uploading to AWS Lambda" -# test: | -# output = shell_output(bin/"sam --version") -# assert_match "sam version #{version}", output -# -# install: | -# bin.install "aws-sam-local" - -fpm: - vendor: Amazon Web Services - homepage: https://github.com/awslabs/aws-sam-local - maintainer: aws-sam-cli@amazon.com - description: AWS SAM Local is a CLI tool for developing, testing and deploying Serverless applications. - license: Apache 2.0 - formats: - - deb - - rpm diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000..c0987c591e --- /dev/null +++ b/.pylintrc @@ -0,0 +1,363 @@ +[MASTER] + +# Specify a configuration file. +#rcfile= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=compat.py + +# Pickle collected data for later comparisons. +persistent=yes + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Use multiple processes to speed up Pylint. +jobs=1 + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist= + +# Allow optimization of some AST trees. This will activate a peephole AST +# optimizer, which will apply various small optimizations. For instance, it can +# be used to obtain the result of joining multiple strings with the addition +# operator. Joining a lot of strings can lead to a maximum recursion error in +# Pylint and this flag can prevent that. It has one side effect, the resulting +# AST will be different than the one from reality. +optimize-ast=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time. See also the "--disable" option for examples. +#enable= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +disable=R0201,W0613,I0021,I0020,W1618,W1619,R0902,R0903,W0231,W0611,R0913,W0703,C0330,R0204,I0011,R0904,C0301 + + +[REPORTS] + +# Set the output format. Available formats are text, parseable, colorized, msvs +# (visual studio) and html. You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Put messages in a separate file for each module / package specified on the +# command line instead of printing them on stdout. Reports (if any) will be +# written in a file name "pylint_global.[txt|html]". +files-output=no + +# Tells whether to display a full report or only the messages +reports=no + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + + +[BASIC] + +# List of builtins function names that should not be used, separated by a comma +bad-functions=apply,reduce + +# Good variable names which should always be accepted, separated by a comma +good-names=e,i,j,k,n,ex,Run,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=yes + +# Regular expression matching correct function names +function-rgx=[a-z_][a-z0-9_]{2,50}$ + +# Naming hint for function names +function-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct variable names +variable-rgx=[a-z_][a-z0-9_]{0,50}$ + +# Naming hint for variable names +variable-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct constant names +const-rgx=(([a-zA-Z_][a-zA-Z0-9_]*)|(__.*__))$ + +# Naming hint for constant names +const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Regular expression matching correct attribute names +attr-rgx=[a-z_][a-z0-9_]{1,50}$ + +# Naming hint for attribute names +attr-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct argument names +argument-rgx=[a-z_][a-z0-9_]{0,50}$ + +# Naming hint for argument names +argument-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct class attribute names +class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Naming hint for class attribute names +class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Regular expression matching correct inline iteration names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Naming hint for inline iteration names +inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ + +# Regular expression matching correct class names +class-rgx=[A-Z_][a-zA-Z0-9]+$ + +# Naming hint for class names +class-name-hint=[A-Z_][a-zA-Z0-9]+$ + +# Regular expression matching correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Naming hint for module names +module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression matching correct method names +method-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for method names +method-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=.* + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + + +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=120 + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + +# List of optional constructs for which whitespace checking is disabled +no-space-check=trailing-comma,dict-separator + +# Maximum number of lines in a module +max-module-lines=1000 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX + + +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=6 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=yes + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[TYPECHECK] + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis +ignored-modules=six.moves + +# List of classes names for which member attributes should not be checked +# (useful for classes with attributes dynamically set). +ignored-classes=SQLObject + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E0201 when accessed. Python regular +# expressions are accepted. +generated-members=REQUEST,acl_users,aq_parent,objects,DoesNotExist,md5,sha1,sha224,sha256,sha384,sha512 + + +[VARIABLES] + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=_|dummy|ignore + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.* + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of branch for function / method body +max-branches=12 + +# Maximum number of statements in function / method body +max-statements=30 + +# Maximum number of parents for a class (see R0901). +max-parents=6 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=0 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + + +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=regsub,string,TERMIOS,Bastion,rexec,UserDict + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/.travis.yml b/.travis.yml index 7a87b85a8e..15d4952614 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,13 @@ -language: go +# Enable container based builds +sudo: false +language: python -go: - - 1.8 \ No newline at end of file +install: +# Install the code requirements +- make init + +# Install Docs requirements + +script: +# Runs unit tests +- make pr diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 537fc8fbc8..1de4002ab0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,32 +1,65 @@ -# Contributing to AWS SAM Local +# Contributing Guidelines -Contributions to AWS SAM Local should be made via GitHub [pull -requests](https://github.com/awslabs/aws-sam-local/pulls) and discussed using -GitHub [issues](https://github.com/awslabs/aws-sam-local/issues). +Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional +documentation, we greatly value feedback and contributions from our community. -### Before you start +Please read through this document before submitting any issues or pull requests to ensure we have all the necessary +information to effectively respond to your bug report or contribution. -If you would like to make a significant change, it's a good idea to first open -an issue to discuss it. +## Development Guide -### Making the request +Refer to the [Development Guide](DEVELOPMENT_GUIDE.rst) for help with environment setup, running tests, submitting a PR, or anything that will make you more productive. -1. Create a fork of the AWS SAM Local repository [(quick link)](https://github.com/awslabs/aws-sam-local#fork-destination-box) -2. Commit your changes to your fork -3. Create a new pull request [(quick link)](https://github.com/awslabs/aws-sam-local/compare) -### Testing +## Reporting Bugs/Feature Requests -Any contributions should pass all tests, including those not run by our -current CI system. +We welcome you to use the GitHub issue tracker to report bugs or suggest features. + +When filing an issue, please check [existing open](https://github.com/awslabs/aws-sam-cli/issues), or [recently closed](https://github.com/awslabs/aws-sam-cli/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already +reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: + +* A reproducible test case or series of steps +* The version of our code being used +* Any modifications you've made relevant to the bug +* Anything unusual about your environment or deployment + + +## Contributing via Pull Requests +Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: + +1. You are working against the latest source on the *develop* branch. +2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. +3. You open an issue to discuss any significant work - we would hate for your time to be wasted. + +To send us a pull request, please: + +1. Fork the repository. +2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. +3. Ensure local tests pass. +4. Commit to your fork using clear commit messages. +5. Send us a pull request, answering any default questions in the pull request interface. +6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. + +GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and +[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). + + +## Finding contributions to work on +Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/aws-sam-cli/labels/help%20wanted) issues is a great place to start. + + +## Code of Conduct +This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). +For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact +opensource-codeofconduct@amazon.com with any additional questions or comments. + + +## Security issue notifications +If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. -You may run all tests by running `go test` (requires `go` to be installed). ## Licensing -The AWS SAM Local is released under an [Apache -2.0](http://aws.amazon.com/apache-2-0/) license. Any code you submit will be -released under that license. +See the [LICENSE](https://github.com/awslabs/aws-sam-cli/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. -For significant changes, we may ask you to sign a [Contributor License -Agreement](http://en.wikipedia.org/wiki/Contributor_License_Agreement). +We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. diff --git a/DESIGN.rst b/DESIGN.rst new file mode 100644 index 0000000000..5e0bad079d --- /dev/null +++ b/DESIGN.rst @@ -0,0 +1,55 @@ +DESIGN DOCUMENT +=============== + + "..with proper design, the features come cheaply " - Dennis Ritchie + + +This document is intended to capture key decisions in the design of this CLI. This is especially useful for new +contributors to understand the codebase and keep the changes aligned with design decisions. We will update +this document when new components are added or the CLI design changes significantly. + +Tenets +====== +These are some key guiding principles for the design: + +- Extensibility is by design. It is not an after thought. +- Each component must be self-contained and testable in isolation. +- Command line interface must be one of many supported input mechanisms. +- SAM is one of many supported input formats. + + +CLI Framework +============= +This component implements generic CLI functionality that makes it easy to write individual CLI commands. It performs: + +- CLI argument parsing +- Generating help text and man pages from RST docs of the command. +- Fetching configuration information from environment +- Consistent exit code generation +- [Future] HTTP Mode: Ability to call the CLI commands with same parameters through a HTTP Endpoint. This is useful for +IDEs and other tools to integrate with this CLI. + +Each command, along with any subcommands, is implemented using Click annotations. They are not directly wired with +the core of the CLI. Instead, commands are dynamically loaded into the CLI at run time by importing the Python +package implementing the command. For example, assuming two commands are implemented at Python packages +"foo.cli.cmd1" and "foo.cli.cmd2", then the CLI framework will dynamically import these two packages and connect them +to parent Click instance. The CLI framework expects the command's Click object to be exposed through an attribute +called ``cli``. + +For example: if "foo.bar.hello" is the package where "hello" command is implemented, then +"/foo/bar/hello/__init__.py" file is expected to contain a Click object called ``cli``. + +By convention, the name of last module in the package's name is the command's name. ie. A package of "foo.bar.baz" +will produce a command name "baz". + +Commands that make up of the core functionality (like local, validate, generate-event etc) are also implemented +this way. They are baked into the CLI, but in the future, we will provide options to completely remove a command. + +By convention, each command is implemented as a separate Python package where the ``__init__.py`` file +exposes the ``cli`` attribute. This allows new commands to be built and distributed as Python packages +through PIP, opening the architecture to support plugins in future. This structure also forces commands implementations +to be modular, reusable, and highly customizable. When RC files are implemented, new commands can be added or existing +commands can be removed, with simple a configuration in the RC file. + + +.. _`click`: https://github.com/pallets/click diff --git a/DEVELOPMENT_GUIDE.rst b/DEVELOPMENT_GUIDE.rst new file mode 100644 index 0000000000..5c5ecd1816 --- /dev/null +++ b/DEVELOPMENT_GUIDE.rst @@ -0,0 +1,107 @@ +DEVELOPMENT GUIDE +================= + +**Welcome hacker!** + +This document will make your life easier by helping you setup a development environment, IDEs, tests, coding practices, +or anything that will help you be more productive. If you found something is missing or inaccurate, update this guide +and send a Pull Request. + +Environment Setup +----------------- + +1. Install Python Versions +~~~~~~~~~~~~~~~~~~~~~~~~~~ +Even though Python 2.7 is our officially supported version, we have a goal to support both Python 2.7 and 3.6 versions. +Follow the idioms from this `excellent cheatsheet`_ to make sure your code is compatible with both Python versions. +Our CI/CD pipeline is setup to run unit tests against both Python versions. So make sure you test it with both +versions before sending a Pull Request. `pyenv`_ is a great tool to easily setup multiple Python versions. + +#. Install PyEnv - ``curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash`` +#. ``pyenv install 2.7.14`` +#. ``pyenv install 3.6.4`` +#. Make both Python versions available in the project: ``pyenv local 3.6.4 2.7.14`` + + +2. Activate Virtualenv +~~~~~~~~~~~~~~~~~~~~~~ +Virtualenv allows you to install required libraries outside of the Python installation. A good practice is to setup +a different virtualenv for each project. `pyenv`_ comes with a handy plugin that can create virtualenv. + +#. Create new virtualenv if it does not exist: ``pyenv virtualenv 2.7.14 samcli27`` +#. ``pyenv activate samcli27`` + + +3. Install dev version of SAM CLI +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +We will install a development version of SAM CLI from source into the virtualenv for you to try out the CLI as you +make changes. We will install in a command called ``samdev`` to keep it separate from a global SAM CLI installation, +if any. + +#. Activate Virtualenv: ``pyenv activate samcli27`` +#. Install dev CLI: ``make init`` +#. Make sure installation succeeded: ``which samdev`` + + +Running Tests +------------- + +Unit testing with multiple Python versions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`tox`_ is used to run tests against all supported Python versions. Follow these instructions to setup multiple Python +versions using `pyenv`_ before running tox: + +#. Deactivate virtualenvs, if any: ``pyenv deactivate`` +#. ``pip install tox`` +#. Run tests against all supported Python versions: ``tox`` + +Integration Test +~~~~~~~~~~~~~~~~ + +``make integ-test`` - To run integration test against global SAM CLI installation. It looks for a command named ``sam`` +in your shell. + +``SAM_CLI_DEV=1 make integ-test`` - To run integration tests against development version of SAM CLI. This is useful if +you are making changes to the CLI and want to verify that it works. It is a good practice to run integration tests +before submitting a pull request. + +Code Conventions +---------------- + +Please follow these code conventions when making your changes. This will align your code to the same conventions used +in rest of the package and make it easier for others to read/understand your code. Some of these conventions are +best practices that we have learnt over time. + +- Use `numpy docstring`_ format for docstrings. Some parts of the code still use an older, unsupported format. If you + happened to be modifying these methods, please change the docstring format as well. + +- Don't write any code in ``__init__.py`` file + +- Module-level logger variable must be named as ``LOG`` + +- If your method wants to report a failure, it *must* raise a custom exception. Built-in Python exceptions like + ``TypeError``, ``KeyError`` are raised by Python interpreter and usually signify a bug in your code. Your method must + not explicitly raise these exceptions because the caller has no way of knowing whether it came from a bug or not. + Custom exceptions convey are must better at conveying the intent and can be handled appropriately by the caller. + In HTTP lingo, custom exceptions are equivalent to 4xx (user's fault) and built-in exceptions are equivalent + to 5xx (Service Fault) + +- CLI commands must always raise a subclass of ``click.ClickException`` to signify an error. Error code and message + must be set as a part of this exception and not explicitly returned by the CLI command. + +- Don't use ``*args`` or ``**kwargs`` unless there is a really strong reason to do so. You must explain the reason + in great detail in docstrings if you were to use them. + +- Library classes, ie. the ones under ``lib`` folder, must **not** use Click. Usage of Click must be restricted to + the ``commands`` package. In the library package, your classes must expose interfaces that are independent + of the user interface, be it a CLI thru Click, or CLI thru argparse, or HTTP API, or a GUI. + +- Do not catch the broader ``Exception``, unless you have a really strong reason to do. You must explain the reason + in great detail in comments. + + +.. _excellent cheatsheet: http://python-future.org/compatible_idioms.html +.. _pyenv: https://github.com/pyenv/pyenv +.. _tox: http://tox.readthedocs.io/en/latest/ +.. _numpy docstring: https://numpydoc.readthedocs.io/en/latest/format.html diff --git a/HOWTO.md b/HOWTO.md deleted file mode 100644 index 73ce85014e..0000000000 --- a/HOWTO.md +++ /dev/null @@ -1,204 +0,0 @@ - -Let's imagine we want to build a simple RESTful API to list, create, read, update and delete products. We'll start by laying out our project directory like so: - -```bash -├── products.js -└── template.yaml -``` - -The `template.yaml` file is the AWS SAM template. Let's start by describing a single Lambda function to handle all of our API requests to `/products`. - -```yaml -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: My first serverless application. - -Resources: - - Products: - Type: AWS::Serverless::Function - Properties: - Handler: products.handler - Runtime: nodejs6.10 - Events: - ListProducts: - Type: Api - Properties: - Path: /products - Method: get - CreateProduct: - Type: Api - Properties: - Path: /products - Method: post - Product: - Type: Api - Properties: - Path: /products/{product} - Method: any - -``` - -In the above example, we're configuring the following RESTful API endpoints: - -* Create new product with a `PUT` request to `/products`. -* List all products with a `GET` request to `/products`. -* Read, update or delete a product with `GET`, `PUT` or `DELETE` request to `/products/{product}`. - -In order to service these, let's create a Lambda function in `products.js` like so: - -```javascript -'use strict'; - -exports.handler = (event, context, callback) => { - - let id = event.pathParameters ? event.pathParameters.product : null; - switch(event.httpMethod){ - - case "GET": - - if(id) { - callback(null, { - statusCode: 200, - body: "This is a READ operation on product ID " + id - }); - return; - } - - callback(null, { - statusCode: 200, - body: "This is a LIST operation, return all products" - }); - break; - - case "POST": - callback(null, { - statusCode: 200, - body: "This is a CREATE operation" - }); - break; - - case "PUT": - callback(null, { - statusCode: 200, - body: "This is a UPDATE operation on product ID " + id - }); - break; - - case "DELETE": - callback(null, { - statusCode: 200, - body: "This is a DELETE operation on product ID " + id - }); - break; - - default: - // Send HTTP 501: Not Implemented - console.log("Error: unsupported HTTP method (" + event.httpMethod + ")"); - callback(null, { statusCode: 501 }) - - } - -} -``` - -We can quickly run this locally with SAM CLI, to help us iterate quickly on development: - -```bash -$ sam local start-api - -2017/05/18 14:03:01 Successfully parsed template.yaml (AWS::Serverless-2016-10-31) -2017/05/18 14:03:01 Found 1 AWS::Serverless::Function -2017/05/18 14:03:01 Mounting products.handler (nodejs6.10) at /products [POST] -2017/05/18 14:03:01 Mounting products.handler (nodejs6.10) at /products/{product} [OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT] -2017/05/18 14:03:01 Mounting products.handler (nodejs6.10) at /products [GET] -2017/05/18 14:03:01 Listening on http://localhost:3000 - -You can now browse to the above endpoints to invoke your functions. -You do not need to restart/reload while working on your functions, -changes will be reflected instantly/automatically. You only need to restart -if you update your AWS SAM template. -``` - -Now we can test our API endpoint locally either with a browser, or the CLI: - -```bash -$ curl http://localhost:3000/products -"This is a LIST operation, return all products" - -$ curl -XDELETE http://localhost:3000/products/1 -"This is a DELETE operation on product ID 1" -``` - -Any logging output (e.g. `console.log()`) as well as the AWS Lambda runtime logs are displayed by the SAM CLI. For example, in our code above we are logging an error message if an unsupported HTTP method is called. - -Let's test this by calling our API with an unsupported HTTP method: - -```bash -$ curl -XOPTIONS http://localhost:3000/products/1 -* Trying ::1... -* TCP_NODELAY set -* Connected to localhost (::1) port 3000 (#0) -> OPTIONS /products/1 HTTP/1.1 -> Host: localhost:3000 -> User-Agent: curl/7.51.0 -> Accept: */* -> -< HTTP/1.1 501 Not Implemented -< Content-Type: application/json -< Date: Thu, 18 May 2017 13:18:57 GMT -< Content-Length: 0 -< -``` - -If we look back at the AWS SAM output, we can see our log entry: - -```java -START RequestId: 2137da9a-c79c-1d43-5716-406b4e6b5c0a Version: $LATEST -2017-05-18T13:18:57.852Z 2137da9a-c79c-1d43-5716-406b4e6b5c0a Error: unsupported HTTP method (OPTIONS) -END RequestId: 2137da9a-c79c-1d43-5716-406b4e6b5c0a -REPORT RequestId: 2137da9a-c79c-1d43-5716-406b4e6b5c0a Duration: 12.78 ms Billed Duration: 100 ms Memory Size: 0 MB Max Memory Used: 29 MB -``` - -When you are developing, any changes to your AWS Lambda function code are reflected instantly - no need to restart `sam local start-api`. - -When you're ready to deploy your Serverless application to AWS, it's easy to package and deploy via the AWS CLI using `aws cloudformation package` and `aws cloudformation deploy`. You can read more - -Or, you can easily setup a full CI/CD pipeline with AWS CodePipeline to automate your software delivery process using [AWS CodeStar][CodeStar]. - -## Developing other (non-API) Serverless Applications - -SAM CLI supports generation of mock Serverless events, allowing you to develop and test locally on functions that respond to asynchronous events such as those from S3, Kinesis, or DynamoDB. - -You can use the `sam local generate-event` command to create these events: - -```bash -$ sam local generate-event -NAME: - sam local generate-event - Generates Lambda events (e.g. for S3/Kinesis etc) that can be piped to 'sam local invoke' - -USAGE: - sam local generate-event command [command options] [arguments...] - -COMMANDS: - s3 Generates a sample Amazon S3 event - sns Generates a sample Amazon SNS event - kinesis Generates a sample Amazon Kinesis event - dynamodb Generates a sample Amazon DynamoDB event - api Generates a sample Amazon API Gateway event - schedule Generates a sample scheduled event - -OPTIONS: - --help, -h show help -``` - -For example, to locally test a function that recieves an S3 event, you could run: - -``` -$ sam local generate-event s3 --bucket --key | sam local invoke -``` - - - -[SAM]: https://github.com/awslabs/serverless-application-model -[CodeStar]: https://aws.amazon.com/codestar diff --git a/LICENSE b/LICENSE index 8dada3edaf..d645695673 100644 --- a/LICENSE +++ b/LICENSE @@ -1,3 +1,4 @@ + Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -178,7 +179,7 @@ APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" + boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a @@ -186,7 +187,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright {yyyy} {name of copyright owner} + Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000000..beb7271dce --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,6 @@ +include LICENSE +include requirements/base.txt +include requirements/dev.txt +recursive-include samcli/local/init/templates * +recursive-include samcli/lib *.json +prune tests diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..7aacdd5611 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +init: + SAM_CLI_DEV=1 pip install -e '.[dev]' + +test: + # Run unit tests + # Fail if coverage falls below 95% + pytest --cov samcli --cov-report term-missing --cov-fail-under 95 tests/unit + +integ-test: + # Integration tests don't need code coverage + SAM_CLI_DEV=1 pytest tests/integration + +func-test: + # Verify function test coverage only for `samcli.local` package + pytest --cov samcli.local --cov samcli.commands.local --cov-report term-missing tests/functional + +flake: + # Make sure code conforms to PEP8 standards + flake8 samcli + flake8 tests/unit tests/integration + +lint: + # Liner performs static analysis to catch latent bugs + pylint --rcfile .pylintrc samcli + +# Command to run everytime you make changes to verify everything works +dev: flake lint test + +# Verifications to run before sending a pull request +pr: init dev diff --git a/NOTICE b/NOTICE index 6ddb949a6b..3b13d76fd6 100644 --- a/NOTICE +++ b/NOTICE @@ -1,2 +1,2 @@ -aws-sam-local -Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +AWS SAM CLI +Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/README.md b/README.md deleted file mode 100644 index 2635677aca..0000000000 --- a/README.md +++ /dev/null @@ -1,522 +0,0 @@ -

- - SAM Local - -

- -# SAM Local (Beta) - -[![Build Status](https://travis-ci.org/awslabs/aws-sam-local.svg?branch=develop)](https://travis-ci.org/awslabs/aws-sam-local) ![Apache-2.0](https://img.shields.io/npm/l/aws-sam-local.svg?maxAge=2592000) ![Contributers](https://img.shields.io/github/contributors/awslabs/aws-sam-local.svg?maxAge=2592000) ![GitHub-release](https://img.shields.io/github/release/awslabs/aws-sam-local.svg?maxAge=2592000) ![npm-release](https://img.shields.io/npm/v/aws-sam-local.svg?maxAge=2592000) [![Join the chat at https://gitter.im/awslabs/aws-sam-local](https://badges.gitter.im/awslabs/aws-sam-local.svg)](https://gitter.im/awslabs/aws-sam-local?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - - **`sam`** is the AWS CLI tool for managing Serverless applications written with [AWS Serverless Application Model (SAM)](https://github.com/awslabs/serverless-application-model). SAM Local can be used to test functions locally, start a local API Gateway from a SAM template, validate a SAM template, and generate sample payloads for various event sources. - -- [SAM Local (Beta)](#sam-local-beta) - - [Main features](#main-features) - - [Installation](#installation) - - [Prerequisites](#prerequisites) - - [Windows, Linux, macOS with NPM [Recommended]](#windows-linux-macos-with-npm-recommended) - - [Binary release](#binary-release) - - [Build From Source](#build-from-source) - - [Usage](#usage) - - [Invoke functions locally](#invoke-functions-locally) - - [Generate sample event source payloads](#generate-sample-event-source-payloads) - - [Run API Gateway locally](#run-api-gateway-locally) - - [Debugging Applications](#debugging-applications) - - [Debugging Python functions](#debugging-python-functions) - - [Validate SAM templates](#validate-sam-templates) - - [Package and Deploy to Lambda](#package-and-deploy-to-lambda) - - [Getting started](#getting-started) - - [Advanced](#advanced) - - [Compiled Languages (Java)](#compiled-languages-java) - - [IAM Credentials](#iam-credentials) - - [Lambda Environment Variables](#lambda-environment-variables) - - [Environment Variable file](#environment-variable-file) - - [Shell environment](#shell-environment) - - [Combination of Shell and Environment Variable file](#combination-of-shell-and-environment-variable-file) - - [Identifying local execution from Lambda function code](#identifying-local-execution-from-lambda-function-code) - - [Static Assets](#static-assets) - - [Local Logging](#local-logging) - - [Remote Docker](#remote-docker) - - [Project Status](#project-status) - - [Contributing](#contributing) - - [A special thank you](#a-special-thank-you) - - [Examples](#examples) - -## Main features - -* Develop and test your Lambda functions locally with `sam local` and Docker -* Invoke functions from known event sources such as Amazon S3, Amazon DynamoDB, Amazon Kinesis, etc. -* Start local API Gateway from a SAM template, and quickly iterate over your functions with hot-reloading -* Validate SAM templates - -## Installation - -### Prerequisites - -Running Serverless projects and functions locally with SAM Local requires Docker to be installed and running. SAM Local will use the `DOCKER_HOST` environment variable to contact the docker daemon. - - - macOS: [Docker for Mac](https://store.docker.com/editions/community/docker-ce-desktop-mac) - - Windows: [Docker Toolbox](https://download.docker.com/win/stable/DockerToolbox.exe) - - Linux: Check your distro’s package manager (e.g. yum install docker) - -For macOS and Windows users: SAM local requires that the project directory (or any parent directory) is listed in Docker file sharing options. - -Verify that docker is working, and that you can run docker commands from the CLI (e.g. ‘docker ps’). You do not need to install/fetch/pull any containers – SAM Local will do it automatically as required. - - -### Windows, Linux, macOS with NPM [Recommended] - -The easiest way to install **`sam`** is to use [NPM](https://www.npmjs.com). - -```bash -npm install -g aws-sam-local -``` - -Verify the installation worked: -```bash -sam --version -``` - -If you get a permission error when using npm (such as `EACCES: permission denied`), please see the instructions on this page of the NPM documentation: [https://docs.npmjs.com/getting-started/fixing-npm-permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions). - -#### Upgrading via npm - -To update **`sam`** once installed via npm: - -```bash -npm update -g aws-sam-local -``` - -### Binary release - -We also release the CLI as binaries that you can download and instantly use. You can find them under [Releases] in this repo. In case you cannot find the version or architecture you're looking for you can refer to [Build From Source](#build-from-source) section for build details. - -### Build From Source - -First, install Go (v1.8+) on your machine: [https://golang.org/doc/install](https://golang.org/doc/install), then run the following: - -```bash -$ go get github.com/awslabs/aws-sam-local -``` - -This will install **`sam`** to your `$GOPATH/bin` folder. Make sure this directory is in your `$PATH` (or %%PATH%% on Windows) and you should then be able to use the SAM Local. Please note that due to the package name, the binary will be installed as `aws-sam-local` rather than `sam`. - -```bash -aws-sam-local --help -``` - -## Usage - -**`sam`** requires a SAM template in order to know how to invoke your function locally, and it's also true for spawning API Gateway locally - If no template is specified `template.yaml` will be used instead. - -You can find sample SAM templates either under **`samples`** located in this repo or by visiting [SAM] official repository. - -### Invoke functions locally - -![SAM Local Invoke Sample](media/sam-invoke.gif) - -You can invoke your function locally by passing its **SAM logical ID** and an event file. Alternatively, `sam local invoke` accepts stdin as an event too. - -```yaml -Resources: - Ratings: # <-- Logical ID - Type: 'AWS::Serverless::Function' - ... -``` - -**Syntax** - -```bash -# Invoking function with event file -$ sam local invoke "Ratings" -e event.json - -# Invoking function with event via stdin -$ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" - -# For more options -$ sam local invoke --help -``` - -### Generate sample event source payloads - -To make local development and testing of Lambda functions easier, you can generate mock/sample event payloads for the following services: - -* S3 -* Kinesis -* DynamoDB -* Cloudwatch Scheduled Event -* Cloudtrail -* API Gateway - -**Syntax** - -```bash -sam local generate-event -``` - -Also, you can invoke an individual lambda function locally from a sample event payload - Here's an example using S3: - -```bash -sam local generate-event s3 --bucket --key | sam local invoke -``` - -For more options, see `sam local generate-event --help`. - -### Run API Gateway locally - -`sam local start-api` spawns a local API Gateway to test HTTP request/response functionality. Features hot-reloading to allow you to quickly develop, and iterate over your functions. - -![SAM Local Start API](media/sam-start-api.gif) - -**Syntax** - -```bash -sam local start-api -``` - -**`sam`** will automatically find any functions within your SAM template that have `Api` event sources defined, and mount them at the defined HTTP paths. - -In the example below, the `Ratings` function would mount `ratings.py:handler()` at `/ratings` for `GET` requests. - -```yaml -Ratings: - Type: AWS::Serverless::Function - Properties: - Handler: ratings.handler - Runtime: python3.6 - Events: - Api: - Type: Api - Properties: - Path: /ratings - Method: get -``` - -By default, SAM uses [Proxy Integration](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html) and expects the response from your Lambda function to include one or more of the following: `statusCode`, `headers` and/or `body`. - -For example: - -```javascript -// Example of a Proxy Integration response -exports.handler = (event, context, callback) => { - callback(null, { - statusCode: 200, - headers: { "x-custom-header" : "my custom header value" }, - body: "hello world" - }); -} -``` - -For examples in other AWS Lambda languages, see [this page](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html). - -If your function does not return a valid [Proxy Integration](http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html) response then you will get a HTTP 500 (Internal Server Error) when accessing your function. SAM Local will also print the following error log message to help you diagnose the problem: - -``` -ERROR: Function ExampleFunction returned an invalid response (must include one of: body, headers or statusCode in the response object) -``` - -### Debugging Applications - -Both `sam local invoke` and `sam local start-api` support local debugging of your functions. - -To run SAM Local with debugging support enabled, just specify `--debug-port` or `-d` on the command line. - -```bash -# Invoke a function locally in debug mode on port 5858 -$ sam local invoke -d 5858 - -# Start local API Gateway in debug mode on port 5858 -$ sam local start-api -d 5858 -``` - -Note: If using `sam local start-api`, the local API Gateway will expose all of your Lambda functions but, since you can specify a single debug port, you can only debug one function at a time. You will need to hit your API before SAM Local binds to the port allowing the debugger to connect. - -Here is an example showing how to debug a NodeJS function with Microsoft Visual Studio Code: - -![SAM Local debugging example](media/sam-debug.gif) - -In order to setup Visual Studio Code for debugging with AWS SAM Local, use the following launch configuration: - -``` -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Attach to SAM Local", - "type": "node", - "request": "attach", - "address": "localhost", - "port": 5858, - "localRoot": "${workspaceRoot}", - "remoteRoot": "/var/task", - "protocol": "legacy" - } - ] -} -``` - -Note: Node.js versions **below** 7 (e.g. Node.js 4.3 and Node.js 6.10) use the `legacy` protocol, while Node.js versions including and above 7 (e.g. Node.js 8.10) use the `inspector` protocol. Be sure to specify the corresponding protocol in the `protocol` entry of your launch configuration. - -#### Debugging Python functions - -Unlike Node.JS and Java, Python requires you to enable remote debugging in your Lambda function code. If you enable debugging with `--debug-port` or `-d` for a function that uses one of the Python runtimes, SAM Local will just map through that port from your host machine through to the Lambda runtime container. You will need to enable remote debugging in your function code. To do this, use a python package such as [remote-pdb](https://pypi.python.org/pypi/remote-pdb). When configuring the host the debugger listens on in your code, make sure to use `0.0.0.0` not `127.0.0.1` to allow Docker to map through the port to your host machine. - -> Please note, due to a [open bug](https://github.com/Microsoft/vscode-python/issues/71) with Visual Studio Code, you may get a `Debug adapter process has terminated unexpectedly` error when attempting to debug Python applications with this IDE. Please track the [GitHub issue](https://github.com/Microsoft/vscode-python/issues/71) for updates. - -#### Passing Additional Runtime Debug Arguments - -To pass additional runtime arguments when debugging your function, use the environment variable `DEBUGGER_ARGUMENTS`. This will pass a string of arguments directly into the run command SAM Local uses to start your function. - -For example, if you want to load a debugger like iKPdb at runtime of your Python function, you could pass the following as `DEBUGGER_ARGUMENTS`: `-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0`. This would load iKPdb at runtime with the other arguments you've specified. In this case, your full SAM local command would be: - -```bash -$ DEBUGGER_ARGUMENTS="-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0" echo {} | sam local invoke -d 5858 myFunction -``` - -You may pass debugger arguments to functions of all runtimes. - -### Connecting to docker network -Both `sam local invoke` and `sam local start-api` support connecting the create lambda docker containers to an existing docker network. - -To connect the containers to an existing docker network, you can use the `--docker-network` command-line argument or the `SAM_DOCKER_NETWORK` environment variable along with the name or id of the docker network you wish to connect to. - -```bash -# Invoke a function locally and connect to a docker network -$ sam local invoke --docker-network my-custom-network - -# Start local API Gateway and connect all containers to a docker network -$ sam local start-api --docker-network b91847306671 -d 5858 -``` - -### Validate SAM templates - -Validate your templates with `$ sam validate`. -Currently this command will validate that the template provided is valid JSON / YAML. -As with most SAM Local commands, it will look for a `template.yaml` file in your current working directory by default. You can specify a different template file/location with the `-t` or `--template` option. - -**Syntax** - -```bash -$ sam validate -Valid! -``` - -Note: More in-depth functionality is currently disabled. An alternative validation route is to validate your JSON against schema for [the whole CloudFormation and SAM specification.](https://github.com/awslabs/goformation/blob/master/schema/sam.schema.json) - -### Package and Deploy to Lambda -Once you have developed and tested your Serverless application locally, you can deploy to Lambda using `sam package` and `sam deploy` command. `package` command will zip your code artifacts, upload to S3 and produce a SAM file that is ready to be deployed to Lambda using AWS CloudFormation. `deploy` command will deploy the packaged SAM template to CloudFormation. Both `sam package` and `sam deploy` are identical to their AWS CLI equivalents commands [`aws cloudformation package`](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html) and [`aws cloudformation deploy`](http://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/index.html) respectively. Please consult the AWS CLI command documentation for usage. - -Example: - -```bash -# Package SAM template -$ sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file packaged.yaml - -# Deploy packaged SAM template -$ sam deploy --template-file ./packaged.yaml --stack-name mystack --capabilities CAPABILITY_IAM -``` - - -## Getting started - -* Check out [HOWTO Guide](HOWTO.md) section for more details - -## Advanced - -### Compiled Languages (Java) - -To use SAM Local with compiled languages, such as Java that require a packaged artifact (e.g. a JAR, or ZIP), you can specify the location of the artifact with the `AWS::Serverless::Function` `CodeUri` property in your SAM template. - -For example: - -``` -AWSTemplateFormatVersion: 2010-09-09 -Transform: AWS::Serverless-2016-10-31 - -Resources: - ExampleJavaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: com.example.HelloWorldHandler - CodeUri: ./target/HelloWorld-1.0.jar - Runtime: java8 -``` - -You should then build your JAR file using your normal build process. Please note that JAR files used with AWS Lambda should be a shaded JAR file (or uber jar) containing all of the function dependencies. - -``` -// Build the JAR file -$ mvn package shade:shade - -// Invoke with SAM Local -$ echo '{ "some": "input" }' | sam local invoke - -// Or start local API Gateway simulator -$ sam local start-api -``` - -You can find a full Java example in the [samples/java](samples/java) folder - -### IAM Credentials - -SAM Local will invoke functions with your locally configured IAM credentials. - -As with the AWS CLI and SDKs, SAM Local will look for credentials in the following order: - -1. Environment Variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`). -2. The AWS credentials file (located at `~/.aws/credentials` on Linux, macOS, or Unix, or at `C:\Users\USERNAME \.aws\credentials` on Windows). -3. Instance profile credentials (if running on Amazon EC2 with an assigned instance role). - -In order to test API Gateway with a non-default profile from your AWS credentials file append `--profile ` to the `start-api` command: - -``` -// Test API Gateway locally with a credential profile. -$ sam local start-api --profile some_profile -``` - -See this [Configuring the AWS CLI](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#config-settings-and-precedence) for more details. - -### Lambda Environment Variables -If your Lambda function uses environment variables, you can provide values for them will passed to the Docker container. Here is how you would do it: - -For example, consider the SAM template snippet: - -```yaml - -Resources: - MyFunction1: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - Environment: - Variables: - TABLE_NAME: prodtable - BUCKET_NAME: prodbucket - - MyFunction2: - Type: AWS::Serverless::Function - Properties: - Handler: app.handler - Runtime: nodejs4.3 - Environment: - Variables: - STAGE: prod - TABLE_NAME: prodtable - - - -``` - -#### Environment Variable file -Use `--env-vars` argument of `invoke` or `start-api` commands to provide a JSON file that contains values for environment variables defined in your function. The file should be structured as follows: - -```json -{ - "MyFunction1": { - "TABLE_NAME": "localtable", - "BUCKET_NAME": "testBucket" - }, - "MyFunction2": { - "TABLE_NAME": "localtable", - "STAGE": "dev" - }, -} - -``` - -```bash -$ sam local start-api --env-vars env.json -``` - -in alternative you can pass a cloudformation configuration.json containing a parameters key: - -```json -{ - "Parameters": { - "TABLE_NAME": "localtable", - "BUCKET_NAME": "testBucket" - } -} -``` - -#### Shell environment -Variables defined in your Shell's environment will be passed to the Docker container, if they map to a Variable in your Lambda function. Shell variables are globally applicable to functions ie. If two functions have a variable called `TABLE_NAME`, then the value for `TABLE_NAME` provided through Shell's environment will be availabe to both functions. - -Following command will make value of `mytable` available to both `MyFunction1` and `MyFunction2` - -```bash -$ TABLE_NAME=mytable sam local start-api -``` - -#### Combination of Shell and Environment Variable file -For greater control, you can use a combination shell variables and external environment variable file. If a variable is defined in both places, the one from the file will override the shell. Here is the order of priority, highest to lowest. Higher priority ones will override the lower. - -1. Environment Variable file -1. Shell's environment -1. Hard-coded values from the template - -### Identifying local execution from Lambda function code -When your Lambda function is invoked using SAM Local, it sets an environment variable `AWS_SAM_LOCAL=true` in the Docker container. Your Lambda function can use this property to enable or disable functionality that would not make sense in local development. For example: Disable emitting metrics to CloudWatch (or) Enable verbose logging etc. - -### Static Assets -Often, it's useful to serve up static assets (e.g CSS/HTML/Javascript etc) when developing a Serverless application. On AWS, this would normally be done with CloudFront/S3. SAM Local by default looks for a `./public/` directory in your SAM project directory and will serve up all files from it at the root of the HTTP server when using `sam local start-api`. You can override the default static asset directory by using the `-s` or `--static-dir` command line flag. You can also disable this behaviour completely by setting `--static-dir ""`. - -### Local Logging -Both `invoke` and `start-api` command allow you to pipe logs from the function's invocation into a file. This will be useful if you are running automated tests against SAM Local and want to capture logs for analysis. - -Example: -```bash -$ sam local invoke --log-file ./output.log -``` - - -### Remote Docker -Sam Local loads function code by mounting filesystem to a Docker Volume. As a result, The project directory must be pre-mounted on the remote host where the Docker is running. - -If mounted, you can use the remote docker normally using `--docker-volume-basedir` or environment variable `SAM_DOCKER_VOLUME_BASEDIR`. - -Example - Docker Toolbox (Windows): - -When you install and run Docker Toolbox, the Linux VM with Docker is automatically installed in the virtual box. - -The /c/ path for this Linux VM is automatically shared with C:\ on the host machine. -```powershell -sam local invoke --docker-volume-basedir /c/Users/shlee322/projects/test "Ratings" -``` - - -## Project Status - -* [ ] Supported AWS Lambda Runtimes - - [x] `nodejs` - - [x] `nodejs4.3` - - [x] `nodejs6.10` - - [x] `nodejs8.10` - - [x] `java8` - - [x] `python2.7` - - [x] `python3.6` - - [ ] `dotnetcore1.0` - - [x] `dotnetcore2.0` -* [x] AWS credential support -* [x] Debugging support -* [x] Inline Swagger support within SAM templates - -## Contributing - -Contributions and feedback are welcome! Proposals and pull requests will be considered and responded to. For more information, see the [CONTRIBUTING](CONTRIBUTING.md) file. - -## A special thank you - -SAM Local uses the open source [docker-lambda](https://github.com/lambci/docker-lambda) Docker images created by [@mhart](https://github.com/mhart). - -## Examples - -You can find sample functions code and a SAM template used in this README under the [samples] folder within this repo. - - -[SAM]: https://github.com/awslabs/serverless-application-model -[HOWTO]: HOWTO.md -[Releases]: https://github.com/awslabs/aws-sam-local/releases -[Samples]: https://github.com/awslabs/aws-sam-local/tree/master/samples - diff --git a/README.rst b/README.rst new file mode 100644 index 0000000000..65c4561250 --- /dev/null +++ b/README.rst @@ -0,0 +1,838 @@ +.. raw:: html + +

+ +.. raw:: html + +

+ +SAM CLI (Beta) +============== + +|Build Status| |Apache-2.0| |Contributers| |GitHub-release| |PyPI version| + +`Join the SAM developers channel (#samdev) on +Slack `__ to collaborate with +fellow community members and the AWS SAM team. + +**``sam``** is the AWS CLI tool for managing Serverless applications +written with `AWS Serverless Application Model +(SAM) `__. SAM +CLI can be used to test functions locally, start a local API Gateway +from a SAM template, validate a SAM template, generate sample payloads +for various event sources, and generate a SAM project in your favorite +Lambda Runtime. + +- `SAM CLI (Beta) <#sam-cli-beta>`__ + + - `Main features <#main-features>`__ + - `Installation <#installation>`__ + + - `Prerequisites <#prerequisites>`__ + - `Upgrade from 0.2.11 or Below <#upgrade-from-version-0-2-11-or-below>`__ + - `Windows, Linux, macOS with PIP + [Recommended] <#windows-linux-macos-with-pip-recommended>`__ + - `Build From Source <#build-from-source>`__ + - `Install with PyEnv <#install-with-pyenv>`__ + - `Troubleshooting <#troubleshooting>`__ + + - `Mac <#mac-issues>`__ + + - `Usage <#usage>`__ + + - `Invoke functions locally <#invoke-functions-locally>`__ + - `Generate sample event source + payloads <#generate-sample-event-source-payloads>`__ + - `Run API Gateway locally <#run-api-gateway-locally>`__ + - `Debugging Applications <#debugging-applications>`__ + + - `Debugging Python functions <#debugging-python-functions>`__ + + - `Validate SAM templates <#validate-sam-templates>`__ + - `Package and Deploy to + Lambda <#package-and-deploy-to-lambda>`__ + + - `Getting started <#getting-started>`__ + - `Advanced <#advanced>`__ + + - `Compiled Languages (Java) <#compiled-languages-java>`__ + - `IAM Credentials <#iam-credentials>`__ + - `Lambda Environment + Variables <#lambda-environment-variables>`__ + + - `Environment Variable file <#environment-variable-file>`__ + - `Shell environment <#shell-environment>`__ + - `Combination of Shell and Environment Variable + file <#combination-of-shell-and-environment-variable-file>`__ + + - `Identifying local execution from Lambda function + code <#identifying-local-execution-from-lambda-function-code>`__ + - `Static Assets <#static-assets>`__ + - `Local Logging <#local-logging>`__ + - `Remote Docker <#remote-docker>`__ + + - `Project Status <#project-status>`__ + - `Contributing <#contributing>`__ + - `A special thank you <#a-special-thank-you>`__ + - `Examples <#examples>`__ + +Main features +------------- + +- Develop and test your Lambda functions locally with ``sam local`` and + Docker +- Invoke functions from known event sources such as Amazon S3, Amazon + DynamoDB, Amazon Kinesis, etc. +- Start local API Gateway from a SAM template, and quickly iterate over + your functions with hot-reloading +- Validate SAM templates +- Get started with boilerplate Serverless Service in your chosen Lambda + Runtime ``sam init`` + +Installation +------------ + +Prerequisites +~~~~~~~~~~~~~ + +Running Serverless projects and functions locally with SAM CLI requires +Docker to be installed and running. SAM CLI will use the ``DOCKER_HOST`` +environment variable to contact the docker daemon. + +- macOS: `Docker for + Mac `__ +- Windows: `Docker + Toolbox `__ +- Linux: Check your distro’s package manager (e.g. yum install docker) + +For macOS and Windows users: SAM CLI requires that the project directory +(or any parent directory) is listed in Docker file sharing options. + +Verify that docker is working, and that you can run docker commands from +the CLI (e.g. ‘docker ps’). You do not need to install/fetch/pull any +containers – SAM CLI will do it automatically as required. + +Upgrade from Version 0.2.11 or Below +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Uninstall previous CLI Version + +.. code:: bash + + npm uninstall -g aws-sam-local + +To upgrade to Version 0.3.0 or above, follow instructions below: + +Windows, Linux, macOS with PIP [Recommended] +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Verify Python Version is 2.7. + +.. code:: bash + python --version + +The easiest way to install **``sam``** is to use +`PIP `__. + +.. code:: bash + + pip install --user aws-sam-cli + +Verify the installation worked: + +.. code:: bash + + sam --version + +Upgrading via pip +^^^^^^^^^^^^^^^^^ + +To update **``sam``** once installed via pip: + +.. code:: bash + + pip install --user --upgrade aws-sam-cli + +Build From Source +~~~~~~~~~~~~~~~~~ + +First, install Python(2.7) on your machine, then run the following: + +.. code:: bash + + # Clone the repository + $ git clone git@github.com:awslabs/aws-sam-cli.git + + # cd into the git + $ cd aws-sam-cli + + # pip install the repository + $ pip install --user -e . + +Install with PyEnv +~~~~~~~~~~~~~~~~~~ +.. code:: bash + + # Install PyEnv (https://github.com/pyenv/pyenv#installation) + $ brew update + $ brew install pyenv + + # Initialize pyenv using bash_profile + $ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi\nexport PATH="~/.pyenv/bin:$PATH"' >> ~/.bash_profile + # or using zshrc + $ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi\nexport PATH="~/.pyenv/bin:$PATH"' >> ~/.zshrc + + # restart the shell + $ exec "$SHELL" + + # Install Python 2.7 + $ pyenv install 2.7.14 + $ pyenv local 2.7.14 + + # Install the CLI + $ pip install --user aws-sam-cli + + # Verify your installation worked + $ sam –version + +Troubleshooting +~~~~~~~~~~~~~~~ + +Mac Issues +^^^^^^^^^^ + +1. **[Errno 13] Permission denied** If you had installed Python using + Homebrew, you might need to use ``sudo`` to install SAM CLI: + +.. code:: bash + + sudo pip install aws-sam-cli + +1. **TLSV1_ALERT_PROTOCOL_VERSION**: + +If you get an error something similar to: + +:: + + Could not fetch URL https://pypi.python.org/simple/click/: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version (_ssl.c:590) - skipping + +then you are probably using the default version of Python that came with +your Mac. This is outdated. So make sure you install Python again using +homebrew and try again: + +.. code:: bash + + brew install python@2 + +Followed by: + +.. code:: bash + + pip install --user aws-sam-cli + +Usage +----- + +**``sam``** requires a SAM template in order to know how to invoke your +function locally, and it’s also true for spawning API Gateway locally - +If no template is specified ``template.yaml`` will be used instead. + +You can find sample SAM templates either under **``samples``** located +in this repo or by visiting +`SAM `__ +official repository. + +Invoke functions locally +~~~~~~~~~~~~~~~~~~~~~~~~ + +.. figure:: media/sam-invoke.gif + :alt: SAM CLI Invoke Sample + + SAM CLI Invoke Sample + +You can invoke your function locally by passing its **SAM logical ID** +and an event file. Alternatively, ``sam local invoke`` accepts stdin as +an event too. + +.. code:: yaml + + Resources: + Ratings: # <-- Logical ID + Type: 'AWS::Serverless::Function' + ... + +**Syntax** + +.. code:: bash + + # Invoking function with event file + $ sam local invoke "Ratings" -e event.json + + # Invoking function with event via stdin + $ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" + + # For more options + $ sam local invoke --help + +Generate sample event source payloads +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To make local development and testing of Lambda functions easier, you +can generate mock/sample event payloads for the following services: + +- S3 +- Kinesis +- DynamoDB +- Cloudwatch Scheduled Event +- Cloudtrail +- API Gateway + +**Syntax** + +.. code:: bash + + sam local generate-event + +Also, you can invoke an individual lambda function locally from a sample +event payload - Here’s an example using S3: + +.. code:: bash + + sam local generate-event s3 --bucket --key | sam local invoke + +For more options, see ``sam local generate-event --help``. + +Run API Gateway locally +~~~~~~~~~~~~~~~~~~~~~~~ + +``sam local start-api`` spawns a local API Gateway to test HTTP +request/response functionality. Features hot-reloading to allow you to +quickly develop, and iterate over your functions. + +.. figure:: media/sam-start-api.gif + :alt: SAM CLI Start API + + SAM CLI Start API + +**Syntax** + +.. code:: bash + + sam local start-api + +**``sam``** will automatically find any functions within your SAM +template that have ``Api`` event sources defined, and mount them at the +defined HTTP paths. + +In the example below, the ``Ratings`` function would mount +``ratings.py:handler()`` at ``/ratings`` for ``GET`` requests. + +.. code:: yaml + + Ratings: + Type: AWS::Serverless::Function + Properties: + Handler: ratings.handler + Runtime: python3.6 + Events: + Api: + Type: Api + Properties: + Path: /ratings + Method: get + +By default, SAM uses `Proxy +Integration `__ +and expects the response from your Lambda function to include one or +more of the following: ``statusCode``, ``headers`` and/or ``body``. + +For example: + +.. code:: javascript + + // Example of a Proxy Integration response + exports.handler = (event, context, callback) => { + callback(null, { + statusCode: 200, + headers: { "x-custom-header" : "my custom header value" }, + body: "hello world" + }); + } + +For examples in other AWS Lambda languages, see `this +page `__. + +If your function does not return a valid `Proxy +Integration `__ +response then you will get a HTTP 500 (Internal Server Error) when +accessing your function. SAM CLI will also print the following error log +message to help you diagnose the problem: + +:: + + ERROR: Function ExampleFunction returned an invalid response (must include one of: body, headers or statusCode in the response object) + +Debugging Applications +~~~~~~~~~~~~~~~~~~~~~~ + +Both ``sam local invoke`` and ``sam local start-api`` support local +debugging of your functions. + +To run SAM Local with debugging support enabled, just specify +``--debug-port`` or ``-d`` on the command line. + +.. code:: bash + + # Invoke a function locally in debug mode on port 5858 + $ sam local invoke -d 5858 + + # Start local API Gateway in debug mode on port 5858 + $ sam local start-api -d 5858 + +Note: If using ``sam local start-api``, the local API Gateway will +expose all of your Lambda functions but, since you can specify a single +debug port, you can only debug one function at a time. You will need to +hit your API before SAM CLI binds to the port allowing the debugger to +connect. + +Here is an example showing how to debug a NodeJS function with Microsoft +Visual Studio Code: + +.. figure:: media/sam-debug.gif + :alt: SAM Local debugging example + + SAM Local debugging example + +In order to setup Visual Studio Code for debugging with AWS SAM CLI, use +the following launch configuration: + +:: + + { + "version": "0.2.0", + "configurations": [ + { + "name": "Attach to SAM Local", + "type": "node", + "request": "attach", + "address": "localhost", + "port": 5858, + "localRoot": "${workspaceRoot}", + "remoteRoot": "/var/task", + "protocol": "legacy" + } + ] + } + +Note: Node.js versions **below** 7 (e.g. Node.js 4.3 and Node.js 6.10) +use the ``legacy`` protocol, while Node.js versions including and above +7 (e.g. Node.js 8.10) use the ``inspector`` protocol. Be sure to specify +the corresponding protocol in the ``protocol`` entry of your launch +configuration. + +Debugging Python functions +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Unlike Node.JS and Java, Python requires you to enable remote debugging +in your Lambda function code. If you enable debugging with +``--debug-port`` or ``-d`` for a function that uses one of the Python +runtimes, SAM CLI will just map through that port from your host machine +through to the Lambda runtime container. You will need to enable remote +debugging in your function code. To do this, use a python package such +as `remote-pdb `__. When +configuring the host the debugger listens on in your code, make sure to +use ``0.0.0.0`` not ``127.0.0.1`` to allow Docker to map through the +port to your host machine. + + Please note, due to a `open + bug `__ with + Visual Studio Code, you may get a + ``Debug adapter process has terminated unexpectedly`` error when + attempting to debug Python applications with this IDE. Please track + the `GitHub + issue `__ for + updates. + +Passing Additional Runtime Debug Arguments +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +To pass additional runtime arguments when debugging your function, use +the environment variable ``DEBUGGER_ARGUMENTS``. This will pass a string +of arguments directly into the run command SAM CLI uses to start your +function. + +For example, if you want to load a debugger like iKPdb at runtime of +your Python function, you could pass the following as +``DEBUGGER_ARGUMENTS``: +``-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0``. +This would load iKPdb at runtime with the other arguments you’ve +specified. In this case, your full SAM CLI command would be: + +.. code:: bash + + $ DEBUGGER_ARGUMENTS="-m ikpdb --ikpdb-port=5858 --ikpdb-working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-address=0.0.0.0" echo {} | sam local invoke -d 5858 myFunction + +You may pass debugger arguments to functions of all runtimes. + +Connecting to docker network +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Both ``sam local invoke`` and ``sam local start-api`` support connecting +the create lambda docker containers to an existing docker network. + +To connect the containers to an existing docker network, you can use the +``--docker-network`` command-line argument or the ``SAM_DOCKER_NETWORK`` +environment variable along with the name or id of the docker network you +wish to connect to. + +.. code:: bash + + # Invoke a function locally and connect to a docker network + $ sam local invoke --docker-network my-custom-network + + # Start local API Gateway and connect all containers to a docker network + $ sam local start-api --docker-network b91847306671 -d 5858 + +Validate SAM templates +~~~~~~~~~~~~~~~~~~~~~~ + +Validate your templates with ``$ sam validate``. Currently this command +will validate that the template provided is valid JSON / YAML. As with +most SAM CLI commands, it will look for a ``template.[yaml|yml]`` file +in your current working directory by default. You can specify a +different template file/location with the ``-t`` or ``--template`` +option. + +**Syntax** + +.. code:: bash + + $ sam validate + /template.yml is a valid SAM Template + +Note: The validate command requires AWS credentials to be configured. See IAMCreds_. + +Package and Deploy to Lambda +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Once you have developed and tested your Serverless application locally, +you can deploy to Lambda using ``sam package`` and ``sam deploy`` +command. ``package`` command will zip your code artifacts, upload to S3 +and produce a SAM file that is ready to be deployed to Lambda using AWS +CloudFormation. ``deploy`` command will deploy the packaged SAM template +to CloudFormation. Both ``sam package`` and ``sam deploy`` are identical +to their AWS CLI equivalents commands +```aws cloudformation package`` `__ +and +```aws cloudformation deploy`` `__ +respectively. Please consult the AWS CLI command documentation for +usage. + +Example: + +.. code:: bash + + # Package SAM template + $ sam package --template-file sam.yaml --s3-bucket mybucket --output-template-file packaged.yaml + + # Deploy packaged SAM template + $ sam deploy --template-file ./packaged.yaml --stack-name mystack --capabilities CAPABILITY_IAM + +Getting started +--------------- + +- Check out `HOWTO Guide `__ section for more details + +Advanced +-------- + +Compiled Languages (Java) +~~~~~~~~~~~~~~~~~~~~~~~~~ + +To use SAM CLI with compiled languages, such as Java that require a +packaged artifact (e.g. a JAR, or ZIP), you can specify the location of +the artifact with the ``AWS::Serverless::Function`` ``CodeUri`` property +in your SAM template. + +For example: + +:: + + AWSTemplateFormatVersion: 2010-09-09 + Transform: AWS::Serverless-2016-10-31 + + Resources: + ExampleJavaFunction: + Type: AWS::Serverless::Function + Properties: + Handler: com.example.HelloWorldHandler + CodeUri: ./target/HelloWorld-1.0.jar + Runtime: java8 + +You should then build your JAR file using your normal build process. +Please note that JAR files used with AWS Lambda should be a shaded JAR +file (or uber jar) containing all of the function dependencies. + +:: + + // Build the JAR file + $ mvn package shade:shade + + // Invoke with SAM Local + $ echo '{ "some": "input" }' | sam local invoke + + // Or start local API Gateway simulator + $ sam local start-api + +You can find a full Java example in the `samples/java `__ +folder + +.. _IAMCreds + +IAM Credentials +~~~~~~~~~~~~~~~ + +SAM CLI will invoke functions with your locally configured IAM +credentials. + +As with the AWS CLI and SDKs, SAM CLI will look for credentials in the +following order: + +1. Environment Variables (``AWS_ACCESS_KEY_ID``, + ``AWS_SECRET_ACCESS_KEY``). +2. The AWS credentials file (located at ``~/.aws/credentials`` on Linux, + macOS, or Unix, or at ``C:\Users\USERNAME \.aws\credentials`` on + Windows). +3. Instance profile credentials (if running on Amazon EC2 with an + assigned instance role). + +In order to test API Gateway with a non-default profile from your AWS +credentials file append ``--profile `` to the +``start-api`` command: + +:: + + // Test API Gateway locally with a credential profile. + $ sam local start-api --profile some_profile + +See this `Configuring the AWS +CLI `__ +for more details. + +Lambda Environment Variables +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If your Lambda function uses environment variables, you can provide +values for them will passed to the Docker container. Here is how you +would do it: + +For example, consider the SAM template snippet: + +.. code:: yaml + + + Resources: + MyFunction1: + Type: AWS::Serverless::Function + Properties: + Handler: index.handler + Runtime: nodejs4.3 + Environment: + Variables: + TABLE_NAME: prodtable + BUCKET_NAME: prodbucket + + MyFunction2: + Type: AWS::Serverless::Function + Properties: + Handler: app.handler + Runtime: nodejs4.3 + Environment: + Variables: + STAGE: prod + TABLE_NAME: prodtable + + +Environment Variable file +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Use ``--env-vars`` argument of ``invoke`` or ``start-api`` commands to +provide a JSON file that contains values for environment variables +defined in your function. The file should be structured as follows: + +.. code:: json + + { + "MyFunction1": { + "TABLE_NAME": "localtable", + "BUCKET_NAME": "testBucket" + }, + "MyFunction2": { + "TABLE_NAME": "localtable", + "STAGE": "dev" + }, + } + +.. code:: bash + + $ sam local start-api --env-vars env.json + + +Shell environment +^^^^^^^^^^^^^^^^^ + +Variables defined in your Shell’s environment will be passed to the +Docker container, if they map to a Variable in your Lambda function. +Shell variables are globally applicable to functions ie. If two +functions have a variable called ``TABLE_NAME``, then the value for +``TABLE_NAME`` provided through Shell’s environment will be availabe to +both functions. + +Following command will make value of ``mytable`` available to both +``MyFunction1`` and ``MyFunction2`` + +.. code:: bash + + $ TABLE_NAME=mytable sam local start-api + +Combination of Shell and Environment Variable file +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For greater control, you can use a combination shell variables and +external environment variable file. If a variable is defined in both +places, the one from the file will override the shell. Here is the order +of priority, highest to lowest. Higher priority ones will override the +lower. + +1. Environment Variable file +2. Shell’s environment +3. Hard-coded values from the template + +Identifying local execution from Lambda function code +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When your Lambda function is invoked using SAM CLI, it sets an +environment variable ``AWS_SAM_LOCAL=true`` in the Docker container. +Your Lambda function can use this property to enable or disable +functionality that would not make sense in local development. For +example: Disable emitting metrics to CloudWatch (or) Enable verbose +logging etc. + +Static Assets +~~~~~~~~~~~~~ + +Often, it’s useful to serve up static assets (e.g CSS/HTML/Javascript +etc) when developing a Serverless application. On AWS, this would +normally be done with CloudFront/S3. SAM CLI by default looks for a +``./public/`` directory in your SAM project directory and will serve up +all files from it at the root of the HTTP server when using +``sam local start-api``. You can override the default static asset +directory by using the ``-s`` or ``--static-dir`` command line flag. You +can also disable this behaviour completely by setting +``--static-dir ""``. + +Local Logging +~~~~~~~~~~~~~ + +Both ``invoke`` and ``start-api`` command allow you to pipe logs from +the function’s invocation into a file. This will be useful if you are +running automated tests against SAM CLI and want to capture logs for +analysis. + +Example: + +.. code:: bash + + $ sam local invoke --log-file ./output.log + +Remote Docker +~~~~~~~~~~~~~ + +Sam CLI loads function code by mounting filesystem to a Docker Volume. +As a result, The project directory must be pre-mounted on the remote +host where the Docker is running. + +If mounted, you can use the remote docker normally using +``--docker-volume-basedir`` or environment variable +``SAM_DOCKER_VOLUME_BASEDIR``. + +Example - Docker Toolbox (Windows): + +When you install and run Docker Toolbox, the Linux VM with Docker is +automatically installed in the virtual box. + +The /c/ path for this Linux VM is automatically shared with C: on the +host machine. + +.. code:: powershell + + sam local invoke --docker-volume-basedir /c/Users/shlee322/projects/test "Ratings" + +Project Status +-------------- + +- [ ] Python Versions support + + - [x] Python 2.7 + - [ ] Python 3.6 + +- [ ] Supported AWS Lambda Runtimes + + - [x] ``nodejs`` + - [x] ``nodejs4.3`` + - [x] ``nodejs6.10`` + - [x] ``nodejs8.10`` + - [x] ``java8`` + - [x] ``python2.7`` + - [x] ``python3.6`` + - [ ] ``dotnetcore1.0`` + - [x] ``dotnetcore2.0`` + +- [x] AWS credential support +- [x] Debugging support +- [x] Inline Swagger support within SAM templates +- [x] Validating SAM templates locally +- [x] Generating boilerplate templates + + - [x] ``nodejs`` + - [x] ``nodejs4.3`` + - [x] ``nodejs6.10`` + - [x] ``nodejs8.10`` + - [x] ``java8`` + - [x] ``python2.7`` + - [x] ``python3.6`` + - [x] ``dotnetcore1.0`` + - [x] ``dotnetcore2.0`` + +Contributing +------------ + +Contributions and feedback are welcome! Proposals and pull requests will +be considered and responded to. For more information, see the +`CONTRIBUTING `__ file. + +A special thank you +------------------- + +SAM CLI uses the open source +`docker-lambda `__ Docker +images created by [@mhart](https://github.com/mhart). + +Examples +-------- + +You can find sample functions code and a SAM template used in this +README under the +`samples `__ +folder within this repo. + +.. raw:: html + + + +.. |Build Status| image:: https://travis-ci.org/awslabs/aws-sam-local.svg?branch=develop +.. |Apache-2.0| image:: https://img.shields.io/npm/l/aws-sam-local.svg?maxAge=2592000 +.. |Contributers| image:: https://img.shields.io/github/contributors/awslabs/aws-sam-local.svg?maxAge=2592000 +.. |GitHub-release| image:: https://img.shields.io/github/release/awslabs/aws-sam-local.svg?maxAge=2592000 +.. |PyPI version| image:: https://badge.fury.io/py/aws-sam-cli.svg + diff --git a/aws_sam_local_suite_test.go b/aws_sam_local_suite_test.go deleted file mode 100644 index d3f10ba96a..0000000000 --- a/aws_sam_local_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package main - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestAwsSamLocal(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "AwsSamLocal Suite") -} diff --git a/convert.go b/convert.go deleted file mode 100644 index 1affe019d5..0000000000 --- a/convert.go +++ /dev/null @@ -1,86 +0,0 @@ -package main - -import ( - "regexp" - "strings" - - "github.com/awslabs/goformation/cloudformation" -) - -// addCloudformationLambdaFunctions converts all Cloudformation Lambda functions to Serverless functions. On name collisions, existing -// serverless functions are preserved. -func addCloudformationLambdaFunctions(template *cloudformation.Template, functions map[string]cloudformation.AWSServerlessFunction) { - // convert all lambda functions to serverless functions so that invoke works for them - for n, f := range template.GetAllAWSLambdaFunctionResources() { - if _, found := functions[n]; !found { - functions[n] = lambdaToServerless(f) - } - } -} - -// dlqTypeEx is used to extract the DLQ type from an ARN -var dlqTypeEx = regexp.MustCompile(`^arn:aws(?:-[\\w]+)*:(sns|sqs):([a-zA-Z_0-9+=,.@\-/:]+)$`) - -// lambdaToServerless converts a Cloudformation lambda to its Serverless counterpart. The conversion makes the following assumptions: -// * codeUri is set to nil in order to use the local code and not the remote one -// * no events are associated with the serverless function -// * no policies are added because a role is already specified -func lambdaToServerless(lambda cloudformation.AWSLambdaFunction) (serverless cloudformation.AWSServerlessFunction) { - // serverless policies are not needed because lambdas have a role - serverless.Policies = nil - - // no events are associated with the function - serverless.Events = nil - - // codeUri is set to nil in order to get the code locally and not from a remote source - serverless.CodeUri = nil - - serverless.FunctionName = lambda.FunctionName - serverless.Description = lambda.Description - serverless.Handler = lambda.Handler - serverless.Timeout = lambda.Timeout - serverless.KmsKeyArn = lambda.KmsKeyArn - serverless.Role = lambda.Role - serverless.Runtime = lambda.Runtime - serverless.MemorySize = lambda.MemorySize - - if lambda.DeadLetterConfig != nil { - dlqType := "SQS" - match := dlqTypeEx.FindAllStringSubmatch(lambda.DeadLetterConfig.TargetArn, -1) - if len(match) > 0 { - dlqType = match[0][1] - } - - serverless.DeadLetterQueue = &cloudformation.AWSServerlessFunction_DeadLetterQueue{ - TargetArn: lambda.DeadLetterConfig.TargetArn, - Type: strings.ToUpper(dlqType), - } - } - - if len(lambda.Tags) > 0 { - tags := make(map[string]string) - for _, t := range lambda.Tags { - tags[t.Key] = t.Value - } - serverless.Tags = tags - } - - if lambda.TracingConfig != nil { - serverless.Tracing = lambda.TracingConfig.Mode - } - - if lambda.Environment != nil { - serverless.Environment = &cloudformation.AWSServerlessFunction_FunctionEnvironment{ - Variables: lambda.Environment.Variables, - } - } - - if lambda.VpcConfig != nil { - serverless.VpcConfig = &cloudformation.AWSServerlessFunction_VpcConfig{ - SecurityGroupIds: lambda.VpcConfig.SecurityGroupIds, - SubnetIds: lambda.VpcConfig.SubnetIds, - } - } - - return -} diff --git a/convert_test.go b/convert_test.go deleted file mode 100644 index 3a6810cfb6..0000000000 --- a/convert_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package main - -import ( - "github.com/awslabs/goformation" - "github.com/awslabs/goformation/cloudformation" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Convert Cloudformation Lambda functions to Serverless", func() { - - Context("with normal input", func() { - - It("converts an empty function", func() { - f := cloudformation.AWSLambdaFunction{} - expected := cloudformation.AWSServerlessFunction{} - Expect(lambdaToServerless(f)).To(Equal(expected)) - }) - - It("converts a function", func() { - f := cloudformation.AWSLambdaFunction{ - FunctionName: "foo", - Description: "desc", - Handler: "index.js", - Timeout: 30, - Runtime: "nodejs6.10", - MemorySize: 300, - Role: "arn:aws:iam::123456789012:role/S3Access", - KmsKeyArn: "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012", - DeadLetterConfig: &cloudformation.AWSLambdaFunction_DeadLetterConfig{ - TargetArn: "arn:aws:sns:us-east-1:123456789012:my_corporate_topic:02034b43-fefa-4e07-a5eb-3be56f8c54ce", - }, - Tags: []cloudformation.Tag{{Key: "key", Value: "value"}}, - TracingConfig: &cloudformation.AWSLambdaFunction_TracingConfig{ - Mode: "PassThrough", - }, - Environment: &cloudformation.AWSLambdaFunction_Environment{ - Variables: map[string]string{"k1": "v1"}, - }, - VpcConfig: &cloudformation.AWSLambdaFunction_VpcConfig{ - SecurityGroupIds: []string{"sg-edcd9784"}, - SubnetIds: []string{"subnet"}, - }, - } - expected := cloudformation.AWSServerlessFunction{ - CodeUri: nil, - Events: nil, - Policies: nil, - FunctionName: "foo", - Description: "desc", - Handler: "index.js", - Timeout: 30, - Runtime: "nodejs6.10", - MemorySize: 300, - Role: "arn:aws:iam::123456789012:role/S3Access", - KmsKeyArn: "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012", - DeadLetterQueue: &cloudformation.AWSServerlessFunction_DeadLetterQueue{ - TargetArn: "arn:aws:sns:us-east-1:123456789012:my_corporate_topic:02034b43-fefa-4e07-a5eb-3be56f8c54ce", - Type: "SNS", - }, - Tags: map[string]string{"key": "value"}, - Tracing: "PassThrough", - Environment: &cloudformation.AWSServerlessFunction_FunctionEnvironment{ - Variables: map[string]string{"k1": "v1"}, - }, - VpcConfig: &cloudformation.AWSServerlessFunction_VpcConfig{ - SecurityGroupIds: []string{"sg-edcd9784"}, - SubnetIds: []string{"subnet"}, - }, - } - - Expect(lambdaToServerless(f)).To(Equal(expected)) - }) - - }) - - Context("with existing template", func() { - - functions := map[string]cloudformation.AWSServerlessFunction{ - "ExistingFunction": cloudformation.AWSServerlessFunction{}, - } - const input = `{ - "Resources": { - "ExistingFunction": { - "Type": "AWS::Lambda::Function", - "Properties": { - "FunctionName": "ExistingFunction", - "Handler": "com.foo.bar.Dispatcher::handleRequest" - } - }, - "Func1": { - "Type": "AWS::Lambda::Function", - "Properties": { - "FunctionName": "Func1", - "Handler": "com.foo.bar.Dispatcher::handleRequest" - } - } - } - }` - - template, err := goformation.ParseJSON([]byte(input)) - - It("parses correctly", func() { - Expect(err).To(BeNil()) - Expect(template).To(Not(BeNil())) - lambdas := template.GetAllAWSLambdaFunctionResources() - Expect(lambdas).To(HaveLen(2)) - Expect(lambdas).To(HaveKey("Func1")) - Expect(lambdas).To(HaveKey("ExistingFunction")) - }) - - if template != nil { - addCloudformationLambdaFunctions(template, functions) - } - - It("adds lambda functions that don't clash", func() { - Expect(functions).To(HaveLen(2)) - Expect(functions).To(HaveKey("Func1")) - Expect(functions).To(HaveKey("ExistingFunction")) - }) - - It("ignores lambda functions which already exist", func() { - Expect(functions).To(HaveKeyWithValue("ExistingFunction", Equal(cloudformation.AWSServerlessFunction{}))) - }) - - }) -}) diff --git a/deploy.go b/deploy.go deleted file mode 100644 index 3619686c8f..0000000000 --- a/deploy.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "io" - "log" - "os" - "os/exec" -) - -func deploy() { - - args := []string{"cloudformation", "deploy"} - for _, arg := range os.Args[2:] { - args = append(args, arg) - } - - cmd := exec.Command("aws", args...) - - stderr, err := cmd.StderrPipe() - if err != nil { - log.Fatal(err) - } - - stdout, err := cmd.StdoutPipe() - if err != nil { - log.Fatal(err) - } - - if err := cmd.Start(); err != nil { - log.Fatal(err) - } - - go io.Copy(os.Stderr, stderr) - go io.Copy(os.Stdout, stdout) - - if err := cmd.Wait(); err != nil { - os.Exit(1) - } -} diff --git a/distribution/npm/npm-release.sh b/distribution/npm/npm-release.sh deleted file mode 100755 index 0f7cf382e3..0000000000 --- a/distribution/npm/npm-release.sh +++ /dev/null @@ -1,44 +0,0 @@ -# Set NPM_TOKEN environment variable to the User's token before running the script -# -# USAGE: ./npm-release.sh -# Picks up the version from latest tag - -VERSION=`git describe --abbrev=0 --tags` -VERSION="${VERSION:1:${#VERSION}}" # Remove starting 'v' v0.0.1 => 0.0.1 -PACKAGE=./package.json -BACKUP=./package.json.bck - -PKG_ROOT=`pwd` -NPM_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -cd $NPM_DIR - -# Add Readme to NPM package to show in NPM Package's webpage -cp $PKG_ROOT/README.md $NPM_DIR - -# 1. Replace __VERSION__ from package.json with version tag passed as first argument -cp $PACKAGE $BACKUP -sed -i '' -e "s/__VERSION__/$VERSION/g" $PACKAGE - -# Make sure the replace actually happened -grep __VERSION__ $PACKAGE -if [ $? -eq 0 ] -then - echo "Replacing __VERSION__ in $PACKAGE was unsuccessful" - cat $PACKAGE - exit 1 -fi - -# 2. Generated package.json should be published to NPM -npm publish ./ - -if [ $? -ne 0 ] -then - echo "ERROR publishing to npm" - exit 1 -fi - -# Restore package.json file -mv $BACKUP $PACKAGE -rm $NPM_DIR/README.md -echo "Successfully published NPM for version $VERSION" -exit 0 diff --git a/distribution/npm/package.json b/distribution/npm/package.json deleted file mode 100644 index d1bae674b7..0000000000 --- a/distribution/npm/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name":"aws-sam-local", - "version":"__VERSION__", - "description":"Built binaries for AWS SAM Local CLI - https://github.com/awslabs/aws-sam-local", - "main":"index.js", - "dependencies":{ - "go-npm":"^0.1.8" - }, - "scripts":{ - "postinstall":"go-npm install", - "preuninstall":"go-npm uninstall" - }, - "goBinary":{ - "name":"sam", - "path":"./bin", - "url":"https://github.com/awslabs/aws-sam-local/releases/download/v{{version}}/sam_{{version}}_{{platform}}_{{arch}}.tar.gz" - }, - "preferGlobal":"true", - "license":"Apache-2.0", - "repository":{ - "type":"git", - "url":"https://github.com/awslabs/aws-sam-local.git" - }, - "bugs":{ - "url":"https://github.com/awslabs/aws-sam-local/issues" - }, - "homepage":"https://github.com/awslabs/aws-sam-local#readme" -} diff --git a/vendor/github.com/docker/go-connections/sockets/README.md b/docs/.gitkeep similarity index 100% rename from vendor/github.com/docker/go-connections/sockets/README.md rename to docs/.gitkeep diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000000..0d692e8b5c --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = SAMCLI +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000000..74ad42a370 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# SAM CLI documentation build configuration file, created by +# sphinx-quickstart on Fri Apr 27 12:48:05 2018. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'SAM CLI' +copyright = '2018, AWS SAM' +author = 'AWS SAM' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '' +# The full version, including alpha/beta/rc tags. +release = '' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# This is required for the alabaster theme +# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars +html_sidebars = { + '**': [ + 'relations.html', # needs 'show_related': True theme option to display + 'searchbox.html', + ] +} + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'SAMCLIdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'SAMCLI.tex', 'SAM CLI Documentation', + 'AWS SAM', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'samcli', 'SAM CLI Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'SAMCLI', 'SAM CLI Documentation', + author, 'SAMCLI', 'One line description of project.', + 'Miscellaneous'), +] + + + diff --git a/docs/deploying_serverless_applications.rst b/docs/deploying_serverless_applications.rst new file mode 100644 index 0000000000..92eab4fd82 --- /dev/null +++ b/docs/deploying_serverless_applications.rst @@ -0,0 +1,48 @@ +Once you have created a Lambda function and a template.yaml file, you can use the AWS CLI to package and deploy your serverless application. + +Packaging and deploying your application +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In order to complete the procedures below, you need to first complete the following: + + `Set up an AWS Account `__. + + `Set up the AWS CLI `__ . + +Packaging your application +~~~~~~~~~~~~~~~~~~~~~~~~~~ +To package your application, create an Amazon S3 bucket that the package command will use to upload your ZIP deployment package (if you haven't specified one in your example.yaml file). You can use the following command to create the Amazon S3 bucket: + +.. code:: bash + + aws s3 mb s3://bucket-name --region + +Next, open a command prompt and type the following: + +.. code:: bash + + sam package \ + --template-file file path/template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket s3-bucket-name + +The package command returns an AWS SAM template named serverless-output.yaml that contains the CodeUri that points to the deployment zip in the Amazon S3 bucket that you specified. This template represents your serverless application. You are now ready to deploy it. + +Deploying your application +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To deploy the application, run the following command: + +.. code:: bash + + sam deploy \ + --template-file serverless-template.yaml \ + --stack-name new-stack-name \ + --capabilities CAPABILITY_IAM + +Note that the value you specify for the --template-file parameter is the name of the SAM template that was returned by the package command. In addition, the --capabilities parameter is optional. The AWS::Serverless::Function resource will implicitly create a role to execute the Lambda function if one is not specified in the template. You use the --capabilities parameter to explicitly acknowledge that AWS CloudFormation is allowed to create roles on your behalf. + +When you run the aws sam deploy command, it creates an AWS CloudFormation ChangeSet, which is a list of changes to the AWS CloudFormation stack, and then deploys it. Some stack templates might include resources that can affect permissions in your AWS account, for example, by creating new AWS Identity and Access Management (IAM) users. For those stacks, you must explicitly acknowledge their capabilities by specifying the --capabilities parameter. + +To verify your results, open the AWS CloudFormation console to view the newly created AWS CloudFormation stack and the Lambda console to view your function. + diff --git a/docs/getting_started.rst b/docs/getting_started.rst new file mode 100644 index 0000000000..d90c07461e --- /dev/null +++ b/docs/getting_started.rst @@ -0,0 +1,58 @@ +Getting started with SAM and the SAM CLI +======================================== +The following sections introduce the Serverless Application Model (SAM) and the the tools available to implement it (SAM CLI): + +What is SAM +=========== +The AWS Serverless Application Model (AWS SAM) is a model to define serverless applications. AWS SAM is natively supported by AWS CloudFormation and defines simplified syntax for expressing serverless resources. The specification currently covers APIs, Lambda functions and Amazon DynamoDB tables. SAM is available under Apache 2.0 for AWS partners and customers to adopt and extend within their own toolsets. + +What is SAM CLI +=============== +Based on AWS SAM, SAM CLI is an AWS CLI tool that provides an environment for you to develop, test, and analyze your serverless applications locally before uploading them to the Lambda runtime. Whether you're developing on Linux, Mac, or Microsoft Windows, you can use SAM CLI to create a local testing environment that simulates the AWS runtime environment. The SAM CLI also allows faster, iterative development of your Lambda function code because there is no need to redeploy your application package to the AWS Lambda runtime. + + +Installing Docker +~~~~~~~~~~~~~~~~~ + +To use SAM CLI, you first need to install Docker, an open-source software container platform that allows you to build, manage and test applications, whether you're running on Linux, Mac or Windows. For more information and download instructions, see `Docker `__. + +Once you have Docker installed, SAM CLI automatically provides a customized Docker image called docker-lambda. This image is designed specifically by an AWS partner to simulate the live AWS Lambda execution environment. This environment includes installed software, libraries, security permissions, environment variables, and other features outlined at Lambda Execution Environment and Available Libraries. + +Using docker-lambda, you can invoke your Lambda function locally. In this environment, your serverless applications execute and perform much as in the AWS Lambda runtime, without your having to redeploy the runtime. Their execution and performance in this environment reflect such considerations as timeouts and memory use. + + Important + + Because this is a simulated environment, there is no guarantee that your local testing results will exactly match those in the actual AWS runtime. +For more information, see `docker-lambda `__. + +Installing SAM CLI +~~~~~~~~~~~~~~~~~~ + +The easiest way to install SAM CLI is to use `pip `__. + +.. code:: bash + + pip install aws-sam-cli + +Then verify that the installation succeeded. + +.. code:: bash + + sam --version + +If pip doesn't work for you, you can download the latest binary and start using SAM CLI immediately. You can find the binaries under the Releases section in the `SAM CLI GitHub Repository `__. + +Creating a hello-world app (init) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +To get started with a project in SAM, you can use the 'sam init' command provided by the SAM CLI to get a fully deployable boilerplate serverless application in any of the supported runtimes. SAM init provides a quick way for customers to get started with creating a Lambda-based application and allow them to grow their idea into a production application by using other commands in the SAM CLI. + +To use 'sam init', nagivate to a directory where where you want the serverless application to be created. Using the SAM CLI, run the following command (using the runtime of your choice. The following example uses Python for demonstration purposes.): + +.. code:: + + $ sam init --runtime python + [+] Initializing project structure... + [SUCCESS] - Read sam-app/README.md for further instructions on how to proceed + [*] Project initialization is now complete +This will create a folder in the current directory titled sam-app. This folder will contain an `AWS SAM template `__, along with your function code file and a README file that provides further guidance on how to proceed with your SAM application. The SAM template defines the AWS Resources that your application will need to run in the AWS Cloud. + diff --git a/docs/make.bat b/docs/make.bat new file mode 100644 index 0000000000..95f33dc2ee --- /dev/null +++ b/docs/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=SAMCLI + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/docs/running_and_debugging_serverless_applications_locally.rst b/docs/running_and_debugging_serverless_applications_locally.rst new file mode 100644 index 0000000000..ccfb8de5b2 --- /dev/null +++ b/docs/running_and_debugging_serverless_applications_locally.rst @@ -0,0 +1,113 @@ +Running and debugging serverless applications locally +===================================================== +SAM CLI works with AWS SAM, allowing you to invoke functions defined in SAM templates, whether directly or through API Gateway endpoints. By using SAM CLI, you can analyze your SAM application's performance in your own testing environment and update accordingly. + +Invoking Lambda functions locally +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: bash + + # Invoking function with event file + + $ echo '{"message": "Hey, are you there?" }' | sam local invoke "Ratings" + + # For more options + + $ sam local invoke --help + + +Running API Gateway Locally +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +start-api: Creates a local HTTP server hosting all of your Lambda functions. When accessed by using a browser or the CLI, this operation launches a Docker container locally to invoke your function. It reads the CodeUri property of the AWS::Serverless::Function resource to find the path in your file system containing the Lambda function code. This path can be the project's root directory for interpreted languages like Node.js or Python, a build directory that stores your compiled artifacts, or for Java, a .jar file. + +If you use an interpreted language, local changes are made available within the same Docker container. This approach means you can reinvoke your Lambda function with no need for redeployment. + +invoke: Invokes a local Lambda function once and terminates after invocation completes. + +.. code:: + + $ sam local start-api + + 2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/ [GET] + 2018-05-08 08:48:38 Mounting HelloWorld at http://127.0.0.1:3000/thumbnail [GET] + 2018-05-08 08:48:38 You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template + 2018-05-08 08:48:38 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) + +Debugging With SAM CLI +~~~~~~~~~~~~~~~~~~~~~~ + +Both sam local invoke and sam local start-api support local debugging of your functions. To run SAM CLI with debugging support enabled, specify --debug-port or -d on the command line. + +.. code:: bash + + # Invoke a function locally in debug mode on port 5858 + + $ sam local invoke -d 5858 function logical id + + # Start local API Gateway in debug mode on port 5858 + + $ sam local start-api -d 5858 + +If you use sam local start-api, the local API Gateway exposes all of your Lambda functions. But because you can specify only one debug port, you can only debug one function at a time. + +Connecting a Debugger to your IDE +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +For compiled languages or projects requiring complex packing support, we recommend that you run your own build solution and point AWS SAM to the directory that contains the build dependency files needed. You can use the following IDEs or one of your choosing. + +- Cloud9 +- Eclipse +- Visual Studio Code + +Integrating other services +~~~~~~~~~~~~~~~~~~~~~~~~~~ +You can use the AWS Serverless Application Model to integrate other services as event sources to your application. For example, assume you have an application that requires a Dynamo DB table. The following shows an example: + +.. code:: yaml + + AWSTemplateFormatVersion: '2010-09-09' + Transform: AWS::Serverless-2016-10-31 + Resources: + ProcessDynamoDBStream: + Type: AWS::Serverless::Function + Properties: + Handler: handler + Runtime: runtime + Policies: AWSLambdaDynamoDBExecutionRole + Events: + Stream: + Type: DynamoDB + Properties: + Stream: !GetAtt DynamoDBTable.StreamArn + BatchSize: 100 + StartingPosition: TRIM_HORIZON + + DynamoDBTable: + Type: AWS::DynamoDB::Table + Properties: + AttributeDefinitions: + - AttributeName: id + AttributeType: S + KeySchema: + - AttributeName: id + KeyType: HASH + ProvisionedThroughput: + ReadCapacityUnits: 5 + WriteCapacityUnits: 5 + StreamSpecification: + StreamViewType: NEW_IMAGE + +Validate your SAM template +~~~~~~~~~~~~~~~~~~~~~~~~~~ +You can use SAM CLI to validate your template against the official AWS Serverless Application Model specification. The following is an example if you specify either an unsupported runtime or deprecated runtime version. + +.. code:: + + $ sam validate + + Error: Invalid Serverless Application Specification document. Number of errors found: 1. Resource with id [SkillFunction] is invalid. property Runtim not defined for resource of type AWS::Serverless::Function + + $ sed -i 's/Runtim/Runtime/g` template.yaml + + $ sam validate + template.yaml is a valid SAM Template + diff --git a/env.go b/env.go deleted file mode 100644 index 3b9ed18df9..0000000000 --- a/env.go +++ /dev/null @@ -1,197 +0,0 @@ -package main - -import ( - "encoding/json" - "io/ioutil" - "log" - "os" - "strconv" - "strings" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/awslabs/goformation/cloudformation" -) - -/** - The Environment Variable Saga.. - - There are two types of environment variables - - Lambda runtime variables starting with "AWS_" and passed to every function - - Custom environment variables defined in SAM template for each function - - Custom environment variables defined in the SAM template can contain hard-coded - values or fetch from a stack parameter or use Intrinsics to generate a value at - at stack creation time like ARNs. It can get complicated to support all cases - - Instead we will parse only hard-coded values from the template. For the rest, - users can supply values through the Shell's environment or the env-var override - CLI argument. If a value is provided through more than one method, the method - with higher priority will win. - - Priority (Highest to lowest) - Env-Var CLI argument - Shell's Environment - Hard-coded values from template - - This priority also applies to AWS_* system variables -*/ - -func getEnvironmentVariables(logicalID string, function *cloudformation.AWSServerlessFunction, overrideFile string, profile string) map[string]string { - - env := getEnvDefaults(function, profile) - osenv := getEnvFromOS() - overrides := getEnvOverrides(logicalID, overrideFile) - - if function.Environment != nil { - for name, value := range function.Environment.Variables { - - // hard-coded values, lowest priority - if stringedValue, ok := toStringMaybe(value); ok { - // Get only hard-coded values from the template - env[name] = stringedValue - } - - // Shell's environment, second priority - if value, ok := osenv[name]; ok { - env[name] = value - } - - // EnvVars overrides provided by customer, highest priority - if len(overrides) > 0 { - if value, ok := overrides[name]; ok { - env[name] = value - } - } - } - } - - return env - -} - -func getEnvDefaults(function *cloudformation.AWSServerlessFunction, profile string) map[string]string { - - creds := getSessionOrDefaultCreds(profile) - - // Variables available in Lambda execution environment for all functions (AWS_* variables) - env := map[string]string{ - "AWS_SAM_LOCAL": "true", - "AWS_REGION": creds["region"], - "AWS_DEFAULT_REGION": creds["region"], - "AWS_ACCESS_KEY_ID": creds["key"], - "AWS_SECRET_ACCESS_KEY": creds["secret"], - "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": strconv.Itoa(int(function.MemorySize)), - "AWS_LAMBDA_FUNCTION_TIMEOUT": strconv.Itoa(int(function.Timeout)), - "AWS_LAMBDA_FUNCTION_HANDLER": function.Handler, - // "AWS_ACCOUNT_ID=", - // "AWS_LAMBDA_EVENT_BODY=", - // "AWS_REGION=", - // "AWS_LAMBDA_FUNCTION_NAME=", - // "AWS_LAMBDA_FUNCTION_VERSION=", - } - - if token, ok := creds["sessiontoken"]; ok && token != "" { - env["AWS_SESSION_TOKEN"] = token - } - - return env - -} - -func getEnvOverrides(logicalID string, filename string) map[string]string { - - if len(filename) > 0 { - - data, err := ioutil.ReadFile(filename) - if err != nil { - log.Printf("Could not read environment overrides from %s: %s\n", filename, err) - return map[string]string{} - } - - // This is a JSON of structure {FunctionName: {key:value}, FunctionName: {key:value}} - overrides := map[string]map[string]string{} - if err = json.Unmarshal(data, &overrides); err != nil { - log.Printf("Invalid environment override file %s: %s\n", filename, err) - return map[string]string{} - } - // In case we have a cloudformation parameters json, structure {Parameters: {key:value}} - if _,ok := overrides["Parameters"]; ok { - if _,ok := overrides[logicalID]; ! ok { - overrides[logicalID] = map[string]string{} - } - - for k, v := range overrides["Parameters"] { - overrides[logicalID][k] = v - } - } - return overrides[logicalID] - - } - - return map[string]string{} - -} - -func getSessionOrDefaultCreds(profile string) map[string]string { - - region := "us-east-1" - key := "defaultkey" - secret := "defaultsecret" - - result := map[string]string{ - "region": region, - "key": key, - "secret": secret, - } - - opts := session.Options{} - opts.Profile = profile - // Obtain AWS credentials and pass them through to the container runtime via env variables - if sess, err := session.NewSessionWithOptions(opts); err == nil { - creds, err := sess.Config.Credentials.Get() - if err != nil { - log.Printf("WARNING: No AWS credentials found. Missing credentials may lead to slow startup times as detailed in https://github.com/awslabs/aws-sam-local/issues/134") - } else { - if *sess.Config.Region != "" { - result["region"] = *sess.Config.Region - } - - result["key"] = creds.AccessKeyID - result["secret"] = creds.SecretAccessKey - if creds.SessionToken != "" { - result["sessiontoken"] = creds.SessionToken - } - } - } - - return result -} - -func getEnvFromOS() map[string]string { - - result := map[string]string{} - for _, value := range os.Environ() { - keyVal := strings.Split(value, "=") - result[keyVal[0]] = keyVal[1] - } - - return result -} - -// Converts the input to string if it is a primitive type, Otherwise returns nil -func toStringMaybe(value interface{}) (string, bool) { - - switch value.(type) { - case string: - return value.(string), true - case int: - return strconv.Itoa(value.(int)), true - case float32, float64: - return strconv.FormatFloat(value.(float64), 'f', -1, 64), true - case bool: - return strconv.FormatBool(value.(bool)), true - default: - return "", false - } - -} diff --git a/env_test.go b/env_test.go deleted file mode 100644 index 63c51ee774..0000000000 --- a/env_test.go +++ /dev/null @@ -1,118 +0,0 @@ -package main - -import ( - "os" - - "github.com/awslabs/goformation" - "github.com/awslabs/goformation/cloudformation" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Environment Variables", func() { - - Context("with a template that has environment variables defined", func() { - - var functions map[string]cloudformation.AWSServerlessFunction - BeforeEach(func() { - template, _ := goformation.Open("test/templates/sam-official-samples/iot_backend/template.yaml") - functions = template.GetAllAWSServerlessFunctionResources() - }) - - It("return defaults with those defined in the template", func() { - - for name, function := range functions { - variables := getEnvironmentVariables(name, &function, "", "") - Expect(variables).To(HaveLen(9)) - Expect(variables).To(HaveKey("AWS_SAM_LOCAL")) - Expect(variables).To(HaveKey("AWS_REGION")) - Expect(variables).To(HaveKey("AWS_DEFAULT_REGION")) - Expect(variables).To(HaveKey("AWS_ACCESS_KEY_ID")) - Expect(variables).To(HaveKey("AWS_SECRET_ACCESS_KEY")) - Expect(variables).To(Not(HaveKey("AWS_SESSION_TOKEN"))) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_TIMEOUT")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_HANDLER")) - Expect(variables).To(HaveKey("TABLE_NAME")) - } - }) - - It("removes AWS_SESSION_TOKEN if the value is empty", func() { - - for name, function := range functions { - - os.Setenv("AWS_ACCESS_KEY_ID", "id") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Unsetenv("AWS_SESSION_TOKEN") - - variables := getEnvironmentVariables(name, &function, "", "") - Expect(variables).To(HaveLen(9)) - Expect(variables).To(HaveKey("AWS_SAM_LOCAL")) - Expect(variables).To(HaveKey("AWS_REGION")) - Expect(variables).To(HaveKey("AWS_DEFAULT_REGION")) - Expect(variables).To(HaveKey("AWS_ACCESS_KEY_ID")) - Expect(variables).To(HaveKey("AWS_SECRET_ACCESS_KEY")) - Expect(variables).To(Not(HaveKey("AWS_SESSION_TOKEN"))) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_TIMEOUT")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_HANDLER")) - Expect(variables).To(HaveKey("TABLE_NAME")) - - os.Unsetenv("AWS_ACCESS_KEY_ID") - os.Unsetenv("AWS_SECRET_ACCESS_KEY") - } - }) - - It("only sets AWS_SESSION_TOKEN if the value is non-nil", func() { - - for name, function := range functions { - - os.Setenv("AWS_ACCESS_KEY_ID", "id") - os.Setenv("AWS_SECRET_ACCESS_KEY", "secret") - os.Setenv("AWS_SESSION_TOKEN", "token") - - variables := getEnvironmentVariables(name, &function, "", "") - Expect(variables).To(HaveLen(10)) - Expect(variables).To(HaveKey("AWS_SAM_LOCAL")) - Expect(variables).To(HaveKey("AWS_REGION")) - Expect(variables).To(HaveKey("AWS_DEFAULT_REGION")) - Expect(variables).To(HaveKey("AWS_ACCESS_KEY_ID")) - Expect(variables).To(HaveKey("AWS_SECRET_ACCESS_KEY")) - Expect(variables).To(HaveKey("AWS_SESSION_TOKEN")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_TIMEOUT")) - Expect(variables).To(HaveKey("AWS_LAMBDA_FUNCTION_HANDLER")) - Expect(variables).To(HaveKey("TABLE_NAME")) - - Expect(variables["AWS_SESSION_TOKEN"]).To(Equal("token")) - - os.Unsetenv("AWS_ACCESS_KEY_ID") - os.Unsetenv("AWS_SECRET_ACCESS_KEY") - os.Unsetenv("AWS_SESSION_TOKEN") - - } - }) - - It("overides template with environment variables", func() { - for name, function := range functions { - variables := getEnvironmentVariables(name, &function, "", "") - Expect(variables["TABLE_NAME"]).To(Equal("")) - - os.Setenv("TABLE_NAME", "ENV_TABLE") - variables = getEnvironmentVariables(name, &function, "", "") - Expect(variables["TABLE_NAME"]).To(Equal("ENV_TABLE")) - os.Unsetenv("TABLE_NAME") - } - }) - - It("overrides template and environment with customer overrides", func() { - for name, function := range functions { - variables := getEnvironmentVariables(name, &function, "test/environment-overrides.json", "") - Expect(variables["TABLE_NAME"]).To(Equal("OVERRIDE_TABLE")) - } - os.Unsetenv("TABLE_NAME") - }) - - }) -}) diff --git a/generate-event.go b/generate-event.go deleted file mode 100644 index 0db8d362a4..0000000000 --- a/generate-event.go +++ /dev/null @@ -1,367 +0,0 @@ -package main - -import ( - "encoding/base64" - "fmt" - "os" - "text/template" - - "github.com/codegangsta/cli" -) - -var events = map[string]string{ - "S3": s3Event, - "SNS": snsEvent, - "Kinesis": kinesisEvent, - "DynamoDB": dynamodbEvent, - "Api": apiEvent, - "Schedule": scheduleEvent, -} - -func generate(eventType string, c *cli.Context) { - - sample, ok := events[eventType] - if !ok { - fmt.Printf("Unsupported event type: %s", eventType) - os.Exit(1) - } - - t, err := template.New("event").Parse(sample) - if err != nil { - fmt.Printf("Failed to load sample %s event: %s", eventType, err) - os.Exit(1) - } - - switch eventType { - case "S3": - - t.Execute(os.Stdout, struct { - Region string - Bucket string - Key string - }{ - Region: c.String("region"), - Bucket: c.String("bucket"), - Key: c.String("key"), - }) - os.Exit(0) - - case "SNS": - - t.Execute(os.Stdout, struct { - Message string - Subject string - Topic string - }{ - Message: c.String("message"), - Subject: c.String("subject"), - Topic: c.String("topic"), - }) - os.Exit(0) - - case "Kinesis": - - t.Execute(os.Stdout, struct { - Region string - Partition string - Sequence string - Data string - }{ - Region: c.String("region"), - Partition: c.String("partition"), - Sequence: c.String("sequence"), - Data: base64.StdEncoding.EncodeToString([]byte(c.String("data"))), - }) - os.Exit(0) - - case "DynamoDB": - t.Execute(os.Stdout, struct { - Region string - }{ - Region: c.String("region"), - }) - os.Exit(0) - - case "Api": - - t.Execute(os.Stdout, struct { - Method string - Body string - Resource string - Path string - }{ - Method: c.String("method"), - Body: c.String("body"), - Resource: c.String("resource"), - Path: c.String("path"), - }) - os.Exit(0) - - case "Schedule": - t.Execute(os.Stdout, struct { - Region string - }{ - Region: c.String("region"), - }) - os.Exit(0) - - } - - fmt.Printf("Error - event type %s not implemented\n", eventType) - os.Exit(1) - -} - -var s3Event = `{ - "Records": [ - { - "eventVersion": "2.0", - "eventTime": "1970-01-01T00:00:00.000Z", - "requestParameters": { - "sourceIPAddress": "127.0.0.1" - }, - "s3": { - "configurationId": "testConfigRule", - "object": { - "eTag": "0123456789abcdef0123456789abcdef", - "sequencer": "0A1B2C3D4E5F678901", - "key": "{{.Key}}", - "size": 1024 - }, - "bucket": { - "arn": "arn:aws:s3:::{{.Bucket}}", - "name": "{{.Bucket}}", - "ownerIdentity": { - "principalId": "EXAMPLE" - } - }, - "s3SchemaVersion": "1.0" - }, - "responseElements": { - "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", - "x-amz-request-id": "EXAMPLE123456789" - }, - "awsRegion": "{{.Region}}", - "eventName": "ObjectCreated:Put", - "userIdentity": { - "principalId": "EXAMPLE" - }, - "eventSource": "aws:s3" - } - ] -}` - -var snsEvent = `{ - "Records": [ - { - "EventVersion": "1.0", - "EventSubscriptionArn": "arn:aws:sns:EXAMPLE", - "EventSource": "aws:sns", - "Sns": { - "SignatureVersion": "1", - "Timestamp": "1970-01-01T00:00:00.000Z", - "Signature": "EXAMPLE", - "SigningCertUrl": "EXAMPLE", - "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", - "Message": "{{.Message}}", - "MessageAttributes": { - "Test": { - "Type": "String", - "Value": "TestString" - }, - "TestBinary": { - "Type": "Binary", - "Value": "TestBinary" - } - }, - "Type": "Notification", - "UnsubscribeUrl": "EXAMPLE", - "TopicArn": "{{.Topic}}", - "Subject": "{{.Subject}}" - } - } - ] -}` - -var kinesisEvent = `{ - "Records": [ - { - "eventID": "shardId-000000000000:{{.Sequence}}", - "eventVersion": "1.0", - "kinesis": { - "approximateArrivalTimestamp": 1428537600, - "partitionKey": "{{.Partition}}", - "data": "{{.Data}}", - "kinesisSchemaVersion": "1.0", - "sequenceNumber": "{{.Sequence}}" - }, - "invokeIdentityArn": "arn:aws:iam::EXAMPLE", - "eventName": "aws:kinesis:record", - "eventSourceARN": "arn:aws:kinesis:EXAMPLE", - "eventSource": "aws:kinesis", - "awsRegion": "{{.Region}}" - } - ] -} -` -var dynamodbEvent = `{ - "Records": [ - { - "eventID": "1", - "eventVersion": "1.0", - "dynamodb": { - "Keys": { - "Id": { - "N": "101" - } - }, - "NewImage": { - "Message": { - "S": "New item!" - }, - "Id": { - "N": "101" - } - }, - "StreamViewType": "NEW_AND_OLD_IMAGES", - "SequenceNumber": "111", - "SizeBytes": 26 - }, - "awsRegion": "{{.Region}}", - "eventName": "INSERT", - "eventSourceARN": "arn:aws:dynamodb:{{.Region}}:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899", - "eventSource": "aws:dynamodb" - }, - { - "eventID": "2", - "eventVersion": "1.0", - "dynamodb": { - "OldImage": { - "Message": { - "S": "New item!" - }, - "Id": { - "N": "101" - } - }, - "SequenceNumber": "222", - "Keys": { - "Id": { - "N": "101" - } - }, - "SizeBytes": 59, - "NewImage": { - "Message": { - "S": "This item has changed" - }, - "Id": { - "N": "101" - } - }, - "StreamViewType": "NEW_AND_OLD_IMAGES" - }, - "awsRegion": "{{.Region}}", - "eventName": "MODIFY", - "eventSourceARN": "arn:aws:dynamodb:{{.Region}}:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899", - "eventSource": "aws:dynamodb" - }, - { - "eventID": "3", - "eventVersion": "1.0", - "dynamodb": { - "Keys": { - "Id": { - "N": "101" - } - }, - "SizeBytes": 38, - "SequenceNumber": "333", - "OldImage": { - "Message": { - "S": "This item has changed" - }, - "Id": { - "N": "101" - } - }, - "StreamViewType": "NEW_AND_OLD_IMAGES" - }, - "awsRegion": "{{.Region}}", - "eventName": "REMOVE", - "eventSourceARN": "arn:aws:dynamodb:{{.Region}}:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899", - "eventSource": "aws:dynamodb" - } - ] -}` - -var apiEvent = `{ - "body": "{{.Body}}", - "resource": "{{.Resource}}", - "requestContext": { - "resourceId": "123456", - "apiId": "1234567890", - "resourcePath": "{{.Resource}}", - "httpMethod": "{{.Method}}", - "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", - "accountId": "123456789012", - "identity": { - "apiKey": null, - "userArn": null, - "cognitoAuthenticationType": null, - "caller": null, - "userAgent": "Custom User Agent String", - "user": null, - "cognitoIdentityPoolId": null, - "cognitoIdentityId": null, - "cognitoAuthenticationProvider": null, - "sourceIp": "127.0.0.1", - "accountId": null - }, - "stage": "prod" - }, - "queryStringParameters": { - "foo": "bar" - }, - "headers": { - "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", - "Accept-Language": "en-US,en;q=0.8", - "CloudFront-Is-Desktop-Viewer": "true", - "CloudFront-Is-SmartTV-Viewer": "false", - "CloudFront-Is-Mobile-Viewer": "false", - "X-Forwarded-For": "127.0.0.1, 127.0.0.2", - "CloudFront-Viewer-Country": "US", - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", - "Upgrade-Insecure-Requests": "1", - "X-Forwarded-Port": "443", - "Host": "1234567890.execute-api.us-east-1.amazonaws.com", - "X-Forwarded-Proto": "https", - "X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==", - "CloudFront-Is-Tablet-Viewer": "false", - "Cache-Control": "max-age=0", - "User-Agent": "Custom User Agent String", - "CloudFront-Forwarded-Proto": "https", - "Accept-Encoding": "gzip, deflate, sdch" - }, - "pathParameters": { - "proxy": "{{.Path}}" - }, - "httpMethod": "{{.Method}}", - "stageVariables": { - "baz": "qux" - }, - "path": "{{.Path}}" -}` - -var scheduleEvent = `{ - "account": "123456789012", - "region": "{{.Region}}", - "detail": {}, - "detail-type": "Scheduled Event", - "source": "aws.events", - "time": "1970-01-01T00:00:00Z", - "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", - "resources": [ - "arn:aws:events:us-east-1:123456789012:rule/my-schedule" - ] -}` diff --git a/invoke.go b/invoke.go deleted file mode 100644 index 6b3fbe21fa..0000000000 --- a/invoke.go +++ /dev/null @@ -1,149 +0,0 @@ -package main - -import ( - "fmt" - "log" - "os" - "path/filepath" - - "io/ioutil" - - "io" - "sync" - - "github.com/awslabs/goformation" - "github.com/awslabs/goformation/intrinsics" - "github.com/codegangsta/cli" -) - -func invoke(c *cli.Context) { - - // Setup the logger - stdout := io.Writer(os.Stdout) - stderr := io.Writer(os.Stderr) - logarg := c.String("log-file") // matches the definition in main.go - - if len(logarg) > 0 { - if logFile, err := os.Create(logarg); err == nil { - stderr = io.Writer(logFile) - stdout = io.Writer(logFile) - log.SetOutput(stderr) - } else { - log.Fatalf("Failed to open log file %s: %s\n", c.String("log"), err) - } - } - - filename := getTemplateFilename(c.String("template")) - template, err := goformation.OpenWithOptions(filename, &intrinsics.ProcessorOptions{ - ParameterOverrides: parseParameters(c.String("parameter-values")), - }) - if err != nil { - log.Fatalf("Failed to parse template: %s\n", err) - } - - log.Printf("Successfully parsed %s\n", filename) - - name := c.Args().First() - - // Find the specified function in the SAM template. Either check for a function whose - // logical ID matches the first CLI argument, or if they only have a single function - // defined, and don't specify a name, then just use that function. - functions := template.GetAllAWSServerlessFunctionResources() - - addCloudformationLambdaFunctions(template, functions) - - function, found := functions[name] - if !found { - if len(functions) == 1 && name == "" { - for _, f := range functions { - function = f - } - } else { - if name == "" { - fmt.Fprintf(os.Stderr, "ERROR: You must provide a function identifier (function's Logical ID in the SAM template) as the first argument.\n") - } else { - fmt.Fprintf(os.Stderr, "ERROR: Could not find a AWS::Serverless::Function with logical ID '%s'\n", name) - } - // If have functions defined in the template, be helpful and suggest them - if len(functions) > 0 { - fmt.Fprintf(os.Stderr, "Possible options in your template:\n") - for resourceName := range functions { - fmt.Fprintf(os.Stderr, " * %s\n", resourceName) - } - } - os.Exit(1) - } - } - - // Check connectivity to docker - dockerVersion, err := getDockerVersion() - if err != nil { - log.Printf("Running AWS SAM projects locally requires Docker. Have you got it installed?\n") - log.Printf("%s\n", err) - os.Exit(1) - } - - log.Printf("Connected to Docker %s", dockerVersion) - - cwd := filepath.Dir(filename) - if c.String("docker-volume-basedir") != "" { - cwd = c.String("docker-volume-basedir") - } - - runt, err := NewRuntime(NewRuntimeOpt{ - Cwd: cwd, - LogicalID: name, - Function: function, - Logger: stderr, - EnvOverrideFile: c.String("env-vars"), - DebugPort: c.String("debug-port"), - SkipPullImage: c.Bool("skip-pull-image"), - DockerNetwork: c.String("docker-network"), - }) - - if err != nil { - log.Fatalf("Could not initiate %s runtime: %s\n", function.Runtime, err) - } - - eventFile := c.String("event") - event := "" - if eventFile == "" { - // The event payload wasn't provided with --event, so read from stdin - log.Printf("Reading invoke payload from stdin (you can also pass it from file with --event)\n") - pb, err := ioutil.ReadAll(os.Stdin) - if err != nil { - log.Fatalf("Could not read event from stdin: %s\n", err) - } - event = string(pb) - } else { - // The event payload should be read from the file provided - pb, err := ioutil.ReadFile(eventFile) - if err != nil { - log.Fatalf("Could not read event from file: %s\n", err) - } - event = string(pb) - } - - stdoutTxt, stderrTxt, err := runt.Invoke(event, c.String("profile")) - if err != nil { - log.Fatalf("Could not invoke function: %s\n", err) - } - - var wg sync.WaitGroup - wg.Add(2) - - go func() { - io.Copy(stderr, stderrTxt) - wg.Done() - }() - - go func() { - io.Copy(stdout, stdoutTxt) - wg.Done() - }() - - wg.Wait() - - fmt.Fprintf(stderr, "\n") - runt.CleanUp() -} diff --git a/main.go b/main.go deleted file mode 100644 index 1bba1fd014..0000000000 --- a/main.go +++ /dev/null @@ -1,424 +0,0 @@ -package main - -import ( - "fmt" - "os" - "path/filepath" - "regexp" - "strings" - - "github.com/codegangsta/cli" - "github.com/fatih/color" -) - -const LOCAL_BUILD_VERSION = "snapshot" - -// `version` property will be replaced by the build upon release -var version = LOCAL_BUILD_VERSION - -func main() { - - color.Unset() - - if version != LOCAL_BUILD_VERSION { - // Enable version checking only on public releases - - v, err := checkVersion() - if err == nil && !v.IsUpToDate { - fmt.Fprintf(os.Stderr, "A newer version of the AWS SAM CLI is available!\n") - fmt.Fprintf(os.Stderr, "Your version: %s\n", version) - fmt.Fprintf(os.Stderr, "Latest version: %s\n", v.LatestVersion) - fmt.Fprintf(os.Stderr, "See https://github.com/awslabs/aws-sam-local for upgrade instructions\n\n") - } - } - - app := cli.NewApp() - - app.Name = "sam" - app.Version = version - app.Usage = ` - ___ _____ ___ _ __ __ - /_\ \ / / __| / __| /_\ | \/ | - / _ \ \/\/ /\__ \ \__ \/ _ \| |\/| | - /_/ \_\_/\_/ |___/ |___/_/ \_\_| |_| - - AWS Serverless Application Model (SAM) CLI - - The AWS Serverless Application Model extends AWS CloudFormation to provide a simplified way of defining the Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application. You can find more in-depth guide about the SAM specification here: https://github.com/awslabs/serverless-application-model. - ` - app.EnableBashCompletion = true // \m/ - - app.Commands = []cli.Command{ - cli.Command{ - Name: "local", - Usage: "Run your Serverless application locally for quick development & testing", - Subcommands: []cli.Command{ - cli.Command{ - Name: "start-api", - Action: start, - Usage: "Allows you to run your Serverless application locally for quick development & testing. When run in a directory that contains your Serverless functions and your AWS SAM template, it will create a local HTTP server hosting all of your functions. When accessed (via browser, cli etc), it will launch a Docker container locally to invoke the function. It will read the CodeUri property of AWS::Serverless::Function resource to find the path in your file system containing the Lambda Function code. This could be the project's root directory for interpreted languages like Node & Python, or a build directory that stores your compiled artifacts or a JAR file. If you are using a interpreted language, local changes will be available immediately in Docker container on every invoke. For more compiled languages or projects requiring complex packing support, we recommended you run your own building solution and point SAM to the directory or file containing build artifacts.\n", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "template, t", - Value: "template.[yaml|yml]", - Usage: "AWS SAM template file", - EnvVar: "SAM_TEMPLATE_FILE", - }, - cli.StringFlag{ - Name: "parameter-values", - Usage: "Optional. A string that contains CloudFormation parameter overrides encoded as key-value pairs. Use the same format as the AWS CLI, e.g. 'ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro'. In case of parsing errors all values are ignored", - EnvVar: "SAM_TEMPLATE_PARAM_ARG", - }, - cli.StringFlag{ - Name: "log-file, l", - Usage: "Optional logfile to send runtime logs to", - }, - cli.StringFlag{ - Name: "static-dir, s", - Usage: "Any static assets (e.g. CSS/Javascript/HTML) files located in this directory will be presented at /", - Value: "public", - }, - cli.StringFlag{ - Name: "port, p", - Value: "3000", - Usage: "Local port number to listen on", - }, - cli.StringFlag{ - Name: "host", - Value: "127.0.0.1", - Usage: "Local hostname or IP address to bind to", - }, - cli.StringFlag{ - Name: "env-vars, n", - Usage: "Optional. JSON file containing values for Lambda function's environment variables. ", - }, - cli.StringFlag{ - Name: "debug-port, d", - Usage: "Optional. When specified, Lambda function container will start in debug mode and will expose this port on localhost.", - EnvVar: "SAM_DEBUG_PORT", - }, - cli.StringFlag{ - Name: "docker-volume-basedir, v", - Usage: "Optional. Specifies the location basedir where the SAM file exists. If the Docker is running on a remote machine, " + - "you must mount the path where the SAM file exists on the docker machine and modify this value to match the remote machine.", - EnvVar: "SAM_DOCKER_VOLUME_BASEDIR", - }, - cli.StringFlag{ - Name: "docker-network", - Usage: "Optional. Specifies the name or id of an existing docker network to lambda docker " + - "containers should connect to, along with the default bridge network. If not specified, " + - "the lambdadocker containers will only connect to the default bridge docker network.", - EnvVar: "SAM_DOCKER_NETWORK", - }, - cli.BoolFlag{ - Name: "skip-pull-image", - Usage: "Optional. Specify whether SAM should skip pulling down the latest Docker image. Default is false.", - EnvVar: "SAM_SKIP_PULL_IMAGE", - }, - cli.StringFlag{ - Name: "profile", - Usage: "Optional. Specify which AWS credentials profile to use.", - }, - cli.BoolFlag{ - Name: "prefix-routing", - Usage: "Optional. Specify whether SAM routing is based on prefix or exact matching (e.g. given a function mounted at '/' with prefix routing calls to '/beers' will be routed the function).", - EnvVar: "SAM_PREFIX_ROUTING", - }, - }, - }, - cli.Command{ - Name: "invoke", - Action: invoke, - Usage: "Invokes a local Lambda function once and quits after invocation completes. \n\n" + - "Useful for developing serverless functions that handle asynchronous events (such as S3/Kinesis etc), or if you want to compose a script of test cases. " + - "Event body can be passed in either by stdin (default), or by using the --event parameter. Runtime output (logs etc) will be outputted to stderr, and the Lambda function result will be outputted to stdout.\n", - ArgsUsage: "", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "template, t", - Value: "template.[yaml|yml]", - Usage: "AWS SAM template file", - EnvVar: "SAM_TEMPLATE_FILE", - }, - cli.StringFlag{ - Name: "parameter-values", - Usage: "Optional. A string that contains CloudFormation parameter overrides encoded as key-value pairs. Use the same format as the AWS CLI, e.g. 'ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro'. In case of parsing errors all values are ignored", - EnvVar: "SAM_TEMPLATE_PARAM_ARG", - }, - cli.StringFlag{ - Name: "log-file, l", - Usage: "Optional. Logfile to send runtime logs to", - }, - cli.StringFlag{ - Name: "env-vars, n", - Usage: "Optional. JSON file containing values for Lambda function's environment variables. ", - }, - cli.StringFlag{ - Name: "event, e", - Usage: "JSON file containing event data passed to the Lambda function during invoke", - }, - cli.StringFlag{ - Name: "debug-port, d", - Usage: "Optional. When specified, Lambda function container will start in debug mode and will expose this port on localhost.", - EnvVar: "SAM_DEBUG_PORT", - }, - cli.StringFlag{ - Name: "docker-volume-basedir, v", - Usage: "Optional. Specifies the location basedir where the SAM file exists. If the Docker is running on a remote machine, " + - "you must mount the path where the SAM file exists on the docker machine and modify this value to match the remote machine.", - EnvVar: "SAM_DOCKER_VOLUME_BASEDIR", - }, - cli.StringFlag{ - Name: "docker-network", - Usage: "Optional. Specifies the name or id of an existing docker network to lambda docker " + - "containers should connect to, along with the default bridge network. If not specified, " + - "the lambdadocker containers will only connect to the default bridge docker network.", - EnvVar: "SAM_DOCKER_NETWORK", - }, - cli.BoolFlag{ - Name: "skip-pull-image", - Usage: "Optional. Specify whether SAM should skip pulling down the latest Docker image. Default is false.", - EnvVar: "SAM_SKIP_PULL_IMAGE", - }, - cli.StringFlag{ - Name: "profile", - Usage: "Optional. Specify which AWS credentials profile to use.", - }, - }, - }, - cli.Command{ - Name: "generate-event", - Usage: "Generates Lambda events (e.g. for S3/Kinesis etc) that can be piped to 'sam local invoke'", - Subcommands: []cli.Command{ - cli.Command{ - Name: "s3", - Usage: "Generates a sample Amazon S3 event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "region, r", - Usage: "The region the event should come from", - Value: "us-east-1", - }, - cli.StringFlag{ - Name: "bucket, b", - Usage: "The S3 bucket the event should reference", - Value: "example-bucket", - }, - cli.StringFlag{ - Name: "key, k", - Usage: "The S3 key the event should reference", - Value: "test/key", - }, - }, - Action: func(c *cli.Context) { - generate("S3", c) - }, - }, - cli.Command{ - Name: "sns", - Usage: "Generates a sample Amazon SNS event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "message, m", - Usage: "The SNS message body", - Value: "example message", - }, - cli.StringFlag{ - Name: "topic, t", - Usage: "The SNS topic", - Value: "arn:aws:sns:us-east-1:111122223333:ExampleTopic", - }, - cli.StringFlag{ - Name: "subject, s", - Usage: "The SNS subject", - Value: "example subject", - }, - }, - Action: func(c *cli.Context) { - generate("SNS", c) - }, - }, - cli.Command{ - Name: "kinesis", - Usage: "Generates a sample Amazon Kinesis event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "region, r", - Usage: "The region the event should come from", - Value: "us-east-1", - }, - cli.StringFlag{ - Name: "partition, p", - Usage: "The Kinesis partition key", - Value: "partitionKey-03", - }, - cli.StringFlag{ - Name: "sequence, s", - Usage: "The Kinesis sequence number", - Value: "49545115243490985018280067714973144582180062593244200961", - }, - cli.StringFlag{ - Name: "data, d", - Usage: "The Kinesis message payload. There is no need to base64 this - sam will do this for you", - Value: "Hello, this is a test 123.", - }, - }, - Action: func(c *cli.Context) { - generate("Kinesis", c) - }, - }, - cli.Command{ - Name: "dynamodb", - Usage: "Generates a sample Amazon DynamoDB event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "region, r", - Usage: "The region the event should come from", - Value: "us-east-1", - }, - }, - Action: func(c *cli.Context) { - generate("DynamoDB", c) - }, - }, - cli.Command{ - Name: "api", - Usage: "Generates a sample Amazon API Gateway event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "method, m", - Usage: "HTTP method", - Value: "POST", - }, - cli.StringFlag{ - Name: "body, b", - Usage: "HTTP body", - Value: `{ \"test\": \"body\"}`, - }, - cli.StringFlag{ - Name: "resource, r", - Usage: "API Gateway resource name", - Value: "/{proxy+}", - }, - cli.StringFlag{ - Name: "path, p", - Usage: "HTTP path", - Value: "/examplepath", - }, - }, - Action: func(c *cli.Context) { - generate("Api", c) - }, - }, - cli.Command{ - Name: "schedule", - Usage: "Generates a sample scheduled event", - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "region, r", - Usage: "The region the event should come from", - Value: "us-east-1", - }, - }, - Action: func(c *cli.Context) { - generate("Schedule", c) - }, - }, - }, - }, - }, - }, - - cli.Command{ - Name: "validate", - Usage: "Validates an AWS SAM template. If valid, will print a summary of the resources found within the SAM template. If the template is invalid, returns a non-zero exit code.", - Action: validate, - Flags: []cli.Flag{ - cli.StringFlag{ - Name: "template, t", - Value: "template.[yaml|yml]", - Usage: "AWS SAM template file", - EnvVar: "SAM_TEMPLATE_FILE", - }, - }, - }, - - cli.Command{ - // This is just here for consistent usage and --help - Name: "package", - Usage: "Package an AWS SAM application. This is an alias for 'aws cloudformation package'.", - Action: pkg, - }, - - cli.Command{ - // This is just here for consistent usage and --help - Name: "deploy", - Usage: "Deploy an AWS SAM application. This is an alias for 'aws cloudformation deploy'.", - Action: deploy, - }, - } - - // For 'package' and 'deploy' CLI options, we want to intercept - // and just pass all arguments through to the AWS CLI commands. - if len(os.Args) > 1 && os.Args[1] == "package" { - pkg() - return - } - - // For 'package' and 'deploy' CLI options, we want to intercept - // and just pass all arguments through to the AWS CLI commands. - if len(os.Args) > 1 && os.Args[1] == "deploy" { - deploy() - return - } - - app.Run(os.Args) - -} - -// regexp that parses Cloudformation paramter key-value pair: https://regex101.com/r/hruxlg/3 -var paramRe = regexp.MustCompile(`(?:ParameterKey)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^, "\\]+)*),(?:ParameterValue)=("(?:\\.|[^"\\]+)*"|(?:\\.|[^ ,"\\]+)*)`) - -// parseParameters parses the Cloudformation parameters like string and converts -// it into a map of key-value pairs. -func parseParameters(arg string) (overrides map[string]interface{}) { - overrides = make(map[string]interface{}) - - unquote := func(orig string) string { - return strings.Replace(strings.TrimSuffix(strings.TrimPrefix(orig, `"`), `"`), `\ `, ` `, -1) - } - - for _, match := range paramRe.FindAllStringSubmatch(arg, -1) { - overrides[unquote(match[1])] = unquote(match[2]) - } - return -} - -// getTemplateFilename allows SAM Local to default to either template.yaml -// or template.yml for the --template/-t parameter. This is helpful, as there -// isn't a hard definition for the filename suffix and usage tends to be mixed -func getTemplateFilename(filename string) string { - - if filename != "template.[yaml|yml]" { - return filename - } - - // See whether to use template.yaml or template.yml - - // First shoot for .yaml - fp, err := filepath.Abs("template.yaml") - if err != nil { - // Can't work out the absolute path, so just use whatever was passed in - return filename - } - - fi, err := os.Stat(fp) - if err == nil { - // There is a template.yaml, so use it - return fi.Name() - } - - // We couldn't find a template.yaml, so fallback to template.yml - return "template.yml" - -} diff --git a/media/sam-local-banner.png b/media/sam-cli-banner.png similarity index 100% rename from media/sam-local-banner.png rename to media/sam-cli-banner.png diff --git a/package.go b/package.go deleted file mode 100644 index 6f3faf9c99..0000000000 --- a/package.go +++ /dev/null @@ -1,39 +0,0 @@ -package main - -import ( - "io" - "log" - "os" - "os/exec" -) - -func pkg() { - - args := []string{"cloudformation", "package"} - for _, arg := range os.Args[2:] { - args = append(args, arg) - } - - cmd := exec.Command("aws", args...) - - stderr, err := cmd.StderrPipe() - if err != nil { - log.Fatal(err) - } - - stdout, err := cmd.StdoutPipe() - if err != nil { - log.Fatal(err) - } - - if err := cmd.Start(); err != nil { - log.Fatal(err) - } - - go io.Copy(os.Stderr, stderr) - go io.Copy(os.Stdout, stdout) - - if err := cmd.Wait(); err != nil { - os.Exit(1) - } -} diff --git a/params_test.go b/params_test.go deleted file mode 100644 index 25d087d667..0000000000 --- a/params_test.go +++ /dev/null @@ -1,47 +0,0 @@ -package main - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Parse Cloudformation parameters", func() { - - Context("with normal input", func() { - - It("returns empty map when input is missing", func() { - p := parseParameters("") - Expect(p).To(BeEmpty()) - }) - - It("returns expected values when input is correct", func() { - p := parseParameters("ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro") - Expect(p).To(HaveLen(2)) - Expect(p).To(HaveKeyWithValue("KeyPairName", "MyKey")) - Expect(p).To(HaveKeyWithValue("InstanceType", "t1.micro")) - }) - - It("returns partial values when input is malformed", func() { - p := parseParameters("ParameterKey=KeyPairName,ParameterValue=MyKey Para") - Expect(p).To(HaveLen(1)) - Expect(p).To(HaveKeyWithValue("KeyPairName", "MyKey")) - }) - }) - - Context("with escaped input", func() { - - It("returns expected values when keys or values are quoted", func() { - p := parseParameters(`ParameterKey="KeyPairName",ParameterValue="MyKey " ParameterKey=InstanceType,ParameterValue=t1\ mic\ ro`) - Expect(p).To(HaveLen(2)) - Expect(p).To(HaveKeyWithValue("KeyPairName", "MyKey ")) - Expect(p).To(HaveKeyWithValue("InstanceType", "t1 mic ro")) - }) - - It("handles wrong quotings", func() { - p := parseParameters(`ParameterKey="KeyPairName,ParameterValue="MyKey" ParameterKey=InstanceType,ParameterValue=t1\ micro`) - Expect(p).To(HaveLen(1)) - Expect(p).To(HaveKeyWithValue("InstanceType", "t1 micro")) - }) - - }) -}) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000000..fd1b9f27dc --- /dev/null +++ b/pytest.ini @@ -0,0 +1,4 @@ +[pytest] +env = + AWS_DEFAULT_REGION = ap-southeast-1 + diff --git a/requirements/base.txt b/requirements/base.txt new file mode 100644 index 0000000000..74574676ec --- /dev/null +++ b/requirements/base.txt @@ -0,0 +1,9 @@ +six~=1.11.0 +click~=6.7 +enum34~=1.1.6 +Flask~=0.12.2 +boto3~=1.5 +PyYAML~=3.12 +cookiecutter~=1.6.0 +aws-sam-translator==1.5.4 +docker>=3.3.0 diff --git a/requirements/dev.txt b/requirements/dev.txt new file mode 100644 index 0000000000..d7ae73ee3f --- /dev/null +++ b/requirements/dev.txt @@ -0,0 +1,16 @@ +coverage==4.3.4 +flake8==3.3.0 +tox==2.2.1 +pytest-cov==2.4.0 +pylint==1.7.2 + +# Test requirements +pytest==3.0.7 +py==1.4.33 +mock==2.0.0 +requests>=2.18.0 +parameterized==0.6.1 +pathlib2==2.3.2 +futures==3.2.0 +# Py3.2 backport +backports.tempfile==1.0 diff --git a/router/api.go b/router/api.go deleted file mode 100644 index 2a7d91921e..0000000000 --- a/router/api.go +++ /dev/null @@ -1,296 +0,0 @@ -package router - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "log" - - "strings" - - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - "github.com/awslabs/goformation/cloudformation" - "github.com/go-openapi/spec" - "github.com/sanathkr/go-yaml" -) - -const apiGatewayIntegrationExtension = "x-amazon-apigateway-integration" -const apiGatewayAnyMethodExtension = "x-amazon-apigateway-any-method" -const apiGatewayBinaryMediaTypesExtension = "x-amazon-apigateway-binary-media-types" - -// temporary object. This is just used to marshal and unmarshal the any method -// API Gateway swagger extension -type ApiGatewayAnyMethod struct { - IntegrationSettings interface{} `json:"x-amazon-apigateway-integration"` -} - -// AWSServerlessApi wraps GoFormation's AWS::Serverless::Api definition -// and adds some convenience methods for extracting the ServerlessRouterMount's -// from the swagger defintion etc. -type AWSServerlessApi struct { - *cloudformation.AWSServerlessApi -} - -// Mounts fetches an array of the ServerlessRouterMount's for this API. -// These contain the path, method and handler function for each mount point. -func (api *AWSServerlessApi) Mounts() ([]*ServerlessRouterMount, error) { - jsonDefinition, err := api.Swagger() - - if err != nil { - // this is our own error so we return it directly - return nil, err - } - - swagger := spec.Swagger{} - err = swagger.UnmarshalJSON(jsonDefinition) - - if err != nil { - return nil, fmt.Errorf("Cannot parse Swagger definition: %s", err.Error()) - } - - mounts := []*ServerlessRouterMount{} - - binaryMediaTypes, ok := swagger.VendorExtensible.Extensions.GetStringSlice(apiGatewayBinaryMediaTypesExtension) - if !ok { - binaryMediaTypes = []string{} - } - - for path, pathItem := range swagger.Paths.Paths { - // temporary tracking of mounted methods for the current path. Used to - // mount all non-existing methods for the any extension. This is because - // the err from JSONLookup did not work as expected - mappedMethods := map[string]bool{} - - for _, method := range HttpMethods { - - if operationIface, err := pathItem.JSONLookup(strings.ToLower(method)); err == nil { - operation := spec.Operation{} - operationJSON, err := json.Marshal(operationIface) - if err != nil { - return nil, fmt.Errorf("Could not parse %s operation: %s", method, err.Error()) - } - operation.UnmarshalJSON(operationJSON) - - // the JSON will always contain the method because it's a property in the Swagger model - // If we don't have an integration defined then we skip it. - if operation.Extensions[apiGatewayIntegrationExtension] == nil { - continue - } - - integration, _ := operation.Extensions[apiGatewayIntegrationExtension] - mounts = append(mounts, api.createMount( - path, - strings.ToLower(method), - api.parseIntegrationSettings(integration), - binaryMediaTypes)) - mappedMethods[method] = true - } - } - - anyMethod, available := pathItem.Extensions[apiGatewayAnyMethodExtension] - if available { - // any method to json then unmarshal to temporary object - anyMethodJSON, err := json.Marshal(anyMethod) - if err != nil { - return nil, fmt.Errorf("Could not marshal any method object to json") - } - - anyMethodObject := ApiGatewayAnyMethod{} - err = json.Unmarshal(anyMethodJSON, &anyMethodObject) - - if err != nil { - return nil, fmt.Errorf("Could not unmarshal any method josn to object model") - } - - for _, method := range HttpMethods { - if _, ok := mappedMethods[method]; !ok { - mounts = append(mounts, api.createMount( - path, - strings.ToLower(method), - api.parseIntegrationSettings(anyMethodObject.IntegrationSettings), - binaryMediaTypes)) - } - } - } - } - - return mounts, nil -} - -// parses a byte[] for the API Gateway inetegration extension from a method and return -// the object representation -func (api *AWSServerlessApi) parseIntegrationSettings(integrationData interface{}) *ApiGatewayIntegration { - integrationJSON, err := json.Marshal(integrationData) - if err != nil { - log.Printf("Could not parse integration data to json") - return nil - } - - integration := ApiGatewayIntegration{} - err = json.Unmarshal(integrationJSON, &integration) - - if err != nil { - log.Printf("Could not unmarshal integration data to ApiGatewayIntegration model") - return nil - } - - return &integration -} - -func (api *AWSServerlessApi) createMount(path string, verb string, integration *ApiGatewayIntegration, binaryMediaTypes []string) *(ServerlessRouterMount) { - newMount := &ServerlessRouterMount{ - Name: path, - Path: path, - Method: verb, - BinaryMediaTypes: binaryMediaTypes, - } - - if integration == nil { - log.Printf("No integration defined for method") - return newMount - } - - functionName, err := integration.GetFunctionArn() - - if err != nil { - log.Printf("Could not extract Lambda function ARN: %s", err.Error()) - } - newMount.IntegrationArn = functionName - - return newMount -} - -// Swagger gets the swagger definition for the API. -// Returns the swagger definition as a []byte of JSON. -func (api *AWSServerlessApi) Swagger() ([]byte, error) { - - // The swagger definition can be passed in 1 of 4 ways: - - // 1. A definition URI defined as a string - if api.DefinitionUri != nil { - if api.DefinitionUri.String != nil { - data, err := api.getSwaggerFromURI(*api.DefinitionUri.String) - if err != nil { - return nil, err - } - return api.ensureJSON(data) - } - } - - // 2. A definition URI defined as an S3 Location - if api.DefinitionUri != nil { - if api.DefinitionUri.S3Location != nil { - data, err := api.getSwaggerFromS3Location(*api.DefinitionUri.S3Location) - if err != nil { - return nil, err - } - return api.ensureJSON(data) - } - } - - if api.DefinitionBody != nil { - - switch val := api.DefinitionBody.(type) { - - case string: - // 3. A definition body defined as JSON (which will unmarshal to a string) - return api.getSwaggerFromString(val) - - case map[string]interface{}: - // 4. A definition body defined as YAML (which will unmarshal to map[string]interface{}) - return api.getSwaggerFromMap(val) - } - - } - - return nil, fmt.Errorf("no swagger definition found") -} - -func (api *AWSServerlessApi) ensureJSON(data []byte) ([]byte, error) { - var tmpDefinition interface{} - err := json.Unmarshal(data, &tmpDefinition) - - if err != nil { // may be yaml - err = yaml.Unmarshal(data, &tmpDefinition) - - if err != nil { - // we can't make it work either as json or yaml. fail :( - return nil, err - } - tmpDefinition = yamlToJSON(tmpDefinition) - - outputData, err := json.Marshal(tmpDefinition) - if err != nil { - return nil, err - } - return outputData, nil - } - - return data, nil -} - -func (api *AWSServerlessApi) getSwaggerFromURI(uri string) ([]byte, error) { - data, err := ioutil.ReadFile(uri) - if err != nil { - return nil, fmt.Errorf("Cannot read local Swagger definition (%s): %s", uri, err.Error()) - } - return data, nil -} - -func (api *AWSServerlessApi) getSwaggerFromS3Location(loc cloudformation.AWSServerlessApi_S3Location) ([]byte, error) { - sess := session.Must(session.NewSession()) - client := s3.New(sess) - - objectVersion := string(loc.Version) - s3Input := s3.GetObjectInput{ - Bucket: &loc.Bucket, - Key: &loc.Key, - VersionId: &objectVersion, - } - - object, err := client.GetObject(&s3Input) - - if err != nil { - return nil, fmt.Errorf("Error while fetching Swagger template from S3: %s\n%s", loc.Bucket+loc.Key, err.Error()) - } - - body, err := ioutil.ReadAll(object.Body) - - if err != nil { - return nil, fmt.Errorf("Cannot read s3 Swagger boject body: %s", err.Error()) - } - return body, nil -} - -func (api *AWSServerlessApi) getSwaggerFromString(input string) ([]byte, error) { - return []byte(input), nil -} - -func (api *AWSServerlessApi) getSwaggerFromMap(input map[string]interface{}) ([]byte, error) { - return json.Marshal(input) -} - -// Recursively convert a map[interface{}]interface{} (yaml) to map[string]interface{} (json) -// with an additional special case for the Swagger version that makes the offical Swagger -// library very upset. -func yamlToJSON(i interface{}) interface{} { - switch x := i.(type) { - case map[interface{}]interface{}: - m2 := map[string]interface{}{} - for k, v := range x { - // we have a special case for the swagger version, we need to convert it to a string - if strings.ToLower(k.(string)) == "swagger" { - m2[k.(string)] = fmt.Sprintf("%v", v) - } else { - m2[k.(string)] = yamlToJSON(v) - } - } - return m2 - case []interface{}: - for i, v := range x { - x[i] = yamlToJSON(v) - } - } - return i -} diff --git a/router/api_test.go b/router/api_test.go deleted file mode 100644 index 453dfe0a92..0000000000 --- a/router/api_test.go +++ /dev/null @@ -1,87 +0,0 @@ -package router_test - -import ( - "strings" - - "github.com/awslabs/aws-sam-local/router" - "github.com/awslabs/goformation/cloudformation" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -func getApiResourceFromTemplate(path string) *router.AWSServerlessApi { - templateUri := &path - apiResource := &router.AWSServerlessApi{ - AWSServerlessApi: &cloudformation.AWSServerlessApi{ - DefinitionUri: &cloudformation.AWSServerlessApi_DefinitionUri{ - String: templateUri, - }, - }, - } - return apiResource -} - -var _ = Describe("Api", func() { - - Context("Load local Swagger definitions", func() { - It("Succesfully loads the basic template", func() { - apiResource := getApiResourceFromTemplate("../test/templates/open-api/pet-store-simple.json") - - mounts, err := apiResource.Mounts() - - Expect(err).Should(BeNil()) - Expect(mounts).ShouldNot(BeNil()) - - Expect(mounts).ShouldNot(BeEmpty()) - Expect(len(mounts)).Should(BeIdenticalTo(4)) - }) - - It("Succesfully reads integration definition", func() { - apiResource := getApiResourceFromTemplate("../test/templates/open-api/pet-store-simple.json") - - mounts, err := apiResource.Mounts() - - Expect(err).Should(BeNil()) - Expect(mounts).ShouldNot(BeNil()) - - for _, mount := range mounts { - if mount.Method == "get" && mount.Path == "/pets" { - Expect(mount.IntegrationArn.Arn).Should(BeIdenticalTo("arn:aws:lambda:us-west-2:123456789012:function:Calc")) - } - } - }) - - It("Loads the proxy template", func() { - apiResource := getApiResourceFromTemplate("../test/templates/open-api/pet-store-proxy.json") - - mounts, err := apiResource.Mounts() - - Expect(err).Should(BeNil()) - Expect(mounts).ShouldNot(BeNil()) - // we expect 9 here because the any method should generate all 7 - Expect(len(mounts)).To(BeIdenticalTo(9)) - - for _, mount := range mounts { - if mount.Method == "post" && mount.Path == "/pets/{proxy+}" { - Expect(mount.IntegrationArn.Arn).Should(ContainSubstring("AnyMethod")) - } - if mount.Method == "delete" && mount.Path == "/pets/{proxy+}" { - Expect(mount.IntegrationArn.Arn).Should(ContainSubstring("Calc")) - } - } - }) - - It("Loads a YAML Swagger template", func() { - apiResource := getApiResourceFromTemplate("../test/templates/open-api/simple-yaml.yaml") - - mounts, err := apiResource.Mounts() - Expect(err).To(BeNil()) - Expect(mounts).ToNot(BeNil()) - Expect(1).To(Equal(len(mounts))) - Expect("/").To(Equal(mounts[0].Path)) - Expect("post").To(Equal(strings.ToLower(mounts[0].Method))) - }) - - }) -}) diff --git a/router/event.go b/router/event.go deleted file mode 100644 index 734b2ceb7f..0000000000 --- a/router/event.go +++ /dev/null @@ -1,126 +0,0 @@ -package router - -import ( - "encoding/json" - "io/ioutil" - "net/http" - "strings" - - "github.com/gorilla/mux" -) - -// Event represents an event passed to an AWS Lambda function by the runtime -type Event struct { - HTTPMethod string `json:"httpMethod"` - Body string `json:"body"` - Resource string `json:"resource"` - RequestContext RequestContext `json:"requestContext"` - QueryStringParams map[string]string `json:"queryStringParameters"` - Headers map[string]string `json:"headers"` - PathParameters map[string]string `json:"pathParameters"` - StageVariables map[string]string `json:"stageVariables"` - Path string `json:"path"` - IsBase64Encoded bool `json:"isBase64Encoded"` -} - -// RequestContext represents the context object that gets passed to an AWS Lambda function -type RequestContext struct { - ResourceID string `json:"resourceId,omitempty"` - APIID string `json:"apiId,omitempty"` - ResourcePath string `json:"resourcePath,omitempty"` - HTTPMethod string `json:"httpMethod,omitempty"` - RequestID string `json:"requestId,omitempty"` - AccountsID string `json:"accountId,omitempty"` - Stage string `json:"stage,omitempty"` - Identity ContextIdentity `json:"identity,omitempty"` -} - -// ContextIdentity represents the identity section of the context object that gets passed to an AWS Lambda function -type ContextIdentity struct { - APIKey string `json:"apiKey,omitempty"` - UserARN string `json:"userArn,omitempty"` - CognitoAuthenticationType string `json:"cognitoAuthenticationType,omitempty"` - Caller string `json:"caller,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - User string `json:"user,omitempty"` - CognitoIdentityPoolID string `json:"cognitoIdentityPoolId,omitempty"` - CognitoIdentityID string `json:"cognitoIdentityId,omitempty"` - CognitoAuthenticationProvider string `json:"cognitoAuthenticationProvider,omitempty"` - SourceIP string `json:"sourceIp,omitempty"` - AccountID string `json:"accountId,omitempty"` -} - -// NewEvent initalises and populates a new ApiEvent with -// event details from a http.Request and isBase64Encoded value -func NewEvent(req *http.Request, isBase64Encoded bool) (*Event, error) { - - var body []byte - if req.Body != nil { - var err error - body, err = ioutil.ReadAll(req.Body) - if err != nil { - return nil, err - } - } - - headers := map[string]string{} - for name, values := range req.Header { - for _, value := range values { - headers[name] = value - } - } - - // add the forwarded headers we expect to see from an API Gateway request - if _, ok := headers["Host"]; !ok { - host := req.Host - if strings.Contains(host, ":") { - host = host[:strings.Index(host, ":")] - } - headers["Host"] = host - } - headers["X-Forwarded-Proto"] = req.URL.Scheme - headers["X-Forwarded-Port"] = req.URL.Port() - - query := map[string]string{} - for name, values := range req.URL.Query() { - for _, value := range values { - query[name] = value - } - } - - pathParams := mux.Vars(req) - if len(pathParams) == 0 { - pathParams = nil - } - - event := &Event{ - HTTPMethod: req.Method, - Body: string(body), - Headers: headers, - QueryStringParams: query, - Path: req.URL.Path, - Resource: req.URL.Path, - PathParameters: pathParams, - IsBase64Encoded: isBase64Encoded, - } - - event.RequestContext.Identity.SourceIP = req.RemoteAddr - event.RequestContext.ResourcePath = req.URL.Path - event.RequestContext.HTTPMethod = req.Method - event.RequestContext.Stage = "prod" - - return event, nil - -} - -// JSON returns the event as a JSON string -func (e *Event) JSON() (string, error) { - - data, err := json.Marshal(e) - if err != nil { - return "", err - } - - return string(data), nil - -} diff --git a/router/event_test.go b/router/event_test.go deleted file mode 100644 index c78bdf02ae..0000000000 --- a/router/event_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package router - -import ( - "bytes" - "net/http" - "net/http/httptest" - - "github.com/awslabs/goformation/cloudformation" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("Event", func() { - Describe("PathParameters", func() { - var r *ServerlessRouter - BeforeEach(func() { - r = NewServerlessRouter(false) - }) - - Context("with path parameters on the route", func() { - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - Events: map[string]cloudformation.AWSServerlessFunction_EventSource{ - "GetRequest": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/get", - Method: "get", - }, - }, - }, - "GetRequestsWithParams": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/get/{parameter}", - Method: "get", - }, - }, - }, - }, - } - - Context("and path parameters on the request", func() { - req, _ := http.NewRequest("GET", "/get/1", new(bytes.Buffer)) - - It("returns the parameters on the event", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(e.PathParameters).To(HaveKeyWithValue("parameter", "1")) - }) - - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - }) - - Context("and path parameters on the request", func() { - req, _ := http.NewRequest("GET", "/get/1", new(bytes.Buffer)) - - It("returns stage property with value \"prod\"", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(e.RequestContext.Stage).To(BeIdenticalTo("prod")) - }) - - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - }) - - Context("and no path parameters on the request", func() { - req, _ := http.NewRequest("GET", "/get", new(bytes.Buffer)) - - It("returns nil for PathParameters on the event", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(e.PathParameters).To(BeNil()) - }) - - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - }) - - Context("Includes forwarded headers", func() { - req, _ := http.NewRequest("GET", "http://localhost:3000/get", new(bytes.Buffer)) - - It("Includes Host header", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - hostHeader, ok := e.Headers["Host"] - Expect(ok).To(BeTrue()) - Expect(hostHeader).To(BeIdenticalTo("localhost")) - }) - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - - It("Includes X-Forwarded-Proto header", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - hostHeader, ok := e.Headers["X-Forwarded-Proto"] - Expect(ok).To(BeTrue()) - Expect(hostHeader).To(BeIdenticalTo("http")) - }) - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - - It("Includes X-Forwarded-Port header", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - hostHeader, ok := e.Headers["X-Forwarded-Port"] - Expect(ok).To(BeTrue()) - Expect(hostHeader).To(BeIdenticalTo("3000")) - }) - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - }) - }) - - Context("with no parameters on the route", func() { - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - Events: map[string]cloudformation.AWSServerlessFunction_EventSource{ - "GetRequest": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/get", - Method: "get", - }, - }, - }, - }, - } - - req, _ := http.NewRequest("GET", "/get", new(bytes.Buffer)) - - It("returns nil for PathParameters on the event", func() { - r.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(e.PathParameters).To(BeNil()) - }) - - rec := httptest.NewRecorder() - r.Router().ServeHTTP(rec, req) - }) - }) - }) -}) diff --git a/router/function.go b/router/function.go deleted file mode 100644 index 5602fa081b..0000000000 --- a/router/function.go +++ /dev/null @@ -1,37 +0,0 @@ -package router - -import ( - "github.com/awslabs/goformation/cloudformation" -) - -// AWSServerlessFunction wraps GoFormation's AWS::Serverless::Function definition -// and adds some convenience methods for extracting the ServerlessRouterMount's -// from the event sources. -type AWSServerlessFunction struct { - *cloudformation.AWSServerlessFunction - handler EventHandlerFunc -} - -// Mounts fetches an array of the ServerlessRouterMount's for this API. -// These contain the path, method and handler function for each mount point. -func (f *AWSServerlessFunction) Mounts() ([]*ServerlessRouterMount, error) { - - mounts := []*ServerlessRouterMount{} - - for name, event := range f.Events { - if event.Type == "Api" { - if event.Properties != nil && event.Properties.ApiEvent != nil { - mounts = append(mounts, &ServerlessRouterMount{ - Name: name, - Path: event.Properties.ApiEvent.Path, - Method: event.Properties.ApiEvent.Method, - Handler: f.handler, - Function: f, - }) - } - } - } - - return mounts, nil - -} diff --git a/router/function_test.go b/router/function_test.go deleted file mode 100644 index 930fddb587..0000000000 --- a/router/function_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package router_test - -import ( - "net/http" - "net/http/httptest" - - "github.com/awslabs/aws-sam-local/router" - "github.com/awslabs/goformation/cloudformation" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gstruct" -) - -var _ = Describe("Function", func() { - - Context("with a GoFormation AWS::Serverless::Function", func() { - - r := router.NewServerlessRouter(false) - - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - Events: map[string]cloudformation.AWSServerlessFunction_EventSource{ - "GetRequests": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/get", - Method: "get", - }, - }, - }, - "PostRequests": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/post", - Method: "post", - }, - }, - }, - "AnyRequests": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/any", - Method: "any", - }, - }, - }, - "ProxyResource": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/proxy/{proxy+}", - Method: "any", - }, - }, - }, - }, - } - - err := r.AddFunction(function, func(w http.ResponseWriter, e *router.Event) { - w.WriteHeader(200) - w.Write([]byte("ok")) - }) - - It("should add the function successfully", func() { - Expect(err).To(BeNil()) - }) - - mounts := r.Mounts() - It("should find three API event sources", func() { - Expect(mounts).To(HaveLen(4)) - }) - - It("should have the correct values for an event with GET http method", func() { - Expect(mounts).To(ContainElement(PointTo(MatchFields(IgnoreExtras, Fields{ - "Name": Equal("GetRequests"), - "Path": Equal("/get"), - "Method": Equal("get"), - })))) - }) - - It("should have the correct values for an event with POST http method", func() { - Expect(mounts).To(ContainElement(PointTo(MatchFields(IgnoreExtras, Fields{ - "Name": Equal("PostRequests"), - "Path": Equal("/post"), - "Method": Equal("post"), - })))) - }) - - It("should have the correct values for an event with ANY http method", func() { - Expect(mounts).To(ContainElement(PointTo(MatchFields(IgnoreExtras, Fields{ - "Name": Equal("AnyRequests"), - "Path": Equal("/any"), - "Method": Equal("any"), - })))) - }) - - It("should have the correct values for an event with catchAll path", func() { - Expect(mounts).To(ContainElement(PointTo(MatchFields(IgnoreExtras, Fields{ - "Name": Equal("ProxyResource"), - "Path": Equal("/proxy/{proxy+}"), - "Method": Equal("any"), - })))) - }) - - It("should respond to HTTP requests on GET /get", func() { - req, _ := http.NewRequest("GET", "/get", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - Expect(rr.Body.String()).To(Equal("ok")) - }) - - It("should respond to HTTP requests on POST /post", func() { - req, _ := http.NewRequest("POST", "/post", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - Expect(rr.Body.String()).To(Equal("ok")) - }) - - It("should respond to HTTP requests on POST /post", func() { - req, _ := http.NewRequest("POST", "/post", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - Expect(rr.Body.String()).To(Equal("ok")) - }) - - It("should respond with a 404 to HTTP requests on an invalid path", func() { - req, _ := http.NewRequest("GET", "/invalid", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusNotFound)) - }) - - It("should respond to GET requests on any path in catch-all resource", func() { - req, _ := http.NewRequest("GET", "/proxy/hello/world", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - }) - - It("should respond to GET requests on a single sub-resource", func() { - req, _ := http.NewRequest("GET", "/proxy/hello", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - }) - - It("should not respond to base proxy path, only sub-resources", func() { - req, _ := http.NewRequest("GET", "/proxy", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusNotFound)) - }) - - methods := []string{"OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} - for _, method := range methods { - It("should respond to HTTP requests on "+method+" /any", func() { - req, _ := http.NewRequest(method, "/any", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - Expect(rr.Body.String()).To(Equal("ok")) - }) - } - - }) - - Context("with a GoFormation AWS::Serverless::Function and prefix matching", func() { - - r := router.NewServerlessRouter(true) - - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - Events: map[string]cloudformation.AWSServerlessFunction_EventSource{ - "AnyRequests": cloudformation.AWSServerlessFunction_EventSource{ - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/any", - Method: "any", - }, - }, - }, - }, - } - - err := r.AddFunction(function, func(w http.ResponseWriter, e *router.Event) { - w.WriteHeader(200) - w.Write([]byte("ok")) - }) - - It("should add the function successfully", func() { - Expect(err).To(BeNil()) - }) - - mounts := r.Mounts() - It("should find three API event sources", func() { - Expect(mounts).To(HaveLen(1)) - }) - - It("should have the correct values for an event with ANY http method", func() { - Expect(mounts).To(ContainElement(PointTo(MatchFields(IgnoreExtras, Fields{ - "Name": Equal("AnyRequests"), - "Path": Equal("/any"), - "Method": Equal("any"), - })))) - }) - - It("should respond with a 404 to HTTP requests on an invalid path", func() { - req, _ := http.NewRequest("GET", "/invalid", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusNotFound)) - }) - - methods := []string{"OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} - for _, method := range methods { - It("should respond to HTTP requests on "+method+" /any", func() { - req, _ := http.NewRequest(method, "/any", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusOK)) - }) - - It("should respond to HTTP requests on "+method+" /any/foo", func() { - req, _ := http.NewRequest(method, "/any/foo", nil) - rr := httptest.NewRecorder() - r.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusNotFound)) - }) - } - - }) - - Context("with a GoFormation AWS::Serverless::Function that has no 'Api' event sources", func() { - - r := router.NewServerlessRouter(false) - - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - } - - err := r.AddFunction(function, func(w http.ResponseWriter, e *router.Event) { - w.WriteHeader(200) - w.Write([]byte("ok")) - }) - - It("should throw a ErrNoEventsFound error", func() { - Expect(err).To(MatchError(router.ErrNoEventsFound)) - }) - - }) - -}) diff --git a/router/integration.go b/router/integration.go deleted file mode 100644 index 2f6785be6e..0000000000 --- a/router/integration.go +++ /dev/null @@ -1,48 +0,0 @@ -package router - -import ( - "regexp" - "fmt" -) - -type ApiGatewayIntegration struct { - Uri string `json:"uri"` - PassthroughBehavior string `json:"passthroughBehavior"` - Type string `json:"type"` -} - -func (i *ApiGatewayIntegration) GetFunctionArn() (*LambdaFunctionArn, error) { - // arn:aws:apigateway:us-west-2:lambda:path//2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations - firstMatch, err := getFirstMatch(`.*/functions/(.*)/invocations`, i.Uri) - - if err != nil { - return nil, err - } - - return &LambdaFunctionArn{ Arn: firstMatch }, nil -} - -type LambdaFunctionArn struct { - Arn string -} - -func (a *LambdaFunctionArn) GetFunctionName() (string, error) { - firstMatch, err := getFirstMatch(`.*:function:(.*)/invocations`, a.Arn) - - if err != nil { - return "", err - } - - return firstMatch, nil -} - -func getFirstMatch(regex string, value string) (string, error) { - re := regexp.MustCompile(regex) - match := re.FindStringSubmatch(value) - - if len(match) < 2 { - return "", fmt.Errorf("Could not find match in %s", value) - } - - return match[1], nil -} \ No newline at end of file diff --git a/router/mount.go b/router/mount.go deleted file mode 100644 index 7878ed1e05..0000000000 --- a/router/mount.go +++ /dev/null @@ -1,95 +0,0 @@ -package router - -import ( - "encoding/base64" - "io/ioutil" - "mime" - "net/http" - "strings" - "unicode/utf8" - "log" - "fmt" -) - -const MuxPathRegex = ".+" -var HttpMethods = []string{"OPTIONS", "GET", "HEAD", "POST", "PUT", "DELETE", "PATCH"} - -// EventHandlerFunc is similar to Go http.Handler but it receives an event from API Gateway -// instead of http.Request -type EventHandlerFunc func(http.ResponseWriter, *Event) - -// ServerlessRouterMount represents a single mount point on the API -// Such as '/path', the HTTP method, and the function to resolve it -type ServerlessRouterMount struct { - Name string - Function *AWSServerlessFunction - Handler EventHandlerFunc - Path string - Method string - BinaryMediaTypes []string - - // authorization settings - AuthType string - AuthFunction *AWSServerlessFunction - IntegrationArn *LambdaFunctionArn -} - -// Returns the wrapped handler to encode the body as base64 when binary -// media types contains Content-Type -func (m *ServerlessRouterMount) WrappedHandler() http.HandlerFunc { - return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - contentType := req.Header.Get("Content-Type") - mediaType, _, err := mime.ParseMediaType(contentType) - binaryContent := false - - if err == nil { - for _, value := range m.BinaryMediaTypes { - if value != "" && value == mediaType { - binaryContent = true - break - } - } - } - - if binaryContent { - if body, err := ioutil.ReadAll(req.Body); err == nil && !utf8.Valid(body) { - req.Body = ioutil.NopCloser(strings.NewReader(base64.StdEncoding.EncodeToString(body))) - } else { - req.Body = ioutil.NopCloser(strings.NewReader(string(body))) - } - } - - event, err := NewEvent(req, binaryContent) - if err != nil { - msg := fmt.Sprintf("Error creating a new event: %s", err) - log.Println(msg) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{ "message": "Internal server error" }`)) - } else { - m.Handler(w, event) - } - }) -} - -// Methods gets an array of HTTP methods from a AWS::Serverless::Function -// API event source method declaration (which could include 'any') -func (m *ServerlessRouterMount) Methods() []string { - switch strings.ToUpper(m.Method) { - case "ANY": - return HttpMethods - default: - return []string{strings.ToUpper(m.Method)} - } -} - -// Returns the mount path adjusted for mux syntax. For example, if the -// SAM template specifies /{proxy+} we replace that with /{proxy:.*} -func (m *ServerlessRouterMount) GetMuxPath() string { - outputPath := m.Path - - if strings.Contains(outputPath, "+") { - outputPath = strings.Replace(outputPath, "+", ":" + MuxPathRegex, -1) - } - - return outputPath -} \ No newline at end of file diff --git a/router/mount_test.go b/router/mount_test.go deleted file mode 100644 index bd6f6d3550..0000000000 --- a/router/mount_test.go +++ /dev/null @@ -1,77 +0,0 @@ -package router_test - -import ( - . "github.com/awslabs/aws-sam-local/router" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ServerlessRouterMount", func() { - - Context("with a method in uppercase", func() { - - m := ServerlessRouterMount{ - Path: "/test", - Method: "GET", - } - - methods := m.Methods() - It("should have the correct HTTP method", func() { - Expect(methods).To(HaveLen(1)) - Expect(methods).To(ContainElement("GET")) - }) - - }) - - Context("with a method in lowercase", func() { - - m := ServerlessRouterMount{ - Path: "/test", - Method: "get", - } - - methods := m.Methods() - It("should have the correct HTTP method", func() { - Expect(methods).To(HaveLen(1)) - Expect(methods).To(ContainElement("GET")) - }) - - }) - - Context("with method 'any'", func() { - - m := ServerlessRouterMount{ - Path: "/test", - Method: "any", - } - - methods := m.Methods() - It("should have the correct HTTP method", func() { - Expect(methods).To(HaveLen(7)) - Expect(methods).To(ContainElement("OPTIONS")) - Expect(methods).To(ContainElement("GET")) - Expect(methods).To(ContainElement("HEAD")) - Expect(methods).To(ContainElement("POST")) - Expect(methods).To(ContainElement("PUT")) - Expect(methods).To(ContainElement("DELETE")) - Expect(methods).To(ContainElement("PATCH")) - }) - - }) - - Context("Catch-all resource path", func() { - m := ServerlessRouterMount{ - Path: "/{proxy+}", - Method: "any", - } - - It("should replace + correctly", func() { - Expect(m.GetMuxPath()).To(Equal("/{proxy:" + MuxPathRegex + "}")) - }) - It("should support all methods", func() { - Expect(m.Methods()).To(HaveLen(7)) - }) - }) - -}) diff --git a/router/router.go b/router/router.go deleted file mode 100644 index fa5279d18a..0000000000 --- a/router/router.go +++ /dev/null @@ -1,136 +0,0 @@ -package router - -import ( - "errors" - "net/http" - "strings" - - "github.com/awslabs/goformation/cloudformation" - "github.com/gorilla/mux" - //"github.com/docker/docker/api/types/mount" -) - -// ErrNoEventsFound is thrown if a AWS::Serverless::Function is added to this -// router, but no API event sources exist for it. -var ErrNoEventsFound = errors.New("no events with type 'Api' were found") - -// ServerlessRouter takes AWS::Serverless::Function and AWS::Serverless::API objects -// and creates a Go http.Handler with the correct paths/methods mounted -type ServerlessRouter struct { - mux *mux.Router - mounts []*ServerlessRouterMount - usePrefix bool -} - -// NewServerlessRouter creates a new instance of ServerlessRouter. -// If usePrefix is true then route matching is done using prefix instead of exact match -func NewServerlessRouter(usePrefix bool) *ServerlessRouter { - return &ServerlessRouter{ - mux: mux.NewRouter(), - mounts: []*ServerlessRouterMount{}, - usePrefix: usePrefix, - } -} - -// AddFunction adds a AWS::Serverless::Function to the router and mounts all of it's -// event sources that have type 'Api' -func (r *ServerlessRouter) AddFunction(f *cloudformation.AWSServerlessFunction, handler EventHandlerFunc) error { - - // Wrap GoFormation's AWS::Serverless::Function definition in our own, which provides - // convenience methods for extracting the ServerlessRouterMount(s) from it. - function := &AWSServerlessFunction{f, handler} - mounts, err := function.Mounts() - if err != nil { - return err - } - - if len(mounts) < 1 { - return ErrNoEventsFound - } - - //r.mounts = append(r.mounts, mounts...) - err = r.mergeMounts(mounts) - if err != nil { - return err - } - - return nil - -} - -// AddAPI adds a AWS::Serverless::Api resource to the router, and mounts all of it's API definition -func (r *ServerlessRouter) AddAPI(a *cloudformation.AWSServerlessApi) error { - - // Wrap GoFormation's AWS::Serverless::Api definition in our own, which provides - // convenience methods for extracting the ServerlessRouterMount(s) from it. - api := &AWSServerlessApi{a} - mounts, err := api.Mounts() - if err != nil { - return err - } - - //r.mounts = append(r.mounts, mounts...) - err = r.mergeMounts(mounts) - if err != nil { - return err - } - - return nil -} - -// merges the various mount paths. mounts could be coming from a function as well as API -// definition. Mounts defined by an API do not have a handler, only a function ARN. -func (r *ServerlessRouter) mergeMounts(newMounts []*ServerlessRouterMount) error { - for _, newMount := range newMounts { - newMountExists := false - - for _, existingMount := range r.mounts { - if newMount.Path == existingMount.Path && strings.ToLower(newMount.Method) == strings.ToLower(existingMount.Method) { - newMountExists = true - // if the new mount has a valid handler I override the existing one anyway - if newMount.Handler != nil { - existingMount.Handler = newMount.Handler - existingMount.Function = newMount.Function - } - } - } - - if !newMountExists { - if newMount.Handler == nil { - newMount.Handler = r.missingFunctionHandler() - } - r.mounts = append(r.mounts, newMount) - } - } - return nil -} - -// AddStaticDir mounts a static directory provided, at the mount point also provided -func (r *ServerlessRouter) AddStaticDir(dirname string) { - r.mux.NotFoundHandler = http.FileServer(http.Dir(dirname)) -} - -// Router returns the Go http.Handler for the router, to be passed to http.ListenAndServe() -func (r *ServerlessRouter) Router() http.Handler { - - // Mount all of the things! - for _, mount := range r.Mounts() { - r.mux.Handle(mount.GetMuxPath(), mount.WrappedHandler()).Methods(mount.Methods()...) - } - - return r.mux - -} - -// Mounts returns a list of the mounts associated with this router -func (r *ServerlessRouter) Mounts() []*ServerlessRouterMount { - return r.mounts -} - -func (r *ServerlessRouter) missingFunctionHandler() func(http.ResponseWriter, *Event) { - return func(w http.ResponseWriter, event *Event) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusBadGateway) - w.Write([]byte(`{ "message": "No function defined for resource method" }`)) - } -} diff --git a/router/router_suite_test.go b/router/router_suite_test.go deleted file mode 100644 index 71e2054f58..0000000000 --- a/router/router_suite_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package router_test - -import ( - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - - "testing" -) - -func TestRouter(t *testing.T) { - RegisterFailHandler(Fail) - RunSpecs(t, "Router Suite") -} diff --git a/router/router_test.go b/router/router_test.go deleted file mode 100644 index be9667d63a..0000000000 --- a/router/router_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package router - -import ( - "bytes" - "encoding/base64" - "net/http" - "net/http/httptest" - "strings" - - "github.com/awslabs/goformation" - "github.com/awslabs/goformation/cloudformation" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("ServerlessRouter", func() { - Context("With a swagger template that has empty mounts", func() { - It("Mounts the missing function handler", func() { - template, err := goformation.Open("../test/templates/api-missing-method.yaml") - - Expect(err).To(BeNil()) - Expect(len(template.Resources)).To(Equal(2)) - mux := NewServerlessRouter(false) - templateApis := template.GetAllAWSServerlessApiResources() - - Expect(len(templateApis)).To(Equal(1)) - - for _, api := range templateApis { - err := mux.AddAPI(&api) - Expect(err).To(BeNil()) - } - - mounts := mux.Mounts() - - Expect(mounts).ToNot(BeNil()) - Expect(len(mounts)).To(Equal(2)) - - req, _ := http.NewRequest("GET", "/badget", nil) - rr := httptest.NewRecorder() - mux.Router().ServeHTTP(rr, req) - Expect(rr.Code).To(Equal(http.StatusBadGateway)) - }) - }) - - Context("with SAM template and x-amazon-apigateway-binary-media-types defined in it", func() { - const input = `{ - "Resources": { - "MyApi": { - "Type": "AWS::Serverless::Api", - "Properties": { - "DefinitionBody": { - "swagger": "2.0", - "paths": { - "/post": { - "post": { - "x-amazon-apigateway-integration": { - "httpMethod": "POST", - "type": "aws_proxy", - "uri": { - "Fn::Sub": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/dummy/invocations" - } - }, - "responses": {} - } - } - }, - "x-amazon-apigateway-binary-media-types": ["multipart/form-data"] - } - } - } - } - }` - template, _ := goformation.ParseJSON([]byte(input)) - - function := &cloudformation.AWSServerlessFunction{ - Runtime: "nodejs6.10", - Events: map[string]cloudformation.AWSServerlessFunction_EventSource{ - "PostRequest": { - Type: "Api", - Properties: &cloudformation.AWSServerlessFunction_Properties{ - ApiEvent: &cloudformation.AWSServerlessFunction_ApiEvent{ - Path: "/post", - Method: "post", - }, - }, - }, - }, - } - templateApis := template.GetAllAWSServerlessApiResources() - - It("returns the base64 encoded body on a binary request", func() { - mux := NewServerlessRouter(false) - - for _, api := range templateApis { - err := mux.AddAPI(&api) - Expect(err).To(BeNil()) - } - data := []byte{'\xe3'} - req, _ := http.NewRequest("POST", "/post", bytes.NewReader(data)) - req.Header.Add("Content-Type", "multipart/form-data; boundary=something") - - mux.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(string(e.Body)).To(Equal(base64.StdEncoding.EncodeToString(data))) - }) - - rec := httptest.NewRecorder() - mux.Router().ServeHTTP(rec, req) - }) - - It("returns the text body on a text request", func() { - mux := NewServerlessRouter(false) - - for _, api := range templateApis { - err := mux.AddAPI(&api) - Expect(err).To(BeNil()) - } - text := "foo" - req, _ := http.NewRequest("POST", "/post", strings.NewReader(text)) - req.Header.Add("Content-Type", "multipart/form-data; boundary=something") - - mux.AddFunction(function, func(w http.ResponseWriter, e *Event) { - Expect(string(e.Body)).To(Equal(text)) - }) - - rec := httptest.NewRecorder() - mux.Router().ServeHTTP(rec, req) - }) - }) -}) diff --git a/runtime.go b/runtime.go deleted file mode 100644 index 75e74315b6..0000000000 --- a/runtime.go +++ /dev/null @@ -1,856 +0,0 @@ -package main - -import ( - "archive/zip" - "bytes" - "io" - "io/ioutil" - "log" - "mime" - "net/http" - "os" - "path/filepath" - "regexp" - "strconv" - "sync" - "time" - - "golang.org/x/net/context" - - "strings" - - "encoding/base64" - "encoding/json" - "fmt" - "path" - - "os/signal" - "syscall" - - "github.com/awslabs/aws-sam-local/router" - "github.com/awslabs/goformation/cloudformation" - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/stdcopy" - "github.com/docker/docker/pkg/term" - "github.com/docker/go-connections/nat" - "github.com/fatih/color" - "github.com/imdario/mergo" - "github.com/mattn/go-colorable" - "github.com/pkg/errors" -) - -// Invoker is a simple interface to help with testing runtimes -type Invoker interface { - Invoke(string, string) (io.Reader, io.Reader, error) - InvokeHTTP(string) func(http.ResponseWriter, *router.Event) - CleanUp() -} - -// Runtime contains a reference to a single container for a specific runtime. It is used to invoke functions multiple times against a single container. -type Runtime struct { - LogicalID string - ID string - Name string - Image string - Cwd string - DecompressedCwd string - Function cloudformation.AWSServerlessFunction - EnvOverrideFile string - DebugPort string - Context context.Context - Client *client.Client - TimeoutTimer *time.Timer - Logger io.Writer - DockerNetwork string -} - -var ( - // ErrRuntimeNotDownloaded is thrown when NewRuntime() is called, but the requested - // runtime has not been downloaded - ErrRuntimeNotDownloaded = errors.New("requested runtime has not been downloaded") - - // ErrRuntimeNotSupported is thrown with the requested runtime is not yet supported - ErrRuntimeNotSupported = errors.New("unsupported runtime") -) - -var runtimeName = struct { - nodejs string - nodejs43 string - nodejs610 string - nodejs810 string - python27 string - python36 string - java8 string - go1x string - dotnetcore20 string -}{ - nodejs: "nodejs", - nodejs43: "nodejs4.3", - nodejs610: "nodejs6.10", - nodejs810: "nodejs8.10", - python27: "python2.7", - python36: "python3.6", - java8: "java8", - go1x: "go1.x", - dotnetcore20: "dotnetcore2.0", -} - -var runtimeImageFor = map[string]string{ - runtimeName.nodejs: "lambci/lambda:nodejs", - runtimeName.nodejs43: "lambci/lambda:nodejs4.3", - runtimeName.nodejs610: "lambci/lambda:nodejs6.10", - runtimeName.nodejs810: "lambci/lambda:nodejs8.10", - runtimeName.python27: "lambci/lambda:python2.7", - runtimeName.python36: "lambci/lambda:python3.6", - runtimeName.java8: "lambci/lambda:java8", - runtimeName.go1x: "lambci/lambda:go1.x", - runtimeName.dotnetcore20: "lambci/lambda:dotnetcore2.0", -} - -// NewRuntimeOpt contains parameters that are passed to the NewRuntime method -type NewRuntimeOpt struct { - Cwd string - LogicalID string - Function cloudformation.AWSServerlessFunction - EnvOverrideFile string - DebugPort string - Logger io.Writer - SkipPullImage bool - DockerNetwork string -} - -// NewRuntime instantiates a Lambda runtime container -func NewRuntime(opt NewRuntimeOpt) (Invoker, error) { - // Determine which docker image to use for the provided runtime - image, found := runtimeImageFor[opt.Function.Runtime] - if !found { - return nil, ErrRuntimeNotSupported - } - - cli, err := client.NewEnvClient() - if err != nil { - return nil, err - } - - r := &Runtime{ - LogicalID: opt.LogicalID, - Name: opt.Function.Runtime, - Cwd: getWorkingDir(opt.Cwd), - Image: image, - Function: opt.Function, - EnvOverrideFile: opt.EnvOverrideFile, - DebugPort: opt.DebugPort, - Context: context.Background(), - Client: cli, - Logger: opt.Logger, - DockerNetwork: opt.DockerNetwork, - } - - // Check if we have the required Docker image for this runtime - filter := filters.NewArgs() - filter.Add("reference", r.Image) - images, err := cli.ImageList(r.Context, types.ImageListOptions{ - Filters: filter, - }) - if err != nil { - return nil, err - } - - // By default, pull images unless we are told not to - pullImage := true - - if opt.SkipPullImage { - log.Printf("Requested to skip pulling images ...\n") - pullImage = false - } - - // However, if we don't have the image we will need it... - if len(images) == 0 { - log.Printf("Runtime image missing, will pull....\n") - pullImage = true - } - - if pullImage { - log.Printf("Fetching %s image for %s runtime...\n", r.Image, opt.Function.Runtime) - progress, err := cli.ImagePull(r.Context, r.Image, types.ImagePullOptions{}) - if len(images) < 0 && err != nil { - log.Fatalf("Could not fetch %s Docker image\n%s", r.Image, err) - return nil, err - } - - if err != nil { - log.Printf("Could not fetch %s Docker image: %s\n", r.Image, err) - } else { - - // Use Docker's standard progressbar to show image pull progress. - // However there is a bug that we are working around. We'll do the same - // as Docker does, and temporarily set the TERM to a non-existant - // terminal - // More info here: - // https://github.com/Nvveen/Gotty/pull/1 - - origTerm := os.Getenv("TERM") - os.Setenv("TERM", "eifjccgifcdekgnbtlvrgrinjjvfjggrcudfrriivjht") - defer os.Setenv("TERM", origTerm) - - // Show the Docker pull messages in green - color.Output = colorable.NewColorableStderr() - color.Set(color.FgGreen) - defer color.Unset() - - jsonmessage.DisplayJSONMessagesStream(progress, os.Stderr, os.Stderr.Fd(), term.IsTerminal(os.Stderr.Fd()), nil) - } - } - - return r, nil - -} - -func overrideHostConfig(cfg *container.HostConfig) error { - - const dotfile = ".config/aws-sam-local/container-config.json" - const eMsg = "unable to use container host config override file from '$HOME/%s'" - - homeDir := os.Getenv("HOME") - if len(homeDir) == 0 { - return errors.Wrapf(errors.New("HOME env variable is not set"), eMsg, dotfile) - } - - reader, err := os.Open(path.Join(homeDir, dotfile)) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return errors.Wrapf(err, eMsg, dotfile) - } - defer reader.Close() - - override := new(container.HostConfig) - if err := json.NewDecoder(reader).Decode(override); err != nil { - return errors.Wrapf(err, eMsg, dotfile) - } - - return errors.Wrapf(mergo.MergeWithOverwrite(cfg, override), eMsg, dotfile) -} - -func (r *Runtime) getHostConfig() (*container.HostConfig, error) { - - // Check if there is a decompressed archive directory we should - // be using instead of the normal working directory (e.g. if a - // ZIP/JAR archive was specified as the CodeUri) - mount := r.Cwd - if r.DecompressedCwd != "" { - mount = r.DecompressedCwd - } - - // If the path is a Windows style one, convert it to the format that Docker Toolbox requires. - mount = convertWindowsPath(mount) - - log.Printf("Mounting %s as /var/task:ro inside runtime container\n", mount) - host := &container.HostConfig{ - Resources: container.Resources{ - Memory: int64(r.Function.MemorySize * 1024 * 1024), - }, - Binds: []string{ - fmt.Sprintf("%s:/var/task:ro", mount), - }, - PortBindings: r.getDebugPortBindings(), - } - - if err := overrideHostConfig(host); err != nil { - log.Print(err) - } - - return host, nil -} - -// Invoke runs a Lambda function within the runtime with the provided event -// payload and returns a pair of io.Readers for it's stdout (callback results) -// and stderr (runtime logs). -func (r *Runtime) Invoke(event string, profile string) (io.Reader, io.Reader, error) { - - log.Printf("Invoking %s (%s)\n", r.Function.Handler, r.Name) - - // If the CodeUri has been specified as a .jar or .zip file, unzip it on the fly - if r.Function.CodeUri != nil && r.Function.CodeUri.String != nil { - codeuri := filepath.Join(r.Cwd, *r.Function.CodeUri.String) - - // Check if the CodeUri exists on the local filesystem - if _, err := os.Stat(codeuri); err == nil { - // It does exist - maybe it's a ZIP/JAR that we need to decompress on the fly - if strings.HasSuffix(codeuri, ".jar") || strings.HasSuffix(codeuri, ".zip") { - log.Printf("Decompressing %s\n", codeuri) - decompressedDir, err := decompressArchive(codeuri) - if err != nil { - log.Printf("ERROR: Failed to decompress archive: %s\n", err) - return nil, nil, fmt.Errorf("failed to decompress archive: %s", err) - } - r.DecompressedCwd = decompressedDir - } else { - // We have a CodeUri that exists locally, but isn't a ZIP/JAR. - // Just append it to the working directory - r.Cwd = codeuri - } - } else { - // The CodeUri specified doesn't exist locally. It could be - // an S3 location (s3://.....), so just ignore it. - } - } - - // If the timeout hasn't been set for the function in the SAM template - // then default to 3 seconds (as per SAM specification). - // This needs to be done before environment variables are generated for - // the Lambda runtime so that the correct AWS_LAMBDA_FUNCTION_TIMEOUT is used - if r.Function.Timeout <= 0 { - r.Function.Timeout = 3 - } - - // If the memory size hasn't been set for the function in the SAM template - // then default to 128MB (as per SAM specification). - // This needs to be done before environment variables are generated for - // the Lambda runtime so that the correct AWS_LAMBDA_FUNCTION_MEMORY_SIZE is used - if r.Function.MemorySize <= 0 { - r.Function.MemorySize = 128 - } - - // Define the container options - config := &container.Config{ - WorkingDir: "/var/task", - Image: r.Image, - Tty: false, - ExposedPorts: r.getDebugExposedPorts(), - Entrypoint: r.getDebugEntrypoint(), - Cmd: []string{r.Function.Handler, event}, - Env: func() []string { - result := []string{} - for k, v := range getEnvironmentVariables(r.LogicalID, &r.Function, r.EnvOverrideFile, profile) { - result = append(result, k+"="+v) - } - return result - }(), - } - - host, err := r.getHostConfig() - if err != nil { - return nil, nil, err - } - - resp, err := r.Client.ContainerCreate(r.Context, config, host, nil, "") - if err != nil { - return nil, nil, err - } - - r.ID = resp.ID - - if r.DockerNetwork != "" { - if err := r.Client.NetworkConnect(r.Context, r.DockerNetwork, resp.ID, nil); err != nil { - return nil, nil, err - } - log.Printf("Connecting container %s to network %s", resp.ID, r.DockerNetwork) - } - - // Invoke the container - if err := r.Client.ContainerStart(r.Context, resp.ID, types.ContainerStartOptions{}); err != nil { - return nil, nil, err - } - - // Attach to the container to read the stdout/stderr stream - attach, err := r.Client.ContainerAttach(r.Context, resp.ID, types.ContainerAttachOptions{ - Stream: true, - Stdin: false, - Stdout: true, - Stderr: true, - Logs: true, - }) - - // As per the Docker SDK documentation, when attaching to a container - // the resulting io.Reader stream is has stdin, stdout and stderr muxed - // into a single stream, with a 8 byte header defining the type/size. - // Demux the stream into separate io.Readers for stdout and stderr - // src: https://docs.docker.com/engine/api/v1.28/#operation/ContainerAttach - stdout, stderr, err := demuxDockerStream(attach.Reader) - if err != nil { - return nil, nil, err - } - - if len(r.DebugPort) == 0 { - r.setupTimeoutTimer(stdout, stderr) - } else { - r.setupInterruptHandler(stdout, stderr) - } - - return stdout, stderr, nil - -} - -func (r *Runtime) setupTimeoutTimer(stdout, stderr io.ReadCloser) { - - // Start a timer, we'll use this to abort the function if it runs beyond the specified timeout - timeout := time.Duration(r.Function.Timeout) * time.Second - - r.TimeoutTimer = time.NewTimer(timeout) - go func() { - <-r.TimeoutTimer.C - log.Printf("Function %s timed out after %d seconds", r.Function.Handler, timeout/time.Second) - stderr.Close() - stdout.Close() - r.CleanUp() - }() -} - -func (r *Runtime) setupInterruptHandler(stdout, stderr io.ReadCloser) { - iChan := make(chan os.Signal, 2) - signal.Notify(iChan, os.Interrupt, syscall.SIGTERM) - go func() { - <-iChan - log.Printf("Execution of function %q was interrupted", r.Function.Handler) - stderr.Close() - stdout.Close() - r.CleanUp() - os.Exit(0) - }() -} - -func (r *Runtime) getDebugPortBindings() nat.PortMap { - if len(r.DebugPort) == 0 { - return nil - } - return nat.PortMap{ - nat.Port(r.DebugPort): []nat.PortBinding{{HostPort: r.DebugPort}}, - } -} - -func (r *Runtime) getDebugExposedPorts() nat.PortSet { - if len(r.DebugPort) == 0 { - return nil - } - return nat.PortSet{nat.Port(r.DebugPort): {}} -} - -func (r *Runtime) getDebugEntrypoint() (overrides []string) { - if len(r.DebugPort) == 0 { - return - } - - debuggerArgs := os.Getenv("DEBUGGER_ARGS") - debuggerArgsArray := []string{} - if len(debuggerArgs) > 0 { - debuggerArgsArray = strings.Split(debuggerArgs, " ") - } - - switch r.Name { - // configs from: https://github.com/lambci/docker-lambda - // to which we add the extra debug mode options - case runtimeName.java8: - overrides = []string{ - "/usr/bin/java", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, - "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address="+r.DebugPort, - "-XX:MaxHeapSize=1336935k", - "-XX:MaxMetaspaceSize=157286k", - "-XX:ReservedCodeCacheSize=78643k", - "-XX:+UseSerialGC", - //"-Xshare:on", doesn't work in conjunction with the debug options - "-XX:-TieredCompilation", - "-Djava.net.preferIPv4Stack=true", - "-jar", - "/var/runtime/lib/LambdaJavaRTEntry-1.0.jar", - ) - case runtimeName.nodejs: - overrides = []string{ - "/usr/bin/node", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, - "--debug-brk="+r.DebugPort, - "--nolazy", - "--max-old-space-size=1229", - "--max-new-space-size=153", - "--max-executable-size=153", - "--expose-gc", - "/var/runtime/node_modules/awslambda/bin/awslambda", - ) - case runtimeName.nodejs43: - overrides = []string{ - "/usr/local/lib64/node-v4.3.x/bin/node", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, - "--debug-brk="+r.DebugPort, - "--nolazy", - "--max-old-space-size=2547", - "--max-semi-space-size=150", - "--max-executable-size=160", - "--expose-gc", - "/var/runtime/node_modules/awslambda/index.js", - ) - case runtimeName.nodejs610: - overrides = []string{ - "/var/lang/bin/node", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, - "--debug-brk="+r.DebugPort, - "--nolazy", - "--max-old-space-size=2547", - "--max-semi-space-size=150", - "--max-executable-size=160", - "--expose-gc", - "/var/runtime/node_modules/awslambda/index.js", - ) - case runtimeName.nodejs810: - overrides = []string{ - "/var/lang/bin/node", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, - // Node8 requires the host to be explicitly set in order to bind to localhost instead of 127.0.0.1 - // https://github.com/nodejs/node/issues/11591#issuecomment-283110138 - "--inspect-brk=0.0.0.0:"+r.DebugPort, - "--nolazy", - "--expose-gc", - "--max-semi-space-size=150", - "--max-old-space-size=2707", - "/var/runtime/node_modules/awslambda/index.js", - ) - case runtimeName.python27: - overrides = []string{ - "/usr/bin/python2.7", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, "/var/runtime/awslambda/bootstrap.py") - case runtimeName.python36: - overrides = []string{ - "/var/lang/bin/python3.6", - } - overrides = append(overrides, debuggerArgsArray...) - overrides = append(overrides, "/var/runtime/awslambda/bootstrap.py") - } - return -} - -// CleanUp removes the Docker container used by this runtime -func (r *Runtime) CleanUp() { - - // Stop the Lambda timeout timer - if r.TimeoutTimer != nil { - r.TimeoutTimer.Stop() - } - - // Remove the container - r.Client.ContainerKill(r.Context, r.ID, "SIGKILL") - r.Client.ContainerRemove(r.Context, r.ID, types.ContainerRemoveOptions{}) - - // Remove any decompressed archive if there was one (e.g. ZIP/JAR) - if r.DecompressedCwd != "" { - os.RemoveAll(r.DecompressedCwd) - } - -} - -// InvokeHTTP invokes a Lambda function. -func (r *Runtime) InvokeHTTP(profile string) func(http.ResponseWriter, *router.Event) { - - return func(w http.ResponseWriter, event *router.Event) { - var wg sync.WaitGroup - w.Header().Set("Content-Type", "application/json") - acceptHeader, ok := event.Headers["Accept"] - if !ok { - acceptHeader = "" - } - - eventJSON, err := event.JSON() - if err != nil { - msg := fmt.Sprintf("Error invoking %s runtime: %s", r.Function.Runtime, err) - log.Println(msg) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{ "message": "Internal server error" }`)) - return - } - - stdoutTxt, stderrTxt, err := r.Invoke(eventJSON, profile) - if err != nil { - msg := fmt.Sprintf("Error invoking %s runtime: %s", r.Function.Runtime, err) - log.Println(msg) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{ "message": "Internal server error" }`)) - return - } - - wg.Add(1) - var output []byte - go func() { - output = parseOutput(w, stdoutTxt, r.Function.Runtime, &wg, acceptHeader) - }() - - wg.Add(1) - go func() { - // Finally, copy the container stdout and stderr (runtime logs) to the console stderr - r.Logger.Write(output) - io.Copy(r.Logger, stderrTxt) - wg.Done() - }() - - wg.Wait() - - r.CleanUp() - } - -} - -// parseOutput decodes the proxy response from the output of the function and returns -// the rest -func parseOutput(w http.ResponseWriter, stdoutTxt io.Reader, runtime string, wg *sync.WaitGroup, acceptHeader string) (output []byte) { - defer wg.Done() - - result, err := ioutil.ReadAll(stdoutTxt) - if err != nil { - msg := fmt.Sprintf("Error invoking %s runtime: %s", runtime, err) - log.Println(msg) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{ "message": "Internal server error" }`)) - return - } - - // At this point, we need to see whether the response is in the format - // of a Lambda proxy response (inc statusCode / body), and if so, handle it - // otherwise just copy the whole output back to the http.ResponseWriter - proxy := &struct { - StatusCode json.Number `json:"statusCode"` - Headers map[string]string `json:"headers"` - Body json.Number `json:"body"` - IsBase64Encoded bool `json:"isBase64Encoded"` - }{} - - // We only want the last line of stdout, because it's possible that - // the function may have written directly to stdout using - // System.out.println or similar, before docker-lambda output the result - lastNewlineIx := bytes.LastIndexByte(bytes.TrimRight(result, "\n"), '\n') - if lastNewlineIx > 0 { - output = result[:lastNewlineIx] - result = result[lastNewlineIx:] - } - - if err := json.Unmarshal(result, proxy); err != nil || (proxy.StatusCode == "" && len(proxy.Headers) == 0 && proxy.Body == "") { - // This is not a proxy integration function, as the response doesn't container headers, statusCode or body. - // Return HTTP 502 (Bad Gateway) to match API Gateway behaviour: http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format - log.Printf(color.RedString("Function returned an invalid response (must include one of: body, headers or statusCode in the response object): %s\n"), err) - w.WriteHeader(http.StatusBadGateway) - w.Write([]byte(`{ "message": "Internal server error" }`)) - return - } - - // Set any HTTP headers requested by the proxy function - if len(proxy.Headers) > 0 { - for key, value := range proxy.Headers { - w.Header().Add(key, value) - } - } - - // This is a proxy function, so set the http status code and return the body - if statusCode, err := proxy.StatusCode.Int64(); err != nil { - w.WriteHeader(http.StatusBadGateway) - } else { - w.WriteHeader(int(statusCode)) - } - - acceptMediaTypeMatched := false - if acceptHeader != "" { - //API Gateway only honors the first Accept media type. - acceptMediaType := strings.Split(acceptHeader, ",")[0] - contentType := proxy.Headers["Content-Type"] - contentMediaType, _, err := mime.ParseMediaType(contentType) - acceptMediaTypeMatched = err == nil && acceptMediaType == contentMediaType - } - - if proxy.IsBase64Encoded && acceptMediaTypeMatched { - if decodedBytes, err := base64.StdEncoding.DecodeString(string(proxy.Body)); err != nil { - log.Printf(color.RedString("Function returned an invalid base64 body: %s\n"), err) - w.WriteHeader(http.StatusInternalServerError) - w.Write([]byte(`{ "message": "Internal server error" }`)) - } else { - w.Write(decodedBytes) - } - } else { - w.Write([]byte(proxy.Body)) - } - - return -} - -// demuxDockerStream takes a Docker attach stream, and parses out stdout/stderr -// into separate streams, based on the Docker engine documentation here: -// https://docs.docker.com/engine/api/v1.28/#operation/ContainerAttach -// Due to the use of io.Pipe, you should take care to read from the streams -// in a separate Go routine to avoid deadlocks. -func demuxDockerStream(input io.Reader) (io.ReadCloser, io.ReadCloser, error) { - - stdoutreader, stdoutwriter := io.Pipe() - stderrreader, stderrwriter := io.Pipe() - - // Return early and continue to copy i/o in another go routine - go func() { - - _, err := stdcopy.StdCopy(stdoutwriter, stderrwriter, input) - if err != nil { - log.Printf("Error reading I/O from runtime container: %s\n", err) - } - - stdoutwriter.Write([]byte("\n")) - - stdoutwriter.Close() - stderrwriter.Close() - - }() - - return stdoutreader, stderrreader, nil - -} - -func getDockerVersion() (string, error) { - - cli, err := client.NewEnvClient() - if err != nil { - return "", err - } - - response, err := cli.Ping(context.Background()) - return response.APIVersion, err - -} - -func getWorkingDir(dir string) string { - - // If the template filepath isn't set, just use the cwd - if dir == "" || dir == "." { - cwd, err := os.Getwd() - if err != nil { - // A directory wasn't specified on the command line - // and we can't determin the current working directory. - log.Printf("Could not find working directory for template: %s\n", err) - return "" - } - dir = cwd - } - - // Docker volumes require an absolute path. - // If the path exists, use the absolute version. - if _, err := os.Stat(dir); err == nil { - absolute, err := filepath.Abs(dir) - if err == nil { - dir = absolute - } - } - - // Windows uses \ as the path delimiter, but Docker requires / as the path delimiter. - // Hence the use of filepath.ToSlash for return values. - return filepath.ToSlash(dir) - -} - -// decompressArchive unzips a ZIP archive to a temporary directory and returns -// the temporary directory name, or an error -func decompressArchive(src string) (string, error) { - - // Create a temporary directory just for this decompression (dirname: OS tmp directory + unix timestamp)) - tmpdir := os.TempDir() - - // By default on macOS, os.TempDir() returns a directory in /var/folders/. - // This sits outside the default Docker Shared Files directories, however - // /var/folders is just a symlink to /private/var/folders/, so use that instead - if strings.HasPrefix(tmpdir, "/var/folders") { - tmpdir = "/private" + tmpdir - } - - dest := filepath.Join(tmpdir, "aws-sam-local-"+strconv.FormatInt(time.Now().UnixNano(), 10)) - - var filenames []string - - r, err := zip.OpenReader(src) - if err != nil { - return dest, err - } - defer r.Close() - - for _, f := range r.File { - - err := func() error { - rc, err := f.Open() - if err != nil { - return err - } - defer rc.Close() - - // Store filename/path for returning and using later on - fpath := filepath.Join(dest, f.Name) - filenames = append(filenames, fpath) - - if f.FileInfo().IsDir() { - - // Make Folder - os.MkdirAll(fpath, os.ModePerm) - - } else { - - // Make File - var fdir string - if lastIndex := strings.LastIndex(fpath, string(os.PathSeparator)); lastIndex > -1 { - fdir = fpath[:lastIndex] - } - - err = os.MkdirAll(fdir, os.ModePerm) - if err != nil { - return err - } - f, err := os.OpenFile( - fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode()) - if err != nil { - return err - } - defer f.Close() - - _, err = io.Copy(f, rc) - if err != nil { - return err - } - } - - return nil - }() - - if err != nil { - log.Fatal(err) - return dest, err - } - } - - return dest, nil - -} - -func convertWindowsPath(input string) string { - - rg := regexp.MustCompile(`^([A-Za-z]+):`) - drive := rg.FindAllStringSubmatch(input, 1) - if drive != nil { - - // The path starts with a drive letter. - // Docker toolbox mounts C:\ as /c/ so we need to extract, convert to lowercase - // and replace into the correct format - letter := drive[0][1] - - input = rg.ReplaceAllString(input, "/"+strings.ToLower(letter)) - - } - - // Convert all OS seperators to '/' - input = filepath.ToSlash(input) - return input - -} diff --git a/runtime_test.go b/runtime_test.go deleted file mode 100644 index 29f378b1af..0000000000 --- a/runtime_test.go +++ /dev/null @@ -1,204 +0,0 @@ -package main - -import ( - "encoding/base64" - "fmt" - "io" - "net/http" - "os" - "strings" - "sync" - - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" -) - -var _ = Describe("sam", func() { - - Describe("runtime", func() { - - Context("mount directory", func() { - Context("with a windows style path", func() { - input := `C:/Users/username/path` - It("should replace it with the docker-toolbox format", func() { - result := convertWindowsPath(input) - Expect(result).To(Equal("/c/Users/username/path")) - }) - }) - }) - - Context("working directory", func() { - - cwd, err := os.Getwd() - It("should determin the current working directory", func() { - Expect(cwd).ToNot(BeNil()) - Expect(err).To(BeNil()) - }) - - inputs := [][]string{ - // input path, output path - []string{"", cwd}, - []string{".", cwd}, - []string{"/test/directory", "/test/directory"}, - []string{"test/non-existant-directory", "test/non-existant-directory"}, - []string{"test", cwd + "/test"}, - } - - // func getWorkingDir(basedir string, codeuri string, checkWorkingDirExist bool) (string, error) { - for _, input := range inputs { - - in := input[0] - expected := input[1] - - context := fmt.Sprintf("with input %s", in) - Context(context, func() { - It("should have the correct directory", func() { - dir := getWorkingDir(in) - Expect(dir).To(Equal(expected)) - }) - }) - - } - - }) - - Context("parse output", func() { - var wg sync.WaitGroup - var out []byte - var r *fakeResponse - - inputs := []struct { - name string - output io.Reader - body []byte - status int - headers http.Header - trailing string - acceptHeader string - }{ - { - name: "only proxy response", - output: strings.NewReader(`{"statusCode":202,"headers":{"foo":"bar"},"body":"{\"nextToken\":null,\"beers\":[]}","isBase64Encoded":false}`), - body: []byte(`{"nextToken":null,"beers":[]}`), - status: 202, - headers: http.Header(map[string][]string{"foo": []string{"bar"}}), - }, - { - name: "proxy response with extra output", - output: strings.NewReader(`Foo - Bar - {"statusCode":200,"headers":null,"body":"{\"nextToken\":null,\"beers\":[]}","isBase64Encoded":false}`), - body: []byte(`{"nextToken":null,"beers":[]}`), - status: 200, - headers: make(http.Header), - trailing: `Foo - Bar`, - }, - { - name: "no output", - output: strings.NewReader(``), - body: []byte(`{ "message": "Internal server error" }`), - status: 502, - headers: make(http.Header), - }, - { - name: "bad status code", - output: strings.NewReader(`{"statusCode":"xxx","headers":null,"body":"{\"nextToken\":null,\"beers\":[]}","isBase64Encoded":false}`), - body: []byte(`{"nextToken":null,"beers":[]}`), - status: 502, - headers: make(http.Header), - }, - { - name: "io error", - output: &errReader{}, - body: []byte(`{ "message": "Internal server error" }`), - status: 500, - headers: make(http.Header), - }, - { - name: "base64 encoded response and Accept and Content-Type media types are matched", - output: strings.NewReader(fmt.Sprintf(`{"statusCode":200,"headers":{"Content-Type": "multipart/form-data; boundary=something"},"body": "%v","isBase64Encoded":true}`, base64.StdEncoding.EncodeToString([]byte("abc")))), - body: []byte("abc"), - status: 200, - headers: http.Header(map[string][]string{"Content-Type": []string{"multipart/form-data; boundary=something"}}), - acceptHeader: "multipart/form-data, application/foo", - }, - { - name: "invalid base64 encoded response and Accept and Content-Type media types are matched", - output: strings.NewReader(fmt.Sprintf(`{"statusCode":200,"headers":{"Content-Type":"multipart/form-data; boundary=something"},"body": "a","isBase64Encoded":true}`)), - body: []byte(`{ "message": "Internal server error" }`), - status: 500, - headers: http.Header(map[string][]string{"Content-Type": []string{"multipart/form-data; boundary=something"}}), - acceptHeader: "multipart/form-data, application/foo", - }, - { - name: "base64 encoded response but Accept and Content-Type media types are not matched", - output: strings.NewReader(fmt.Sprintf(`{"statusCode":200,"headers":{"Content-Type": "multipart/form-data; boundary=something"},"body": "%v","isBase64Encoded":true}`, base64.StdEncoding.EncodeToString([]byte("abc")))), - body: []byte(base64.StdEncoding.EncodeToString([]byte("abc"))), - status: 200, - headers: http.Header(map[string][]string{"Content-Type": []string{"multipart/form-data; boundary=something"}}), - acceptHeader: "application/foo", - }, - { - name: "base64 encoded response and empty Accept and Content-Type headers", - output: strings.NewReader(fmt.Sprintf(`{"statusCode":200,"headers":{"Content-Type": ""},"body": "%v","isBase64Encoded":true}`, base64.StdEncoding.EncodeToString([]byte("abc")))), - body: []byte(base64.StdEncoding.EncodeToString([]byte("abc"))), - status: 200, - headers: http.Header(map[string][]string{"Content-Type": []string{""}}), - acceptHeader: "", - }, - } - - for _, input := range inputs { - - Context(input.name, func() { - wg.Add(1) - r = newResponse() - out = parseOutput(r, input.output, "foo", &wg, input.acceptHeader) - - It("should have the expected output", func() { - Expect(r.status).To(Equal(input.status)) - Expect(r.body).To(Equal(input.body)) - Expect(r.headers).To(Equal(input.headers)) - Expect(string(out)).To(Equal(input.trailing)) - }) - - }) - - } - - }) - - }) -}) - -type errReader struct{} - -func (r *errReader) Read(p []byte) (int, error) { - return 0, io.ErrUnexpectedEOF -} - -type fakeResponse struct { - headers http.Header - body []byte - status int -} - -func newResponse() *fakeResponse { - return &fakeResponse{ - headers: make(http.Header), - } -} - -func (r *fakeResponse) Header() http.Header { - return r.headers -} - -func (r *fakeResponse) Write(body []byte) (int, error) { - r.body = body - return len(body), nil -} - -func (r *fakeResponse) WriteHeader(status int) { - r.status = status -} diff --git a/sam-banner.png b/sam-banner.png deleted file mode 100644 index 8e9255ce01..0000000000 Binary files a/sam-banner.png and /dev/null differ diff --git a/samcli/__init__.py b/samcli/__init__.py new file mode 100644 index 0000000000..51197b937b --- /dev/null +++ b/samcli/__init__.py @@ -0,0 +1,5 @@ +""" +SAM CLI version +""" + +__version__ = '0.3.0' diff --git a/samcli/cli/__init__.py b/samcli/cli/__init__.py new file mode 100644 index 0000000000..060dc25d17 --- /dev/null +++ b/samcli/cli/__init__.py @@ -0,0 +1,3 @@ +""" +CLI Framework +""" diff --git a/samcli/cli/command.py b/samcli/cli/command.py new file mode 100644 index 0000000000..b627872948 --- /dev/null +++ b/samcli/cli/command.py @@ -0,0 +1,109 @@ +""" +Base classes that implement the CLI framework +""" + +import logging +import importlib +import click + +logger = logging.getLogger(__name__) + +# Commands that are bundled with the CLI by default +_SAM_CLI_COMMAND_PACKAGES = { + "samcli.commands.local.local", + "samcli.commands.validate.validate", + "samcli.commands.init", + "samcli.commands.deploy", + "samcli.commands.package", +} + + +class BaseCommand(click.MultiCommand): + """ + Dynamically loads commands. It takes a list of names of Python packages representing the commands, loads + these packages, and initializes them as Click commands. If a command "hello" is available in a Python package + "foo.bar.hello", then this package name is passed to this class to load the command. This allows commands + to be written as standalone packages that are dynamically initialized by the CLI. + + Each command, along with any subcommands, is implemented using Click annotations. When the command is loaded + dynamically, this class expects the Click object to be exposed through an attribute called ``cli``. If the + attribute is not present, or is not a Click object, then an exception will be raised. + + For example: if "foo.bar.hello" is the package where "hello" command is implemented, then + "/foo/bar/hello/__init__.py" file is expected to contain a Click object called ``cli``. + + The command package is dynamically loaded using Python's standard ``importlib`` library. Therefore package names + can be specified using the standard Python's dot notation such as "foo.bar.hello". + + By convention, the name of last module in the package's name is the command's name. ie. A package of "foo.bar.baz" + will produce a command name "baz". + """ + + def __init__(self, cmd_packages=None, *args, **kwargs): + """ + Initializes the class, optionally with a list of available commands + + :param cmd_packages: List of Python packages names of CLI commands + :param args: Other Arguments passed to super class + :param kwargs: Other Arguments passed to super class + """ + super(BaseCommand, self).__init__(*args, **kwargs) + + if not cmd_packages: + cmd_packages = _SAM_CLI_COMMAND_PACKAGES + + self._commands = {} + self._commands = BaseCommand._set_commands(cmd_packages) + + @staticmethod + def _set_commands(package_names): + """ + Extract the command name from package name. Last part of the module path is the command + ie. if path is foo.bar.baz, then "baz" is the command name. + + :param package_names: List of package names + :return: Dictionary with command name as key and the package name as value. + """ + + commands = {} + + for pkg_name in package_names: + cmd_name = pkg_name.split('.')[-1] + commands[cmd_name] = pkg_name + + return commands + + def list_commands(self, ctx): + """ + Overrides a method from Click that returns a list of commands available in the CLI. + + :param ctx: Click context + :return: List of commands available in the CLI + """ + return list(self._commands.keys()) + + def get_command(self, ctx, cmd_name): + """ + Overrides method from ``click.MultiCommand`` that returns Click CLI object for given command name, if found. + + :param ctx: Click context + :param cmd_name: Top-level command name + :return: Click object representing the command + """ + if cmd_name not in self._commands: + logger.error("Command %s not available", cmd_name) + return + + pkg_name = self._commands[cmd_name] + + try: + mod = importlib.import_module(pkg_name) + except ImportError: + logger.exception("Command '%s' is not configured correctly. Unable to import '%s'", cmd_name, pkg_name) + return + + if not hasattr(mod, "cli"): + logger.error("Command %s is not configured correctly. It must expose an function called 'cli'", cmd_name) + return + + return mod.cli diff --git a/samcli/cli/context.py b/samcli/cli/context.py new file mode 100644 index 0000000000..7861e9329d --- /dev/null +++ b/samcli/cli/context.py @@ -0,0 +1,42 @@ +""" +Context information passed to each CLI command +""" + +import logging + + +class Context(object): + """ + Top level context object for the CLI. Exposes common functionality required by a CLI, including logging, + environment config parsing, debug logging etc. + + This object is passed by Click to every command that adds the proper annotation. + Read this for more details on Click Context - http://click.pocoo.org/5/commands/#nested-handling-and-contexts + Each command gets its own context object, but linked to both parent and child command's context, like a Linked List. + + This class itself does not rely on how Click works. It is just a plain old Python class that holds common + properties used by every CLI command. + """ + + def __init__(self): + """ + Initialize the context with default values + """ + self._debug = False + + @property + def debug(self): + return self._debug + + @debug.setter + def debug(self, value): + """ + Turn on debug logging if necessary. + + :param value: Value of debug flag + """ + self._debug = value + + if self._debug: + # Turn on debug logging + logging.getLogger().setLevel(logging.DEBUG) diff --git a/samcli/cli/main.py b/samcli/cli/main.py new file mode 100644 index 0000000000..9693562586 --- /dev/null +++ b/samcli/cli/main.py @@ -0,0 +1,43 @@ +""" +Entry point for the CLI +""" + +import logging +import click + +from samcli import __version__ +from .options import debug_option +from .context import Context +from .command import BaseCommand + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') + + +pass_context = click.make_pass_decorator(Context) + + +def common_options(f): + """ + Common CLI options used by all commands. Ex: --debug + :param f: Callback function passed by Click + :return: Callback function + """ + f = debug_option(f) + return f + + +@click.command(cls=BaseCommand) +@common_options +@click.version_option(version=__version__, prog_name="SAM CLI") +@pass_context +def cli(ctx): + """ + AWS Serverless Application Model (SAM) CLI + + The AWS Serverless Application Model extends AWS CloudFormation to provide a simplified way of defining the + Amazon API Gateway APIs, AWS Lambda functions, and Amazon DynamoDB tables needed by your serverless application. + You can find more in-depth guide about the SAM specification here: + https://github.com/awslabs/serverless-application-model. + """ + pass diff --git a/samcli/cli/options.py b/samcli/cli/options.py new file mode 100644 index 0000000000..04052313a3 --- /dev/null +++ b/samcli/cli/options.py @@ -0,0 +1,27 @@ +""" +This file contains common CLI options common to all commands. As we add more commands, this will +become a repository of options that other commands could use when needed. +""" + +import click + +from .context import Context + + +def debug_option(f): + """ + Configures --debug option for CLI + + :param f: Callback Function to be passed to Click + """ + def callback(ctx, param, value): + state = ctx.ensure_object(Context) + state.debug = value + return value + + return click.option('--debug', + expose_value=False, + is_flag=True, + envvar="SAM_DEBUG", + help='Turn on debug logging', + callback=callback)(f) diff --git a/samcli/commands/__init__.py b/samcli/commands/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/deploy/__init__.py b/samcli/commands/deploy/__init__.py new file mode 100644 index 0000000000..9ab2e30550 --- /dev/null +++ b/samcli/commands/deploy/__init__.py @@ -0,0 +1,26 @@ +""" +CLI command for "deploy" command +""" + +import click + +from samcli.cli.main import pass_context, common_options +from samcli.lib.samlib.cloudformation_command import execute_command + + +SHORT_HELP = "Deploy an AWS SAM application. This is an alias for 'aws cloudformation deploy'." + + +@click.command("deploy", short_help=SHORT_HELP, context_settings={"ignore_unknown_options": True}) +@click.argument("args", nargs=-1, type=click.UNPROCESSED) +@common_options +@pass_context +def cli(ctx, args): + + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(args) # pragma: no cover + + +def do_cli(args): + execute_command("deploy", args) diff --git a/samcli/commands/init/__init__.py b/samcli/commands/init/__init__.py new file mode 100644 index 0000000000..14d8273dae --- /dev/null +++ b/samcli/commands/init/__init__.py @@ -0,0 +1,91 @@ +# -*- coding: utf-8 -*- +""" +Init command to scaffold a project app from a template +""" +import logging +import click + +from samcli.cli.main import pass_context, common_options +from samcli.local.init import generate_project +from samcli.local.init import RUNTIME_TEMPLATE_MAPPING +from samcli.local.init.exceptions import GenerateProjectFailedError +from samcli.commands.local.cli_common.user_exceptions import UserException + +LOG = logging.getLogger(__name__) +SUPPORTED_RUNTIME = [r for r in RUNTIME_TEMPLATE_MAPPING] + + +@click.command(context_settings=dict(help_option_names=[u'-h', u'--help'])) +@click.option('-l', '--location', help="Template location (git, mercurial, http(s), zip, path)") +@click.option('-r', '--runtime', type=click.Choice(SUPPORTED_RUNTIME), default="nodejs8.10", + help="Lambda Runtime of your app") +@click.option('-o', '--output-dir', default='.', type=click.Path(), help="Where to output the initialized app into") +@click.option('-n', '--name', default="sam-app", help="Name of your project to be generated as a folder") +@click.option('--no-input', is_flag=True, default=False, + help="Disable prompting and accept default values defined template config") +@common_options +@pass_context +def cli(ctx, location, runtime, output_dir, name, no_input): + """ \b + Initialize a serverless application with a SAM template, folder + structure for your Lambda functions, connected to an event source such as APIs, + S3 Buckets or DynamoDB Tables. This application includes everything you need to + get started with serverless and eventually grow into a production scale application. + \b + This command can initialize a boilerplate serverless app. If you want to create your own + template as well as use a custom location please take a look at our official documentation. + + \b + Common usage: + + \b + Initializes a new SAM project using Python 3.6 default template runtime + \b + $ sam init --runtime python3.6 + \b + Initializes a new SAM project using custom template in a Git/Mercurial repository + \b + # gh being expanded to github url + $ sam init --location gh:aws-samples/cookiecutter-sam-python + \b + $ sam init --location git+ssh://git@github.com/aws-samples/cookiecutter-sam-python.git + \b + $ sam init --location hg+ssh://hg@bitbucket.org/repo/template-name + \b + $ sam init --location hg+ssh://hg@bitbucket.org/repo/template-name + + \b + Initializes a new SAM project using custom template in a Zipfile + \b + $ sam init --location /path/to/template.zip + \b + $ sam init --location https://example.com/path/to/template.zip + + \b + Initializes a new SAM project using custom template in a local path + \b + $ sam init --location /path/to/template/folder + + """ + # All logic must be implemented in the `do_cli` method. This helps ease unit tests + do_cli(ctx, location, runtime, output_dir, + name, no_input) # pragma: no cover + + +def do_cli(ctx, location, runtime, output_dir, name, no_input): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + LOG.debug("Init command") + click.secho("[+] Initializing project structure...", fg="green") + + try: + generate_project(location, runtime, output_dir, name, no_input) + # Custom templates can implement their own visual cues so let's not repeat the message + if not location: + click.secho( + "[SUCCESS] - Read {name}/README.md for further instructions on how to proceed" + .format(name=name), bold=True) + click.secho("[*] Project initialization is now complete", fg="green") + except GenerateProjectFailedError as e: + raise UserException(str(e)) diff --git a/samcli/commands/local/__init__.py b/samcli/commands/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/cli_common/__init__.py b/samcli/commands/local/cli_common/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/cli_common/invoke_context.py b/samcli/commands/local/cli_common/invoke_context.py new file mode 100644 index 0000000000..103f175da2 --- /dev/null +++ b/samcli/commands/local/cli_common/invoke_context.py @@ -0,0 +1,274 @@ +""" +Reads CLI arguments and performs necessary preparation to be able to run the function +""" + +import os +import sys +import json +import yaml +import docker + +from requests.exceptions import ConnectionError + +from samcli.yamlhelper import yaml_parse +from samcli.commands.local.lib.local_lambda import LocalLambdaRunner +from samcli.local.lambdafn.runtime import LambdaRuntime +from samcli.local.docker.manager import ContainerManager +from .user_exceptions import InvokeContextException +from ..lib.sam_function_provider import SamFunctionProvider + + +class InvokeContext(object): + """ + Sets up a context to invoke Lambda functions locally by parsing all command line arguments necessary for the + invoke. + + ``start-api`` command will also use this class to read and parse invoke related CLI arguments and setup the + necessary context to invoke. + + This class *must* be used inside a `with` statement as follows: + + with InvokeContext(**kwargs) as context: + context.local_lambda_runner.invoke(...) + + This class sets up some resources that need to be cleaned up after the context object is used. + """ + + def __init__(self, + template_file, + function_identifier=None, + env_vars_file=None, + debug_port=None, + debug_args=None, + docker_volume_basedir=None, + docker_network=None, + log_file=None, + skip_pull_image=None, + aws_profile=None): + """ + Initialize the context + + :param string template_file: Name or path to template + :param string function_identifier: Identifier of the function to invoke + :param string env_vars_file: Path to a file containing values for environment variables + :param int debug_port: Port to bind the debugger + :param string docker_volume_basedir: Directory for the Docker volume + :param string docker_network: Docker network identifier + :param string log_file: Path to a file to send container output to. If the file does not exist, it will be + created + :param bool skip_pull_image: Should we skip pulling the Docker container image? + :param string aws_profile: Name of the profile to fetch AWS credentials from + """ + + self._template_file = template_file + self._function_identifier = function_identifier + self._env_vars_file = env_vars_file + self._debug_port = debug_port + self._debug_args = debug_args + self._docker_volume_basedir = docker_volume_basedir + self._docker_network = docker_network + self._log_file = log_file + self._skip_pull_image = skip_pull_image + self._aws_profile = aws_profile + + self._template_dict = None + self._function_provider = None + self._env_vars_value = None + self._log_file_handle = None + + def __enter__(self): + """ + Performs some basic checks and returns itself when everything is ready to invoke a Lambda function. + + :returns InvokeContext: Returns this object + """ + + # Grab template from file and create a provider + self._template_dict = self._get_template_data(self._template_file) + self._function_provider = SamFunctionProvider(self._template_dict) + + self._env_vars_value = self._get_env_vars_value(self._env_vars_file) + self._log_file_handle = self._setup_log_file(self._log_file) + + self._check_docker_connectivity() + + return self + + def __exit__(self, *args): + """ + Cleanup any necessary opened files + """ + + if self._log_file_handle: + self._log_file_handle.close() + self._log_file_handle = None + + @property + def function_name(self): + """ + Returns name of the function to invoke. If no function identifier is provided, this method will return name of + the only function from the template + + :return string: Name of the function + :raises InvokeContextException: If function identifier is not provided + """ + if self._function_identifier: + return self._function_identifier + + # Function Identifier is *not* provided. If there is only one function in the template, + # default to it. + + all_functions = [f for f in self._function_provider.get_all()] + if len(all_functions) == 1: + return all_functions[0].name + + # Get all the available function names to print helpful exception message + all_function_names = [f.name for f in all_functions] + + # There are more functions in the template, and function identifier is not provided, hence raise. + raise InvokeContextException("You must provide a function identifier (function's Logical ID in the template). " + "Possible options in your template: {}".format(all_function_names)) + + @property + def local_lambda_runner(self): + """ + Returns an instance of the runner capable of running Lambda functions locally + + :return samcli.commands.local.lib.local_lambda.LocalLambdaRunner: Runner configured to run Lambda functions + locally + """ + + container_manager = ContainerManager(docker_network_id=self._docker_network, + skip_pull_image=self._skip_pull_image) + + lambda_runtime = LambdaRuntime(container_manager) + return LocalLambdaRunner(local_runtime=lambda_runtime, + function_provider=self._function_provider, + cwd=self.get_cwd(), + env_vars_values=self._env_vars_value, + debug_port=self._debug_port, + debug_args=self._debug_args, + aws_profile=self._aws_profile) + + @property + def stdout(self): + """ + Returns a stdout stream to output Lambda function logs to + + :return File like object: Stream where the output of the function is sent to + """ + if self._log_file_handle: + return self._log_file_handle + + return sys.stdout + + @property + def stderr(self): + """ + Returns stderr stream to output Lambda function errors to + + :return File like object: Stream where the stderr of the function is sent to + """ + if self._log_file_handle: + return self._log_file_handle + + return sys.stderr + + @property + def template(self): + """ + Returns the template data as dictionary + + :return dict: Template data + """ + return self._template_dict + + def get_cwd(self): + """ + Get the working directory. This is usually relative to the directory that contains the template. If a Docker + volume location is specified, it takes preference + + All Lambda function code paths are resolved relative to this working directory + + :return string: Working directory + """ + + cwd = os.path.dirname(os.path.abspath(self._template_file)) + if self._docker_volume_basedir: + cwd = self._docker_volume_basedir + + return cwd + + @staticmethod + def _get_template_data(template_file): + """ + Read the template file, parse it as JSON/YAML and return the template as a dictionary. + + :param string template_file: Path to the template to read + :return dict: Template data as a dictionary + :raises InvokeContextException: If template file was not found or the data was not a JSON/YAML + """ + + if not os.path.exists(template_file): + raise InvokeContextException("Template file not found at {}".format(template_file)) + + with open(template_file, 'r') as fp: + try: + return yaml_parse(fp.read()) + except (ValueError, yaml.YAMLError) as ex: + raise InvokeContextException("Failed to parse template: {}".format(str(ex))) + + @staticmethod + def _get_env_vars_value(filename): + """ + If the user provided a file containing values of environment variables, this method will read the file and + return its value + + :param string filename: Path to file containing environment variable values + :return dict: Value of environment variables, if provided. None otherwise + :raises InvokeContextException: If the file was not found or not a valid JSON + """ + if not filename: + return None + + # Try to read the file and parse it as JSON + try: + + with open(filename, 'r') as fp: + return json.load(fp) + + except Exception as ex: + raise InvokeContextException("Could not read environment variables overrides from file {}: {}".format( + filename, + str(ex))) + + @staticmethod + def _setup_log_file(log_file): + """ + Open a log file if necessary and return the file handle. This will create a file if it does not exist + + :param string log_file: Path to a file where the logs should be written to + :return: Handle to the opened log file, if necessary. None otherwise + """ + if not log_file: + return None + + return open(log_file, 'w') + + @staticmethod + def _check_docker_connectivity(docker_client=None): + """ + Checks if Docker daemon is running. This is required for us to invoke the function locally + + :param docker_client: Instance of Docker client + :return bool: True, if Docker is available + :raises InvokeContextException: If Docker is not available + """ + + docker_client = docker_client or docker.from_env() + + try: + docker_client.ping() + # When Docker is not installed, a request.exceptions.ConnectionError is thrown. + except (docker.errors.APIError, ConnectionError): + raise InvokeContextException("Running AWS SAM projects locally requires Docker. Have you got it installed?") diff --git a/samcli/commands/local/cli_common/options.py b/samcli/commands/local/cli_common/options.py new file mode 100644 index 0000000000..d75f28ed48 --- /dev/null +++ b/samcli/commands/local/cli_common/options.py @@ -0,0 +1,110 @@ +""" +Common CLI options for invoke command +""" + +import os +import click + +_TEMPLATE_OPTION_DEFAULT_VALUE = "template.[yaml|yml]" + + +def get_or_default_template_file_name(ctx, param, provided_value): + """ + Default value for the template file name option is more complex than what Click can handle. + This method either returns user provided file name or one of the two default options (template.yaml/template.yml) + depending on the file that exists + + :param ctx: Click Context + :param param: Param name + :param provided_value: Value provided by Click. It could either be the default value or provided by user. + :return: Actual value to be used in the CLI + """ + + if provided_value == _TEMPLATE_OPTION_DEFAULT_VALUE: + # Default value was used. Value can either be template.yaml or template.yml. Decide based on which file exists + # .yml is the default, even if it does not exist. + provided_value = "template.yml" + + option = "template.yaml" + if os.path.exists(option): + provided_value = option + + return os.path.abspath(provided_value) + + +def template_common_option(f): + """ + Common ClI option for template + + :param f: Callback passed by Click + :return: Callback + """ + return template_click_option()(f) + + +def template_click_option(): + """ + Click Option for template option + """ + return click.option('--template', '-t', + default=_TEMPLATE_OPTION_DEFAULT_VALUE, + type=click.Path(), + envvar="SAM_TEMPLATE_FILE", + callback=get_or_default_template_file_name, + show_default=True, + help="AWS SAM template file") + + +def invoke_common_options(f): + """ + Common CLI options shared by "local invoke" and "local start-api" commands + + :param f: Callback passed by Click + """ + + invoke_options = [ + template_click_option(), + + click.option('--env-vars', '-n', + type=click.Path(exists=True), + help="JSON file containing values for Lambda function's environment variables."), + + click.option('--debug-port', '-d', + help="When specified, Lambda function container will start in debug mode and will expose this " + "port on localhost.", + envvar="SAM_DEBUG_PORT"), + + click.option('--debug-args', + help="Additional arguments to be passed to the debugger", + envvar="DEBUGGER_ARGS"), + + click.option('--docker-volume-basedir', '-v', + envvar="SAM_DOCKER_VOLUME_BASEDIR", + help="Specifies the location basedir where the SAM file exists. If the Docker is running on " + "a remote machine, you must mount the path where the SAM file exists on the docker machine " + "and modify this value to match the remote machine."), + + click.option('--docker-network', + envvar="SAM_DOCKER_NETWORK", + help="Specifies the name or id of an existing docker network to lambda docker" + "containers should connect to, along with the default bridge network. If not specified," + "the Lambda containers will only connect to the default bridge docker network."), + + click.option('--log-file', '-l', + help="logfile to send runtime logs to"), + + click.option('--skip-pull-image', + is_flag=True, + help="Specify whether CLI should skip pulling down the latest Docker image for Lambda runtime", + envvar="SAM_SKIP_PULL_IMAGE"), + + click.option('--profile', + help="Specify which AWS credentials profile to use."), + + ] + + # Reverse the list to maintain ordering of options in help text printed with --help + for option in reversed(invoke_options): + option(f) + + return f diff --git a/samcli/commands/local/cli_common/user_exceptions.py b/samcli/commands/local/cli_common/user_exceptions.py new file mode 100644 index 0000000000..846781852a --- /dev/null +++ b/samcli/commands/local/cli_common/user_exceptions.py @@ -0,0 +1,35 @@ +""" +Class containing error conditions that are exposed to the user. +""" + +import click + + +class UserException(click.ClickException): + """ + Base class for all exceptions that need to be surfaced to the user. Typically, we will display the exception + message to user and return the error code from CLI process + """ + + exit_code = 1 + + +class InvokeContextException(UserException): + """ + Something went wrong invoking the function. + """ + pass + + +class InvalidSamTemplateException(UserException): + """ + The template provided was invalid and not able to transform into a Standard CloudFormation Template + """ + pass + + +class SamTemplateNotFoundException(UserException): + """ + The SAM Template provided could not be found + """ + pass diff --git a/samcli/commands/local/generate_event/__init__.py b/samcli/commands/local/generate_event/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/api/__init__.py b/samcli/commands/local/generate_event/api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/api/cli.py b/samcli/commands/local/generate_event/api/cli.py new file mode 100644 index 0000000000..29d64ca7d8 --- /dev/null +++ b/samcli/commands/local/generate_event/api/cli.py @@ -0,0 +1,43 @@ +""" +Generates an Api Gateway Event for a Lambda Invoke +""" +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_api_event + + +@click.command("api", short_help="Generates a sample Amazon API Gateway event") +@click.option("--method", "-m", + type=str, + default="POST", + help='HTTP method (default: "POST")') +@click.option("--body", "-b", + type=str, + default="{ \"test\": \"body\"}", + help='HTTP body (default: "{ \"test\": \"body\"}")') +@click.option("--resource", "-r", + type=str, + default="/{proxy+}", + help='API Gateway resource name (default: "/{proxy+}")') +@click.option("--path", "-p", + type=str, + default="/examplepath", + help=' HTTP path (default: "/examplepath")') +@cli_framework_options +@pass_context +def cli(ctx, method, body, resource, path): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, method, body, resource, path) # pragma: no cover + + +def do_cli(ctx, method, body, resource, path): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + event_dict = generate_api_event(method, body, resource, path) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/generate_event/cli.py b/samcli/commands/local/generate_event/cli.py new file mode 100644 index 0000000000..f99691c6fc --- /dev/null +++ b/samcli/commands/local/generate_event/cli.py @@ -0,0 +1,39 @@ +""" +Command group for "generate-event" suite for commands. +""" + +import click + +from .s3.cli import cli as s3_cli +from .api.cli import cli as api_cli +from .dynamodb.cli import cli as dynamodb_cli +from .kinesis.cli import cli as kinesis_cli +from .schedule.cli import cli as schedule_cli +from .sns.cli import cli as sns_cli + + +HELP_TEXT = """ +Generate a Lambda Event that can be used to invoke a Lambda Function. + +Useful for developing serverless functions that handle asynchronous events (such as S3/Kinesis etc), or if you want to +compose a script of test cases. Event body can be passed in either by stdin (default), or by using the --event +parameter. Runtime output (logs etc) will be outputted to stderr, and the Lambda function result will be outputted to +stdout. +""" + + +@click.group("generate-event") +def cli(): + """ + Generate an event + """ + pass # pragma: no cover + + +# Add individual commands under this group +cli.add_command(s3_cli) +cli.add_command(api_cli) +cli.add_command(dynamodb_cli) +cli.add_command(kinesis_cli) +cli.add_command(schedule_cli) +cli.add_command(sns_cli) diff --git a/samcli/commands/local/generate_event/dynamodb/__init__.py b/samcli/commands/local/generate_event/dynamodb/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/dynamodb/cli.py b/samcli/commands/local/generate_event/dynamodb/cli.py new file mode 100644 index 0000000000..6071b5f7e4 --- /dev/null +++ b/samcli/commands/local/generate_event/dynamodb/cli.py @@ -0,0 +1,31 @@ +""" +Generates a DynamoDB Event for a Lambda Invoke +""" +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_dynamodb_event + + +@click.command("dynamodb", short_help="Generates a sample Amazon DynamoDB event") +@click.option("--region", "-r", + type=str, + default="us-east-1", + help='The region the event should come from (default: "us-east-1")') +@pass_context +@cli_framework_options +def cli(ctx, region): + # All of the logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, region) # pragma: no cover + + +def do_cli(ctx, region): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + event_dict = generate_dynamodb_event(region) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/generate_event/kinesis/__init__.py b/samcli/commands/local/generate_event/kinesis/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/kinesis/cli.py b/samcli/commands/local/generate_event/kinesis/cli.py new file mode 100644 index 0000000000..2ade43e34d --- /dev/null +++ b/samcli/commands/local/generate_event/kinesis/cli.py @@ -0,0 +1,48 @@ +""" +Generates a Kinesis Event for a Lambda Invoke +""" +import base64 +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_kinesis_event + + +@click.command("kinesis", short_help="Generates a sample Amazon Kinesis event") +@click.option("--region", "-r", + type=str, + default="us-east-1", + help='The region the event should come from (default: "us-east-1")') +@click.option("--partition", "-p", + type=str, + default="partitionKey-03", + help='The Kinesis partition key (default: "partitionKey-03")') +@click.option("--sequence", "-s", + type=str, + default="49545115243490985018280067714973144582180062593244200961", + help='The Kinesis sequence number (default: "49545115243490985018280067714973144582180062593244200961")') +@click.option("--data", "-d", + type=str, + default="Hello, this is a test 123.", + help='The Kinesis message payload. There is no need to base64 this - sam will do this for you ' + '(default: "Hello, this is a test 123.")') +@cli_framework_options +@pass_context +def cli(ctx, region, partition, sequence, data): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, region, partition, sequence, data) # pragma: no cover + + +def do_cli(ctx, region, partition, sequence, data): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + + # base64 encode the data + date_base64 = base64.urlsafe_b64encode(data.encode('utf8')) + event_dict = generate_kinesis_event(region, partition, sequence, date_base64) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/generate_event/s3/__init__.py b/samcli/commands/local/generate_event/s3/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/s3/cli.py b/samcli/commands/local/generate_event/s3/cli.py new file mode 100644 index 0000000000..89046f5109 --- /dev/null +++ b/samcli/commands/local/generate_event/s3/cli.py @@ -0,0 +1,39 @@ +""" +Generates a S3 Event for a Lambda Invoke +""" +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_s3_event + + +@click.command("s3", short_help="Generates a sample Amazon S3 event") +@click.option("--region", "-r", + type=str, + default="us-east-1", + help='The region the event should come from (default: "us-east-1")') +@click.option("--bucket", "-b", + type=str, + default="example-bucket", + help='The S3 bucket the event should reference (default: "example-bucket")') +@click.option("--key", "-k", + type=str, + default="test/key", + help='The S3 key the event should reference (default: "test/key")') +@cli_framework_options +@pass_context +def cli(ctx, region, bucket, key): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, region, bucket, key) # pragma: no cover + + +def do_cli(ctx, region, bucket, key): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + event_dict = generate_s3_event(region, bucket, key) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/generate_event/schedule/__init__.py b/samcli/commands/local/generate_event/schedule/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/schedule/cli.py b/samcli/commands/local/generate_event/schedule/cli.py new file mode 100644 index 0000000000..107e7fad84 --- /dev/null +++ b/samcli/commands/local/generate_event/schedule/cli.py @@ -0,0 +1,31 @@ +""" +Generates a Schedule Event for a Lambda Invoke +""" +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_schedule_event + + +@click.command("schedule", short_help="Generates a sample scheduled event") +@click.option("--region", "-r", + type=str, + default="us-east-1", + help='The region the event should come from (default: "us-east-1")') +@cli_framework_options +@pass_context +def cli(ctx, region): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, region) # pragma: no cover + + +def do_cli(ctx, region): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + event_dict = generate_schedule_event(region) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/generate_event/sns/__init__.py b/samcli/commands/local/generate_event/sns/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/generate_event/sns/cli.py b/samcli/commands/local/generate_event/sns/cli.py new file mode 100644 index 0000000000..9075a2e7a8 --- /dev/null +++ b/samcli/commands/local/generate_event/sns/cli.py @@ -0,0 +1,39 @@ +""" +Generates a SNS Event for a Lambda Invoke +""" +import json + +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.lib.events import generate_sns_event + + +@click.command("sns", short_help="Generates a sample Amazon SNS event") +@click.option("--message", "-m", + type=str, + default="example message", + help='The SNS message body (default: "example message")') +@click.option("--topic", "-t", + type=str, + default="arn:aws:sns:us-east-1:111122223333:ExampleTopic", + help='The SNS topic (default: "arn:aws:sns:us-east-1:111122223333:ExampleTopic")') +@click.option("--subject", "-s", + type=str, + default="example subject", + help='The SNS subject (default: "example subject")') +@cli_framework_options +@pass_context +def cli(ctx, message, topic, subject): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, message, topic, subject) # pragma: no cover + + +def do_cli(ctx, message, topic, subject): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + event_dict = generate_sns_event(message, topic, subject) + event = json.dumps(event_dict, indent=4) + click.echo(event) diff --git a/samcli/commands/local/invoke/__init__.py b/samcli/commands/local/invoke/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/invoke/cli.py b/samcli/commands/local/invoke/cli.py new file mode 100644 index 0000000000..0bb8ae6353 --- /dev/null +++ b/samcli/commands/local/invoke/cli.py @@ -0,0 +1,99 @@ +""" +CLI command for "local invoke" command +""" + +import logging +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.cli_common.options import invoke_common_options +from samcli.commands.local.cli_common.user_exceptions import UserException +from samcli.commands.local.cli_common.invoke_context import InvokeContext +from samcli.local.lambdafn.exceptions import FunctionNotFound +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + +LOG = logging.getLogger(__name__) + + +HELP_TEXT = """ +Invokes a local Lambda function once and quits after invocation completes. + +Useful for developing serverless functions that handle asynchronous events (such as S3/Kinesis etc), or if you want to +compose a script of test cases. Event body can be passed in either by stdin (default), or by using the --event +parameter. Runtime output (logs etc) will be outputted to stderr, and the Lambda function result will be outputted to +stdout. +""" + + +@click.command("invoke", help=HELP_TEXT, short_help="Invokes a local Lambda function once") +@click.option("--event", '-e', + type=click.Path(), + default="-", # Defaults to stdin + help="JSON file containing event data passed to the Lambda function during invoke. If this option " + "is not specified, we will default to reading JSON from stdin") +@invoke_common_options +@cli_framework_options +@click.argument('function_identifier', required=False) +@pass_context +def cli(ctx, function_identifier, template, event, env_vars, debug_port, debug_args, docker_volume_basedir, + docker_network, log_file, skip_pull_image, profile): + + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, function_identifier, template, event, env_vars, debug_port, debug_args, docker_volume_basedir, + docker_network, log_file, skip_pull_image, profile) # pragma: no cover + + +def do_cli(ctx, function_identifier, template, event, env_vars, debug_port, debug_args, docker_volume_basedir, + docker_network, log_file, skip_pull_image, profile): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + + LOG.debug("local invoke command is called") + + event_data = _get_event(event) + + # Pass all inputs to setup necessary context to invoke function locally. + # Handler exception raised by the processor for invalid args and print errors + try: + + with InvokeContext(template_file=template, + function_identifier=function_identifier, + env_vars_file=env_vars, + debug_port=debug_port, + debug_args=debug_args, + docker_volume_basedir=docker_volume_basedir, + docker_network=docker_network, + log_file=log_file, + skip_pull_image=skip_pull_image, + aws_profile=profile) as context: + + # Invoke the function + context.local_lambda_runner.invoke(context.function_name, + event=event_data, + stdout=context.stdout, + stderr=context.stderr) + + except FunctionNotFound: + raise UserException("Function {} not found in template".format(function_identifier)) + except InvalidSamDocumentException as ex: + raise UserException(str(ex)) + + +def _get_event(event_file_name): + """ + Read the event JSON data from the given file. If no file is provided, read the event from stdin. + + :param string event_file_name: Path to event file, or '-' for stdin + :return string: Contents of the event file or stdin + """ + + if event_file_name == "-": + # If event is empty, listen to stdin for event data until EOF + LOG.info("Reading invoke payload from stdin (you can also pass it from file with --event)") + + # click.open_file knows to open stdin when filename is '-'. This is safer than manually opening streams, and + # accidentally closing a standard stream + with click.open_file(event_file_name, 'r') as fp: + return fp.read() diff --git a/samcli/commands/local/lib/__init__.py b/samcli/commands/local/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/lib/events.py b/samcli/commands/local/lib/events.py new file mode 100644 index 0000000000..17bd77b863 --- /dev/null +++ b/samcli/commands/local/lib/events.py @@ -0,0 +1,305 @@ +""" +File that holds functions for generating different types of events +""" + +from samcli.local.events.api_event import ContextIdentity, ApiGatewayLambdaEvent, RequestContext + + +def generate_s3_event(region, bucket, key): + """ + Generates a S3 Event + + :param str region: AWS Region + :param str bucket: Name of the S3 bucket + :param str key: S3 Bucket Key + :return dict: Dictionary representing the S3 Event + """ + return { + "Records": [{ + "eventVersion": "2.0", + "eventTime": "1970-01-01T00:00:00.000Z", + "requestParameters": { + "sourceIPAddress": "127.0.0.1" + }, + "s3": { + "configurationId": "testConfigRule", + "object": { + "eTag": "0123456789abcdef0123456789abcdef", + "sequencer": "0A1B2C3D4E5F678901", + "key": key, + "size": 1024 + }, + "bucket": { + "arn": "arn:aws:s3:::{}".format(bucket), + "name": bucket, + "ownerIdentity": { + "principalId": "EXAMPLE" + } + }, + "s3SchemaVersion": "1.0" + }, + "responseElements": { + "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", + "x-amz-request-id": "EXAMPLE123456789" + }, + "awsRegion": region, + "eventName": "ObjectCreated:Put", + "userIdentity": { + "principalId": "EXAMPLE" + }, + "eventSource": "aws:s3" + }] + } + + +def generate_sns_event(message, topic, subject): + """ + Generates a SNS Event + + :param str message: Message sent to the topic + :param str topic: Name of the Topic + :param str subject: Subject of the Topic + :return dict: Dictionary representing the SNS Event + """ + return { + "Records": [{ + "EventVersion": "1.0", + "EventSubscriptionArn": "arn:aws:sns:EXAMPLE", + "EventSource": "aws:sns", + "Sns": { + "SignatureVersion": "1", + "Timestamp": "1970-01-01T00:00:00.000Z", + "Signature": "EXAMPLE", + "SigningCertUrl": "EXAMPLE", + "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", + "Message": message, + "MessageAttributes": { + "Test": { + "Type": "String", + "Value": "TestString" + }, + "TestBinary": { + "Type": "Binary", + "Value": "TestBinary" + } + }, + "Type": "Notification", + "UnsubscribeUrl": "EXAMPLE", + "TopicArn": topic, + "Subject": subject + } + }] + } + + +def generate_schedule_event(region): + """ + Generates a Scheduled Event + + :param str region: AWS Region + :return dict: Dictionary representing the Schedule Event + """ + return { + "account": "123456789012", + "region": region, + "detail": {}, + "detail-type": "Scheduled Event", + "source": "aws.events", + "time": "1970-01-01T00:00:00Z", + "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", + "resources": [ + "arn:aws:events:us-east-1:123456789012:rule/my-schedule" + ] + } + + +def generate_dynamodb_event(region): + """ + Generates a DynamoDG Event + + :param str region: AWS region + :return dict: Dictionary representing the DynamoDB Event + """ + return { + "Records": [ + { + "eventID": "1", + "eventVersion": "1.0", + "dynamodb": { + "Keys": { + "Id": { + "N": "101" + } + }, + "NewImage": { + "Message": { + "S": "New item!" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES", + "SequenceNumber": "111", + "SizeBytes": 26 + }, + "awsRegion": region, + "eventName": "INSERT", + "eventSourceARN": "arn:aws:dynamodb:{}:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899".format(region), + "eventSource": "aws:dynamodb" + }, + { + "eventID": "2", + "eventVersion": "1.0", + "dynamodb": { + "OldImage": { + "Message": { + "S": "New item!" + }, + "Id": { + "N": "101" + } + }, + "SequenceNumber": "222", + "Keys": { + "Id": { + "N": "101" + } + }, + "SizeBytes": 59, + "NewImage": { + "Message": { + "S": "This item has changed" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES" + }, + "awsRegion": region, + "eventName": "MODIFY", + "eventSourceARN": + "arn:aws:dynamodb:{}:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899".format(region), + "eventSource": "aws:dynamodb" + }, + { + "eventID": "3", + "eventVersion": "1.0", + "dynamodb": { + "Keys": { + "Id": { + "N": "101" + } + }, + "SizeBytes": 38, + "SequenceNumber": "333", + "OldImage": { + "Message": { + "S": "This item has changed" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES" + }, + "awsRegion": region, + "eventName": "REMOVE", + "eventSourceARN": "arn:aws:dynamodb:{}:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899".format(region), + "eventSource": "aws:dynamodb" + } + ] + } + + +def generate_kinesis_event(region, partition, sequence, data): + """ + Generates a Kinesis Event + + :param str region: AWS Region + :param str partition: PartitionKey in Kinesis + :param str sequence: Sequence Number as a string + :param str data: Data for the stream + :return dict: Dictionary representing the Kinesis Event + """ + return { + "Records": [{ + "eventID": "shardId-000000000000:{}".format(sequence), + "eventVersion": "1.0", + "kinesis": { + "approximateArrivalTimestamp": 1428537600, + "partitionKey": partition, + "data": data, + "kinesisSchemaVersion": "1.0", + "sequenceNumber": sequence + }, + "invokeIdentityArn": "arn:aws:iam::EXAMPLE", + "eventName": "aws:kinesis:record", + "eventSourceARN": "arn:aws:kinesis:EXAMPLE", + "eventSource": "aws:kinesis", + "awsRegion": region + }] + } + + +def generate_api_event(method, body, resource, path): + """ + Generates an Api Event + + :param str method: HTTP Method of the request + :param str body: Body of the request + :param str resource: Api Gateway resource path + :param str path: Request path + :return dict: Dictionary representing the Api Event + """ + headers = { + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "Accept-Language": "en-US,en;q=0.8", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Mobile-Viewer": "false", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "CloudFront-Viewer-Country": "US", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Upgrade-Insecure-Requests": "1", + "X-Forwarded-Port": "443", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "X-Forwarded-Proto": "https", + "X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==", + "CloudFront-Is-Tablet-Viewer": "false", + "Cache-Control": "max-age=0", + "User-Agent": "Custom User Agent String", + "CloudFront-Forwarded-Proto": "https", + "Accept-Encoding": "gzip, deflate, sdch" + } + + query_params = { + "foo": "bar" + } + + path_params = { + "proxy": path + } + + identity = ContextIdentity(source_ip='127.0.0.1') + + context = RequestContext(resource_path=resource, + http_method=method, + stage="prod", + identity=identity, + path=resource) + + event = ApiGatewayLambdaEvent(http_method=method, + body=body, + resource=resource, + request_context=context, + query_string_params=query_params, + headers=headers, + path_parameters=path_params, + path=path) + + return event.to_dict() diff --git a/samcli/commands/local/lib/exceptions.py b/samcli/commands/local/lib/exceptions.py new file mode 100644 index 0000000000..f7fefd0259 --- /dev/null +++ b/samcli/commands/local/lib/exceptions.py @@ -0,0 +1,10 @@ +""" +Custom exceptions raised by this local library +""" + + +class NoApisDefined(Exception): + """ + Raised when there are no APIs defined in the template + """ + pass diff --git a/samcli/commands/local/lib/local_api_service.py b/samcli/commands/local/lib/local_api_service.py new file mode 100644 index 0000000000..e8761798de --- /dev/null +++ b/samcli/commands/local/lib/local_api_service.py @@ -0,0 +1,168 @@ +""" +Connects the CLI with Local API Gateway service. +""" + +import os +import logging + +from samcli.local.apigw.service import Service, Route +from samcli.commands.local.lib.sam_api_provider import SamApiProvider +from samcli.commands.local.lib.exceptions import NoApisDefined + +LOG = logging.getLogger(__name__) + + +class LocalApiService(object): + """ + Implementation of Local API service that is capable of serving APIs defined in a SAM file that invoke a Lambda + function. + """ + + def __init__(self, + lambda_invoke_context, + port, + host, + static_dir): + """ + Initialize the local API service. + + :param samcli.commands.local.cli_common.invoke_context.InvokeContext lambda_invoke_context: Context object + that can help with Lambda invocation + :param int port: Port to listen on + :param string host: Local hostname or IP address to bind to + :param string static_dir: Optional, directory from which static files will be mounted + """ + + self.port = port + self.host = host + self.static_dir = static_dir + + self.cwd = lambda_invoke_context.get_cwd() + self.api_provider = SamApiProvider(lambda_invoke_context.template, cwd=self.cwd) + self.lambda_runner = lambda_invoke_context.local_lambda_runner + self.stderr_stream = lambda_invoke_context.stderr + + def start(self): + """ + Creates and starts the local API Gateway service. This method will block until the service is stopped + manually using an interrupt. After the service is started, callers can make HTTP requests to the endpoint + to invoke the Lambda function and receive a response. + + NOTE: This is a blocking call that will not return until the thread is interrupted with SIGINT/SIGTERM + """ + + routing_list = self._make_routing_list(self.api_provider) + + if not routing_list: + raise NoApisDefined("No APIs available in SAM template") + + static_dir_path = self._make_static_dir_path(self.cwd, self.static_dir) + + # We care about passing only stderr to the Service and not stdout because stdout from Docker container + # contains the response to the API which is sent out as HTTP response. Only stderr needs to be printed + # to the console or a log file. stderr from Docker container contains runtime logs and output of print + # statements from the Lambda function + service = Service(routing_list=routing_list, + lambda_runner=self.lambda_runner, + static_dir=static_dir_path, + port=self.port, + host=self.host, + stderr=self.stderr_stream) + + service.create() + + # Print out the list of routes that will be mounted + self._print_routes(self.api_provider, self.host, self.port) + LOG.info("You can now browse to the above endpoints to invoke your functions. " + "You do not need to restart/reload SAM CLI while working on your functions " + "changes will be reflected instantly/automatically. You only need to restart " + "SAM CLI if you update your AWS SAM template") + + service.run() + + @staticmethod + def _make_routing_list(api_provider): + """ + Returns a list of routes to configure the Local API Service based on the APIs configured in the template. + + Parameters + ---------- + api_provider : samcli.commands.local.lib.sam_api_provider.SamApiProvider + + Returns + ------- + list(samcli.local.apigw.service.Route) + List of Routes to pass to the service + """ + + routes = [] + for api in api_provider.get_all(): + route = Route(methods=[api.method], function_name=api.function_name, path=api.path, + binary_types=api.binary_media_types) + routes.append(route) + + return routes + + @staticmethod + def _print_routes(api_provider, host, port): + """ + Helper method to print the APIs that will be mounted. This method is purely for printing purposes. + This method takes in a list of Route Configurations and prints out the Routes grouped by path. + Grouping routes by Function Name + Path is the bulk of the logic. + + Example output: + Mounting Product at http://127.0.0.1:3000/path1/bar [GET, POST, DELETE] + Mounting Product at http://127.0.0.1:3000/path2/bar [HEAD] + + :param samcli.commands.local.lib.provider.ApiProvider api_provider: API Provider that can return a list of APIs + :param string host: Host name where the service is running + :param int port: Port number where the service is running + :returns list(string): List of lines that were printed to the console. Helps with testing + """ + grouped_api_configs = {} + + for api in api_provider.get_all(): + key = "{}-{}".format(api.function_name, api.path) + + config = grouped_api_configs.get(key, {}) + config.setdefault("methods", []) + + config["function_name"] = api.function_name + config["path"] = api.path + config["methods"].append(api.method) + + grouped_api_configs[key] = config + + print_lines = [] + for _, config in grouped_api_configs.items(): + methods_str = "[{}]".format(', '.join(config["methods"])) + output = "Mounting {} at http://{}:{}{} {}".format( + config["function_name"], + host, + port, + config["path"], + methods_str) + print_lines.append(output) + + LOG.info(output) + + return print_lines + + @staticmethod + def _make_static_dir_path(cwd, static_dir): + """ + This method returns the path to the directory where static files are to be served from. If static_dir is a + relative path, then it is resolved to be relative to the current working directory. If no static directory is + provided, or if the resolved directory does not exist, this method will return None + + :param string cwd: Current working directory relative to which we will resolve the static directory + :param string static_dir: Path to the static directory + :return string: Path to the static directory, if it exists. None, otherwise + """ + if not static_dir: + return None + + static_dir_path = os.path.join(cwd, static_dir) + if os.path.exists(static_dir_path): + LOG.info("Mounting static files from %s at /", static_dir_path) + return static_dir_path diff --git a/samcli/commands/local/lib/local_lambda.py b/samcli/commands/local/lib/local_lambda.py new file mode 100644 index 0000000000..2e7c9805e1 --- /dev/null +++ b/samcli/commands/local/lib/local_lambda.py @@ -0,0 +1,219 @@ +""" +Implementation of Local Lambda runner +""" + +import os +import logging +import boto3 + +from samcli.local.lambdafn.env_vars import EnvironmentVariables +from samcli.local.lambdafn.config import FunctionConfig +from samcli.local.lambdafn.exceptions import FunctionNotFound + +LOG = logging.getLogger(__name__) + + +class LocalLambdaRunner(object): + """ + Runs Lambda functions locally. This class is a wrapper around the `samcli.local` library which takes care + of actually running the function on a Docker container. + """ + PRESENT_DIR = "." + + def __init__(self, + local_runtime, + function_provider, + cwd, + env_vars_values=None, + debug_port=None, + debug_args=None, + aws_profile=None + ): + """ + Initializes the class + + :param samcli.local.lambdafn.runtime.LambdaRuntime local_runtime: Lambda runtime capable of running a function + :param samcli.commands.local.lib.provider.FunctionProvider function_provider: Provider that can return a + Lambda function + :param string cwd: Current working directory. We will resolve all function CodeURIs relative to this directory. + :param dict env_vars_values: Optional. Dictionary containing values of environment variables + :param integer debug_port: Optional. Port to bind the debugger to + :param string debug_args: Optional. Additional arguments passed to the debugger + :param string aws_profile: Optional. AWS Credentials profile to use + """ + + self.local_runtime = local_runtime + self.provider = function_provider + self.cwd = cwd + self.env_vars_values = env_vars_values or {} + self.debug_port = debug_port + self.debug_args = debug_args + self.aws_profile = aws_profile + + def invoke(self, function_name, event, stdout=None, stderr=None): + """ + Find the Lambda function with given name and invoke it. Pass the given event to the function and return + response through the given streams. + + This function will block until either the function completes or times out. + + :param string function_name: Name of the Lambda function to invoke + :param string event: Event data passed to the function. Must be a valid JSON String. + :param io.BaseIO stdout: Stream to write the output of the Lambda function to. + :param io.BaseIO stderr: Stream to write the Lambda runtime logs to. + :raises FunctionNotfound: When we cannot find a function with the given name + """ + + # Generate the correct configuration based on given inputs + function = self.provider.get(function_name) + + if not function: + raise FunctionNotFound("Unable to find a Function with name '%s'", function_name) + + LOG.debug("Found one Lambda function with name '%s'", function_name) + + LOG.info("Invoking %s (%s)", function.handler, function.runtime) + config = self._get_invoke_config(function) + + # Invoke the function + self.local_runtime.invoke(config, event, debug_port=self.debug_port, debug_args=self.debug_args, + stdout=stdout, stderr=stderr) + + def is_debugging(self): + """ + Are we debugging the invoke? + + Returns + ------- + bool + True, if we are debugging the invoke ie. the Docker container will break into the debugger and wait for + attach + """ + return bool(self.debug_port) + + def _get_invoke_config(self, function): + """ + Returns invoke configuration to pass to Lambda Runtime to invoke the given function + + :param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for + :return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime + """ + + env_vars = self._make_env_vars(function) + code_abs_path = self._get_code_path(function.codeuri) + + LOG.debug("Resolved absolute path to code is %s", code_abs_path) + + return FunctionConfig(name=function.name, + runtime=function.runtime, + handler=function.handler, + code_abs_path=code_abs_path, + memory=function.memory, + timeout=function.timeout, + env_vars=env_vars) + + def _make_env_vars(self, function): + """ + Returns the environment variables configuration for this function + + :param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for + :return samcli.local.lambdafn.env_vars.EnvironmentVariables: Environment variable configuration for this + function + """ + + name = function.name + + variables = None + if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment: + variables = function.environment["Variables"] + else: + LOG.debug("No environment variables found for function '%s'", name) + + # This could either be in standard format, or a CloudFormation parameter file format. + # + # Standard format is {FunctionName: {key:value}, FunctionName: {key:value}} + # CloudFormation parameter file is {"Parameters": {key:value}} + if "Parameters" in self.env_vars_values: + LOG.debug("Environment variables overrides data is in CloudFormation parameter file format") + # CloudFormation parameter file format + overrides = self.env_vars_values["Parameters"] + else: + # Standard format + LOG.debug("Environment variables overrides data is standard format") + overrides = self.env_vars_values.get(name, None) + + shell_env = os.environ + aws_creds = self.get_aws_creds() + + return EnvironmentVariables(function.memory, + function.timeout, + function.handler, + variables=variables, + shell_env_values=shell_env, + override_values=overrides, + aws_creds=aws_creds) + + def _get_code_path(self, codeuri): + """ + Returns path to the function code resolved based on current working directory. + + :param string codeuri: CodeURI of the function. This should contain the path to the function code + :return string: Absolute path to the function code + """ + + LOG.debug("Resolving code path. Cwd=%s, CodeUri=%s", self.cwd, codeuri) + + # First, let us figure out the current working directory. + # If current working directory is not provided, then default to the directory where the CLI is running from + if not self.cwd or self.cwd == self.PRESENT_DIR: + self.cwd = os.getcwd() + + # Make sure cwd is an absolute path + self.cwd = os.path.abspath(self.cwd) + + # Next, let us get absolute path of function code. + # Codepath is always relative to current working directory + # If the path is relative, then construct the absolute version + if not os.path.isabs(codeuri): + codeuri = os.path.normpath(os.path.join(self.cwd, codeuri)) + + return codeuri + + def get_aws_creds(self): + """ + Returns AWS credentials obtained from the shell environment or given profile + + :return dict: A dictionary containing credentials. This dict has the structure + {"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved, + this returns None + """ + result = {} + + LOG.debug("Loading AWS credentials from session with profile '%s'", self.aws_profile) + session = boto3.session.Session(profile_name=self.aws_profile) + + if not session: + return result + + # Load the credentials from profile/environment + creds = session.get_credentials() + + if not creds: + # If we were unable to load credentials, then just return empty. We will use the default + return result + + # After loading credentials, region name might be available here. + if hasattr(session, 'region_name') and session.region_name: + result["region"] = session.region_name + + # Only add the key, if its value is present + if hasattr(creds, 'access_key') and creds.access_key: + result["key"] = creds.access_key + + if hasattr(creds, 'secret_key') and creds.secret_key: + result["secret"] = creds.secret_key + + if hasattr(creds, 'token') and creds.token: + result["sessiontoken"] = creds.token + + return result diff --git a/samcli/commands/local/lib/provider.py b/samcli/commands/local/lib/provider.py new file mode 100644 index 0000000000..7e3183fc7b --- /dev/null +++ b/samcli/commands/local/lib/provider.py @@ -0,0 +1,105 @@ +""" +A provider class that can parse and return Lambda Functions from a variety of sources. A SAM template is one such +source +""" + +from collections import namedtuple + +# Named Tuple to representing the properties of a Lambda Function +Function = namedtuple("Function", [ + # Function name or logical ID + "name", + + # Runtime/language + "runtime", + + # Memory in MBs + "memory", + + # Function Timeout in seconds + "timeout", + + # Name of the handler + "handler", + + # Path to the code. This could be a S3 URI or local path or a dictionary of S3 Bucket, Key, Version + "codeuri", + + # Environment variables. This is a dictionary with one key called Variables inside it. This contains the definition + # of environment variables + "environment", + + # Lambda Execution IAM Role ARN. In the future, this can be used by Local Lambda runtime to assume the IAM role + # to get credentials to run the container with. This gives a much higher fidelity simulation of cloud Lambda. + "rolearn" +]) + + +class FunctionProvider(object): + """ + Abstract base class of the function provider. + """ + + def get(self, name): + """ + Given name of the function, this method must return the Function object + + :param string name: Name of the function + :return Function: namedtuple containing the Function information + """ + raise NotImplementedError("not implemented") + + def get_all(self): + """ + Yields all the Lambda functions available in the provider. + + :yields Function: namedtuple containing the function information + """ + raise NotImplementedError("not implemented") + + +_ApiTuple = namedtuple("Api", [ + + # String. Path that this API serves. Ex: /foo, /bar/baz + "path", + + # String. HTTP Method this API responds with + "method", + + # String. Name of the Function this API connects to + "function_name", + + # Optional Dictionary containing CORS configuration on this path+method + # If this configuration is set, then API server will automatically respond to OPTIONS HTTP method on this path and + # respond with appropriate CORS headers based on configuration. + "cors", + + # List(Str). List of the binary media types the API + "binary_media_types" +]) +_ApiTuple.__new__.__defaults__ = (None, # Cors is optional and defaults to None + [] # binary_media_types is optional and defaults to empty + ) + + +class Api(_ApiTuple): + def __hash__(self): + # Other properties are not a part of the hash + return hash(self.path) * hash(self.method) * hash(self.function_name) + + +Cors = namedtuple("Cors", ["AllowOrigin", "AllowMethods", "AllowHeaders"]) + + +class ApiProvider(object): + """ + Abstract base class to return APIs and the functions they route to + """ + + def get_all(self): + """ + Yields all the APIs available. + + :yields Api: namedtuple containing the API information + """ + raise NotImplementedError("not implemented") diff --git a/samcli/commands/local/lib/sam_api_provider.py b/samcli/commands/local/lib/sam_api_provider.py new file mode 100644 index 0000000000..901dfbd8ac --- /dev/null +++ b/samcli/commands/local/lib/sam_api_provider.py @@ -0,0 +1,468 @@ +"""Class that provides Apis from a SAM Template""" + +import logging +from collections import namedtuple + +from six import string_types + +from samcli.commands.local.lib.swagger.parser import SwaggerParser +from samcli.commands.local.lib.provider import ApiProvider, Api +from samcli.commands.local.lib.sam_base_provider import SamBaseProvider +from samcli.commands.local.lib.swagger.reader import SamSwaggerReader +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + +LOG = logging.getLogger(__name__) + + +class SamApiProvider(ApiProvider): + + _IMPLICIT_API_RESOURCE_ID = "ServerlessRestApi" + _SERVERLESS_FUNCTION = "AWS::Serverless::Function" + _SERVERLESS_API = "AWS::Serverless::Api" + _TYPE = "Type" + + _FUNCTION_EVENT_TYPE_API = "Api" + _FUNCTION_EVENT = "Events" + _EVENT_PATH = "Path" + _EVENT_METHOD = "Method" + + _ANY_HTTP_METHODS = ["GET", + "DELETE", + "PUT", + "POST", + "HEAD", + "OPTIONS", + "PATCH"] + + def __init__(self, template_dict, cwd=None): + """ + Initialize the class with SAM template data. The template_dict (SAM Templated) is assumed + to be valid, normalized and a dictionary. template_dict should be normalized by running any and all + pre-processing before passing to this class. + This class does not perform any syntactic validation of the template. + + After the class is initialized, changes to ``template_dict`` will not be reflected in here. + You will need to explicitly update the class with new template, if necessary. + + Parameters + ---------- + template_dict : dict + SAM Template as a dictionary + cwd : str + Optional working directory with respect to which we will resolve relative path to Swagger file + """ + + self.template_dict = SamBaseProvider.get_template(template_dict) + self.resources = self.template_dict.get("Resources", {}) + + LOG.debug("%d resources found in the template", len(self.resources)) + + # Store a set of apis + self.cwd = cwd + self.apis = self._extract_apis(self.resources) + + LOG.debug("%d APIs found in the template", len(self.apis)) + + def get_all(self): + """ + Yields all the Lambda functions with Api Events available in the SAM Template. + + :yields Api: namedtuple containing the Api information + """ + + for api in self.apis: + yield api + + def _extract_apis(self, resources): + """ + Extract all Implicit Apis (Apis defined through Serverless Function with an Api Event + + :param dict resources: Dictionary of SAM/CloudFormation resources + :return: List of nametuple Api + """ + + # Some properties like BinaryMediaTypes, Cors are set once on the resource but need to be applied to each API. + # For Implicit APIs, which are defined on the Function resource, these properties + # are defined on a AWS::Serverless::Api resource with logical ID "ServerlessRestApi". Therefore, no matter + # if it is an implicit API or an explicit API, there is a corresponding resource of type AWS::Serverless::Api + # that contains these additional configurations. + # + # We use this assumption in the following loop to collect information from resources of type + # AWS::Serverless::Api. We also extract API from Serverless::Function resource and add them to the + # corresponding Serverless::Api resource. This is all done using the ``collector``. + + collector = ApiCollector() + + for logical_id, resource in resources.items(): + + resource_type = resource.get(SamApiProvider._TYPE) + + if resource_type == SamApiProvider._SERVERLESS_FUNCTION: + self._extract_apis_from_function(logical_id, resource, collector) + + if resource_type == SamApiProvider._SERVERLESS_API: + self._extract_from_serverless_api(logical_id, resource, collector) + + apis = SamApiProvider._merge_apis(collector) + return self._normalize_apis(apis) + + def _extract_from_serverless_api(self, logical_id, api_resource, collector): + """ + Extract APIs from AWS::Serverless::Api resource by reading and parsing Swagger documents. The result is added + to the collector. + + Parameters + ---------- + logical_id : str + Logical ID of the resource + + api_resource : dict + Resource definition, including its properties + + collector : ApiCollector + Instance of the API collector that where we will save the API information + """ + + properties = api_resource.get("Properties", {}) + body = properties.get("DefinitionBody") + uri = properties.get("DefinitionUri") + binary_media = properties.get("BinaryMediaTypes", []) + + if not body and not uri: + # Swagger is not found anywhere. + LOG.debug("Skipping resource '%s'. Swagger document not found in DefinitionBody and DefinitionUri", + logical_id) + return + + reader = SamSwaggerReader(definition_body=body, + definition_uri=uri, + working_dir=self.cwd) + swagger = reader.read() + parser = SwaggerParser(swagger) + apis = parser.get_apis() + LOG.debug("Found '%s' APIs in resource '%s'", len(apis), logical_id) + + collector.add_apis(logical_id, apis) + collector.add_binary_media_types(logical_id, parser.get_binary_media_types()) # Binary media from swagger + collector.add_binary_media_types(logical_id, binary_media) # Binary media specified on resource in template + + @staticmethod + def _merge_apis(collector): + """ + Quite often, an API is defined both in Implicit and Explicit API definitions. In such cases, Implicit API + definition wins because that conveys clear intent that the API is backed by a function. This method will + merge two such list of Apis with the right order of precedence. If a Path+Method combination is defined + in both the places, only one wins. + + Parameters + ---------- + collector : ApiCollector + Collector object that holds all the APIs specified in the template + + Returns + ------- + list of samcli.commands.local.lib.provider.Api + List of APIs obtained by combining both the input lists. + """ + + implicit_apis = [] + explicit_apis = [] + + # Store implicit and explicit APIs separately in order to merge them later in the correct order + # Implicit APIs are defined on a resource with logicalID ServerlessRestApi + for logical_id, apis in collector: + if logical_id == SamApiProvider._IMPLICIT_API_RESOURCE_ID: + implicit_apis.extend(apis) + else: + explicit_apis.extend(apis) + + # We will use "path+method" combination as key to this dictionary and store the Api config for this combination. + # If an path+method combo already exists, then overwrite it if and only if this is an implicit API + all_apis = {} + + # By adding implicit APIs to the end of the list, they will be iterated last. If a configuration was already + # written by explicit API, it will be overriden by implicit API, just by virtue of order of iteration. + all_configs = explicit_apis + implicit_apis + + for config in all_configs: + # Normalize the methods before de-duping to allow an ANY method in implicit API to override a regular HTTP + # method on explicit API. + for normalized_method in SamApiProvider._normalize_http_methods(config.method): + key = config.path + normalized_method + all_apis[key] = config + + result = set(all_apis.values()) # Assign to a set() to de-dupe + LOG.debug("Removed duplicates from '%d' Explicit APIs and '%d' Implicit APIs to produce '%d' APIs", + len(explicit_apis), len(implicit_apis), len(result)) + + return list(result) + + @staticmethod + def _normalize_apis(apis): + """ + Normalize the APIs to use standard method name + + Parameters + ---------- + apis : list of samcli.commands.local.lib.provider.Api + List of APIs to replace normalize + + Returns + ------- + list of samcli.commands.local.lib.provider.Api + List of normalized APIs + """ + + result = list() + for api in apis: + for normalized_method in SamApiProvider._normalize_http_methods(api.method): + # _replace returns a copy of the namedtuple. This is the official way of creating copies of namedtuple + result.append(api._replace(method=normalized_method)) + + return result + + @staticmethod + def _extract_apis_from_function(logical_id, function_resource, collector): + """ + Fetches a list of APIs configured for this SAM Function resource. + + Parameters + ---------- + logical_id : str + Logical ID of the resource + + function_resource : dict + Contents of the function resource including its properties + + collector : ApiCollector + Instance of the API collector that where we will save the API information + """ + + resource_properties = function_resource.get("Properties", {}) + serverless_function_events = resource_properties.get(SamApiProvider._FUNCTION_EVENT, {}) + SamApiProvider._extract_apis_from_events(logical_id, serverless_function_events, collector) + + @staticmethod + def _extract_apis_from_events(function_logical_id, serverless_function_events, collector): + """ + Given an AWS::Serverless::Function Event Dictionary, extract out all 'Api' events and store within the + collector + + Parameters + ---------- + function_logical_id : str + LogicalId of the AWS::Serverless::Function + + serverless_function_events : dict + Event Dictionary of a AWS::Serverless::Function + + collector : ApiCollector + Instance of the API collector that where we will save the API information + """ + count = 0 + for _, event in serverless_function_events.items(): + + if SamApiProvider._FUNCTION_EVENT_TYPE_API == event.get(SamApiProvider._TYPE): + api_resource_id, api = SamApiProvider._convert_event_api(function_logical_id, event.get("Properties")) + collector.add_apis(api_resource_id, [api]) + count += 1 + + LOG.debug("Found '%d' API Events in Serverless function with name '%s'", count, function_logical_id) + + @staticmethod + def _convert_event_api(lambda_logical_id, event_properties): + """ + Converts a AWS::Serverless::Function's Event Property to an Api configuration usable by the provider. + + :param str lambda_logical_id: Logical Id of the AWS::Serverless::Function + :param dict event_properties: Dictionary of the Event's Property + :return tuple: tuple of API resource name and Api namedTuple + """ + path = event_properties.get(SamApiProvider._EVENT_PATH) + method = event_properties.get(SamApiProvider._EVENT_METHOD) + + # An API Event, can have RestApiId property which designates the resource that owns this API. If omitted, + # the API is owned by Implicit API resource. This could either be a direct resource logical ID or a + # "Ref" of the logicalID + api_resource_id = event_properties.get("RestApiId", SamApiProvider._IMPLICIT_API_RESOURCE_ID) + if isinstance(api_resource_id, dict) and "Ref" in api_resource_id: + api_resource_id = api_resource_id["Ref"] + + # This is still a dictionary. Something wrong with the template + if isinstance(api_resource_id, dict): + LOG.debug("Invalid RestApiId property of event %s", event_properties) + raise InvalidSamDocumentException("RestApiId property of resource with logicalId '{}' is invalid. " + "It should either be a LogicalId string or a Ref of a Logical Id string" + .format(lambda_logical_id)) + + return api_resource_id, Api(path=path, method=method, function_name=lambda_logical_id) + + @staticmethod + def _normalize_http_methods(http_method): + """ + Normalizes Http Methods. Api Gateway allows a Http Methods of ANY. This is a special verb to denote all + supported Http Methods on Api Gateway. + + :param str http_method: Http method + :yield str: Either the input http_method or one of the _ANY_HTTP_METHODS (normalized Http Methods) + """ + + if http_method.upper() == 'ANY': + for method in SamApiProvider._ANY_HTTP_METHODS: + yield method.upper() + else: + yield http_method.upper() + + +class ApiCollector(object): + """ + Class to store the API configurations in the SAM Template. This class helps store both implicit and explicit + APIs in a standardized format + """ + + # Properties of each API. The structure is quite similar to the properties of AWS::Serverless::Api resource. + # This is intentional because it allows us to easily extend this class to support future properties on the API. + # We will store properties of Implicit APIs also in this format which converges the handling of implicit & explicit + # APIs. + Properties = namedtuple("Properties", ["apis", "binary_media_types", "cors"]) + + def __init__(self): + # API properties stored per resource. Key is the LogicalId of the AWS::Serverless::Api resource and + # value is the properties + self.by_resource = {} + + def __iter__(self): + """ + Iterator to iterate through all the APIs stored in the collector. In each iteration, this yields the + LogicalId of the API resource and a list of APIs available in this resource. + + Yields + ------- + str + LogicalID of the AWS::Serverless::Api resource + list samcli.commands.local.lib.provider.Api + List of the API available in this resource along with additional configuration like binary media types. + """ + + for logical_id, _ in self.by_resource.items(): + yield logical_id, self._get_apis_with_config(logical_id) + + def add_apis(self, logical_id, apis): + """ + Stores the given APIs tagged under the given logicalId + + Parameters + ---------- + logical_id : str + LogicalId of the AWS::Serverless::Api resource + + apis : list of samcli.commands.local.lib.provider.Api + List of APIs available in this resource + """ + properties = self._get_properties(logical_id) + properties.apis.extend(apis) + + def add_binary_media_types(self, logical_id, binary_media_types): + """ + Stores the binary media type configuration for the API with given logical ID + + Parameters + ---------- + logical_id : str + LogicalId of the AWS::Serverless::Api resource + + binary_media_types : list of str + List of binary media types supported by this resource + + """ + properties = self._get_properties(logical_id) + + binary_media_types = binary_media_types or [] + for value in binary_media_types: + normalized_value = self._normalize_binary_media_type(value) + + # If the value is not supported, then just skip it. + if normalized_value: + properties.binary_media_types.add(normalized_value) + else: + LOG.debug("Unsupported data type of binary media type value of resource '%s'", logical_id) + + def _get_apis_with_config(self, logical_id): + """ + Returns the list of APIs in this resource along with other extra configuration such as binary media types, + cors etc. Additional configuration is merged directly into the API data because these properties, although + defined globally, actually apply to each API. + + Parameters + ---------- + logical_id : str + Logical ID of the resource to fetch data for + + Returns + ------- + list of samcli.commands.local.lib.provider.Api + List of APIs with additional configurations for the resource with given logicalId. If there are no APIs, + then it returns an empty list + """ + + properties = self._get_properties(logical_id) + + # These configs need to be applied to each API + binary_media = sorted(list(properties.binary_media_types)) # Also sort the list to keep the ordering stable + cors = properties.cors + + result = [] + for api in properties.apis: + # Create a copy of the API with updated configuration + updated_api = api._replace(binary_media_types=binary_media, + cors=cors) + result.append(updated_api) + + return result + + def _get_properties(self, logical_id): + """ + Returns the properties of resource with given logical ID. If a resource is not found, then it returns an + empty data. + + Parameters + ---------- + logical_id : str + Logical ID of the resource + + Returns + ------- + samcli.commands.local.lib.sam_api_provider.ApiCollector.Properties + Properties object for this resource. + """ + + if logical_id not in self.by_resource: + self.by_resource[logical_id] = self.Properties(apis=[], + # Use a set() to be able to easily de-dupe + binary_media_types=set(), + cors=None) + + return self.by_resource[logical_id] + + @staticmethod + def _normalize_binary_media_type(value): + """ + Converts binary media types values to the canonical format. Ex: image~1gif -> image/gif. If the value is not + a string, then this method just returns None + + Parameters + ---------- + value : str + Value to be normalized + + Returns + ------- + str or None + Normalized value. If the input was not a string, then None is returned + """ + + if not isinstance(value, string_types): + # It is possible that user specified a dict value for one of the binary media types. We just skip them + return None + + return value.replace("~1", "/") diff --git a/samcli/commands/local/lib/sam_base_provider.py b/samcli/commands/local/lib/sam_base_provider.py new file mode 100644 index 0000000000..50c6f94b78 --- /dev/null +++ b/samcli/commands/local/lib/sam_base_provider.py @@ -0,0 +1,19 @@ +""" +Base class for SAM Template providers +""" + +from samcli.lib.samlib.wrapper import SamTranslatorWrapper + + +class SamBaseProvider(object): + """ + Base class for SAM Template providers + """ + + @staticmethod + def get_template(template_dict): + template_dict = template_dict or {} + if template_dict: + template_dict = SamTranslatorWrapper(template_dict).run_plugins() + + return template_dict diff --git a/samcli/commands/local/lib/sam_function_provider.py b/samcli/commands/local/lib/sam_function_provider.py new file mode 100644 index 0000000000..395c8961f2 --- /dev/null +++ b/samcli/commands/local/lib/sam_function_provider.py @@ -0,0 +1,163 @@ +""" +Class that provides functions from a given SAM template +""" + +import logging +import six + +from .provider import FunctionProvider, Function +from .sam_base_provider import SamBaseProvider + +LOG = logging.getLogger(__name__) + + +class SamFunctionProvider(FunctionProvider): + """ + Fetches and returns Lambda Functions from a SAM Template. The SAM template passed to this provider is assumed + to be valid, normalized and a dictionary. + + It may or may not contain a function. + """ + + _SERVERLESS_FUNCTION = "AWS::Serverless::Function" + _LAMBDA_FUNCTION = "AWS::Lambda::Function" + _DEFAULT_CODEURI = "." + + def __init__(self, template_dict): + """ + Initialize the class with SAM template data. The SAM template passed to this provider is assumed + to be valid, normalized and a dictionary. It should be normalized by running all pre-processing + before passing to this class. The process of normalization will remove structures like ``Globals``, resolve + intrinsic functions etc. + This class does not perform any syntactic validation of the template. + + After the class is initialized, any changes to the ``template_dict`` will not be reflected in here. + You need to explicitly update the class with new template, if necessary. + + :param dict template_dict: SAM Template as a dictionary + """ + + self.template_dict = SamBaseProvider.get_template(template_dict) + self.resources = self.template_dict.get("Resources", {}) + + LOG.debug("%d resources found in the template", len(self.resources)) + + # Store a map of function name to function information for quick reference + self.functions = self._extract_functions(self.resources) + + def get(self, name): + """ + Returns the function given name or LogicalId of the function. Every SAM resource has a logicalId, but it may + also have a function name. This method searches only for LogicalID and returns the function that matches + it. + + :param string name: Name of the function + :return Function: namedtuple containing the Function information if function is found. + None, if function is not found + :raises ValueError If name is not given + """ + + if not name: + raise ValueError("Function name is required") + + return self.functions.get(name) + + def get_all(self): + """ + Yields all the Lambda functions available in the SAM Template. + + :yields Function: namedtuple containing the function information + """ + + for _, function in self.functions.items(): + yield function + + @staticmethod + def _extract_functions(resources): + """ + Extracts and returns function information from the given dictionary of SAM/CloudFormation resources. This + method supports functions defined with AWS::Serverless::Function and AWS::Lambda::Function + + :param dict resources: Dictionary of SAM/CloudFormation resources + :return dict(string : samcli.commands.local.lib.provider.Function): Dictionary of function LogicalId to the + Function configuration object + """ + + result = {} + + for name, resource in resources.items(): + + resource_type = resource.get("Type") + resource_properties = resource.get("Properties", {}) + + if resource_type == SamFunctionProvider._SERVERLESS_FUNCTION: + result[name] = SamFunctionProvider._convert_sam_function_resource(name, resource_properties) + + elif resource_type == SamFunctionProvider._LAMBDA_FUNCTION: + result[name] = SamFunctionProvider._convert_lambda_function_resource(name, resource_properties) + + # We don't care about other resource types. Just ignore them + + return result + + @staticmethod + def _convert_sam_function_resource(name, resource_properties): + """ + Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. + + :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions + declare a name + :param dict resource_properties: Properties of this resource + :return samcli.commands.local.lib.provider.Function: Function configuration + """ + + codeuri = resource_properties.get("CodeUri", SamFunctionProvider._DEFAULT_CODEURI) + + # CodeUri can be a dictionary of S3 Bucket/Key or a S3 URI, neither of which are supported + if isinstance(codeuri, dict) or \ + (isinstance(codeuri, six.string_types) and codeuri.startswith("s3://")): + + codeuri = SamFunctionProvider._DEFAULT_CODEURI + LOG.warning("Lambda function '%s' has specified S3 location for CodeUri which is unsupported. " + "Using default value of '%s' instead", name, codeuri) + + LOG.debug("Found Serverless function with name='%s' and CodeUri='%s'", name, codeuri) + + return Function( + name=name, + runtime=resource_properties.get("Runtime"), + memory=resource_properties.get("MemorySize"), + timeout=resource_properties.get("Timeout"), + handler=resource_properties.get("Handler"), + codeuri=codeuri, + environment=resource_properties.get("Environment"), + rolearn=resource_properties.get("Role") + ) + + @staticmethod + def _convert_lambda_function_resource(name, resource_properties): # pylint: disable=invalid-name + """ + Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. + + :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions + declare a name + :param dict resource_properties: Properties of this resource + :return samcli.commands.local.lib.provider.Function: Function configuration + """ + + # CodeUri is set to "." in order to get code locally from current directory. AWS::Lambda::Function's ``Code`` + # property does not support specifying a local path + codeuri = SamFunctionProvider._DEFAULT_CODEURI + + LOG.debug("Found Lambda function with name='%s' and CodeUri='%s'", name, codeuri) + + return Function( + name=name, + runtime=resource_properties.get("Runtime"), + memory=resource_properties.get("MemorySize"), + timeout=resource_properties.get("Timeout"), + handler=resource_properties.get("Handler"), + codeuri=codeuri, + environment=resource_properties.get("Environment"), + rolearn=resource_properties.get("Role") + ) diff --git a/samcli/commands/local/lib/swagger/__init__.py b/samcli/commands/local/lib/swagger/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/lib/swagger/integration_uri.py b/samcli/commands/local/lib/swagger/integration_uri.py new file mode 100644 index 0000000000..fd0c169b97 --- /dev/null +++ b/samcli/commands/local/lib/swagger/integration_uri.py @@ -0,0 +1,275 @@ +""" +Handles parsing of Swagger Integration data. This contains the arn of the Lambda function it connects to, +integration type, response template etc. +""" + +import re +import logging + +from enum import Enum +from six import string_types + +LOG = logging.getLogger(__name__) + + +class LambdaUri(object): + """ + Purely static class that helps you parse Lambda Function Integration URI ARN + """ + + _FN_SUB = "Fn::Sub" + + # From an ARN like below, extract just the Lambda Function ARN + # arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calculator:ProdAlias/invocations # NOQA + _REGEX_GET_FUNCTION_ARN = r'.*/functions/(.*)/invocations' + + # From Lamdba Function ARN like below, extract the function name. Note, the [^:] syntax is to capture only function + # name and exclude the Alias name that can optionally follow it. + # arn:aws:lambda:us-west-2:123456789012:function:Calculator:ProdAlias + _REGEX_GET_FUNCTION_NAME = r'.*:function:([^:]*)' + + # ${stageVariable.MyFunctionName} + _REGEX_STAGE_VARIABLE = r'\$\{stageVariables\..+\}' + + # Got this regex from Lambda's CreateFunction API docs + _REGEX_VALID_FUNCTION_NAME = r'([a-zA-Z0-9-_]+)' + + # Get the function name from variables within Fn::Sub. Supports ${Resource.Arn} and ${Resource.Alias} + # Ex: "arn:aws:apigateway:function/${LambdaFunction.Arn}/invocations => ${LambdaFunction.Arn} => LambdaFunction + _REGEX_SUB_FUNCTION_ARN = r'\$\{([A-Za-z0-9]+)\.(Arn|Alias)\}' + + @staticmethod + def get_function_name(integration_uri): + """ + Gets the name of the function from the Integration URI ARN. This is a best effort service which returns None + if function name could not be parsed. This can happen when the ARN is an intrinsic function which is too + complex or the ARN is not a Lambda integration. + + Parameters + ---------- + integration_uri : basestring or dict + Integration URI data extracted from Swagger dictionary. This could be a string of the ARN or an intrinsic + function that will resolve to the ARN + + Returns + ------- + basestring or None + If the function name could be parsed out of the Integration URI ARN. None, otherwise + """ + + arn = LambdaUri._get_function_arn(integration_uri) + + LOG.debug("Extracted Function ARN: %s", arn) + + return LambdaUri._get_function_name_from_arn(arn) + + @staticmethod + def _get_function_arn(uri_data): + """ + Integration URI can be expressed in various shapes and forms. This method normalizes the Integration URI ARN + and returns the Lambda Function ARN. Here are the different forms of Integration URI ARN: + + - String: + - Fully resolved ARN + - ARN with Stage Variables: + Ex: arn:aws:apigateway:ap-southeast-2:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-southeast-2:123456789012:function:${stageVariables.PostFunctionName}/invocations # NOQA + + - Dictionary: Usually contains intrinsic functions + + - Fn::Sub: + Example: + { + "Fn::Sub": + "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations" + } + + - Fn::Join: **Unsupported**. It is very hard to combine the joins into one string especially when + certain properties are resolved only at runtime. + + - Ref, Fn::GetAtt: **Unsupported**. Impossible to use these intrinsics with integration URI. CFN doesn't + support this functionality. + + Note + ~~~~ + This method supports only a very restricted subset of intrinsic functions with Swagger document. This is the + best we can do without implementing a full blown intrinsic function resolution module. + + Parameters + ---------- + uri_data : string or dict + Value of Integration URI. It can either be a string or an intrinsic function that resolves to a string + + Returns + ------- + basestring or None + Lambda Function ARN extracted from Integration URI. None, if it cannot get function Arn + """ + + if not uri_data: + return None + + if LambdaUri._is_sub_intrinsic(uri_data): + uri_data = LambdaUri._resolve_fn_sub(uri_data) + LOG.debug("Resolved Sub intrinsic function: %s", uri_data) + + # Even after processing intrinsics, this is not a string. Give up. + if not isinstance(uri_data, string_types): + LOG.debug("This Integration URI format is not supported: %s", uri_data) + return None + + # uri_data is a string. + # Let's check if it is actually a Lambda Integration URI and if so, extract the Function ARN + matches = re.match(LambdaUri._REGEX_GET_FUNCTION_ARN, uri_data) + if not matches or not matches.groups(): + LOG.debug("Ignoring Integration URI because it is not a Lambda Function integration: %s", uri_data) + return None + + groups = matches.groups() + return groups[0] # First group in the regex is the Lambda Function ARN + + @staticmethod + def _get_function_name_from_arn(function_arn): + """ + Given the integration ARN, extract the Lambda function name from the ARN. If there + are stage variables, or other unsupported formats, this function will return None. + + Parameters + ---------- + function_arn : basestring or None + Function ARN from the swagger document + + Returns + ------- + basestring or None + Function name of this integration. None if the ARN is not parsable + """ + + if not function_arn: + return None + + matches = re.match(LambdaUri._REGEX_GET_FUNCTION_NAME, function_arn) + if not matches or not matches.groups(): + LOG.debug("No Lambda function ARN defined for integration containing ARN %s", function_arn) + return None + + groups = matches.groups() + maybe_function_name = groups[0] # This regex has only one group match + + # Function name could be a real name or a stage variable or some unknown format + if re.match(LambdaUri._REGEX_STAGE_VARIABLE, maybe_function_name): + # yes, this is a stage variable + LOG.debug("Stage variables are not supported. Ignoring integration with function ARN %s", function_arn) + return None + + elif re.match(LambdaUri._REGEX_VALID_FUNCTION_NAME, maybe_function_name): + # Yes, this is a real function name + return maybe_function_name + + # Some unknown format + LOG.debug("Ignoring integration ARN. Unable to parse Function Name from function arn %s", + function_arn) + + @staticmethod + def _resolve_fn_sub(uri_data): + """ + Tries to resolve an Integration URI which contains Fn::Sub intrinsic function. This method tries to resolve + and produce a string output. + + Example: + { + "Fn::Sub": + "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations" + } + + Fn::Sub Processing: + ~~~~~~~~~~~~~~~~~~ + + If this is a Fn::Sub, resolve as following: + 1. Get the ARN String: + - If Sub is using the array syntax, then use element which is a string. + - If Sub is using string syntax, then just use the string. + 2. If there is a ${XXX.Arn} then replace it with a dummy ARN + 3. Otherwise skip it + + .. code: + Input: + { + "Fn::Sub": + "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/invocations" + } + + Output: "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:LambdaFunction/invocations" # NOQA + + Note + ~~~~ + This method supports only a very restricted subset of intrinsic functions with Swagger document. This is the + best we can do without implementing a full blown intrinsic function resolution module. + + Parameters + ---------- + uri_data : string or dict + Value of Integration URI. It can either be a string or an intrinsic function that resolves to a string + + Returns + ------- + string + Integration URI as a string, if we were able to resolve the Sub intrinsic + dict + Input data is returned unmodified if we are unable to resolve the intrinsic + """ + + # Try the short form of Fn::Sub syntax where the value is the ARN + arn = uri_data[LambdaUri._FN_SUB] + + if isinstance(arn, list): + # This is the long form of Fn::Sub syntax + # + # { + # "Fn::Sub":[ "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyARn}/invocations", + # {"MyARn": {"Ref": MyFunction"} + # ] + # } + # + # Get the ARN out of the list + arn = arn[0] + + if not isinstance(arn, string_types): + # Even after all the processing, ARN is still not a string. Probably customer provided wrong syntax + # for Fn::Sub. Let's skip this altogether + LOG.debug("Unable to resolve Fn::Sub value for integration URI: %s", uri_data) + return uri_data + + # Now finally we got the ARN string. Let us try to resolve it. + # We only support value of type ${XXX.Arn} or ${YYY.Alias}. The `.Alias` syntax is a SAM specific intrinsic + # to get ARN of Lambda Alias when using DeploymentPreference + lambda_function_arn_template = r'arn:aws:lambda:${AWS::Region}:123456789012:function:\1' + + return re.sub(LambdaUri._REGEX_SUB_FUNCTION_ARN, # Find all ${blah} patterns + # Replace with Lambda Function ARN, where function name is from pattern + lambda_function_arn_template, + arn) + + @staticmethod + def _is_sub_intrinsic(data): + """ + Is this input data a Fn::Sub intrinsic function + + Parameters + ---------- + data + Data to check + + Returns + ------- + bool + True if the data Fn::Sub intrinsic function + """ + return isinstance(data, dict) and len(data) == 1 and LambdaUri._FN_SUB in data + + +class IntegrationType(Enum): + # Mainly used with Lambda integration + aws_proxy = "aws_proxy" + + # Mainly used if someone specifies CORS response in Swagger + mock = "mock" diff --git a/samcli/commands/local/lib/swagger/parser.py b/samcli/commands/local/lib/swagger/parser.py new file mode 100644 index 0000000000..f475eb2cee --- /dev/null +++ b/samcli/commands/local/lib/swagger/parser.py @@ -0,0 +1,121 @@ +"""Handles Swagger Parsing""" + +import logging + +from samcli.commands.local.lib.provider import Api +from samcli.commands.local.lib.swagger.integration_uri import LambdaUri, IntegrationType + +LOG = logging.getLogger(__name__) + + +class SwaggerParser(object): + + _INTEGRATION_KEY = "x-amazon-apigateway-integration" + _ANY_METHOD_EXTENSION_KEY = "x-amazon-apigateway-any-method" + _BINARY_MEDIA_TYPES_EXTENSION_KEY = "x-amazon-apigateway-binary-media-types" # pylint: disable=C0103 + _ANY_METHOD = "ANY" + + def __init__(self, swagger): + """ + Constructs an Swagger Parser object + + :param dict swagger: Dictionary representation of a Swagger document + """ + self.swagger = swagger or {} + + def get_binary_media_types(self): + """ + Get the list of Binary Media Types from Swagger + + Returns + ------- + list of str + List of strings that represent the Binary Media Types for the API, defaulting to empty list is None + + """ + return self.swagger.get(self._BINARY_MEDIA_TYPES_EXTENSION_KEY) or [] + + def get_apis(self): + """ + Parses a swagger document and returns a list of APIs configured in the document. + + Swagger documents have the following structure + { + "/path1": { # path + "get": { # method + "x-amazon-apigateway-integration": { # integration + "type": "aws_proxy", + + # URI contains the Lambda function ARN that needs to be parsed to get Function Name + "uri": { + "Fn::Sub": + "arn:aws:apigateway:aws:lambda:path/2015-03-31/functions/${LambdaFunction.Arn}/..." + } + } + }, + "post": { + }, + }, + "/path2": { + ... + } + } + + Returns + ------- + list of samcli.commands.local.lib.provider.Api + List of APIs that are configured in the Swagger document + """ + + result = [] + paths_dict = self.swagger.get("paths", {}) + + binary_media_types = self.get_binary_media_types() + + for full_path, path_config in paths_dict.items(): + for method, method_config in path_config.items(): + + function_name = self._get_integration_function_name(method_config) + if not function_name: + LOG.debug("Lambda function integration not found in Swagger document at path='%s' method='%s'", + full_path, method) + continue + + if method.lower() == self._ANY_METHOD_EXTENSION_KEY: + # Convert to a more commonly used method notation + method = self._ANY_METHOD + + api = Api(path=full_path, method=method, function_name=function_name, cors=None, + binary_media_types=binary_media_types) + result.append(api) + + return result + + def _get_integration_function_name(self, method_config): + """ + Tries to parse the Lambda Function name from the Integration defined in the method configuration. + Integration configuration is defined under the special "x-amazon-apigateway-integration" key. We care only + about Lambda integrations, which are of type aws_proxy, and ignore the rest. Integration URI is complex and + hard to parse. Hence we do our best to extract function name out of integration URI. If not possible, we + return None. + + Parameters + ---------- + method_config : dict + Dictionary containing the method configuration which might contain integration settings + + Returns + ------- + string or None + Lambda function name, if possible. None, if not. + """ + if not isinstance(method_config, dict) or self._INTEGRATION_KEY not in method_config: + return None + + integration = method_config[self._INTEGRATION_KEY] + + if integration \ + and isinstance(integration, dict) \ + and integration.get("type") == IntegrationType.aws_proxy.value: + # Integration must be "aws_proxy" otherwise we don't care about it + return LambdaUri.get_function_name(integration.get("uri")) diff --git a/samcli/commands/local/lib/swagger/reader.py b/samcli/commands/local/lib/swagger/reader.py new file mode 100644 index 0000000000..e7e92f58af --- /dev/null +++ b/samcli/commands/local/lib/swagger/reader.py @@ -0,0 +1,282 @@ +""" +Read Swagger documents from variety of sources +""" + +import os +import tempfile +import logging + +import boto3 +import botocore + +from six import string_types +from six.moves.urllib.parse import urlparse, parse_qs # pylint: disable=relative-import +from samcli.yamlhelper import yaml_parse + +LOG = logging.getLogger(__name__) +_FN_TRANSFORM = "Fn::Transform" + + +def parse_aws_include_transform(data): + """ + If the input data is an AWS::Include data, then parse and return the location of the included file. + + AWS::Include transform data usually has the following format: + { + "Fn::Transform": { + "Name": "AWS::Include", + "Parameters": { + "Location": "s3://MyAmazonS3BucketName/swagger.yaml" + } + } + } + + Parameters + ---------- + data : dict + Dictionary data to parse + + Returns + ------- + str + Location of the included file, if available. None, otherwise + """ + + if not data: + return + + if _FN_TRANSFORM not in data: + return + + transform_data = data[_FN_TRANSFORM] + + name = transform_data.get("Name") + location = transform_data.get("Parameters", {}).get("Location") + if name == "AWS::Include": + LOG.debug("Successfully parsed location from AWS::Include transform: %s", location) + return location + + +class SamSwaggerReader(object): + """ + Class to read and parse Swagger document from a variety of sources. This class accepts the same data formats as + available in Serverless::Api SAM resource + """ + + def __init__(self, definition_body=None, definition_uri=None, working_dir=None): + """ + Initialize the class with swagger location + + Parameters + ---------- + definition_body : dict + Swagger document as a dictionary directly or inlined using AWS::Include transform. + + definition_uri : str or dict + Location of the Swagger file. Supports three formats: + - S3 URI Ex: ``s3://mybucket/swagger.yaml`` + - S3 URI as a dictionary Ex: ``{"Bucket": "mybucket", "Key": "swagger.yaml", "Version": "123"}`` + - Local file path either as absolute or relative path Ex: ``./swagger.yaml``. Relative paths are + resolved to with respect to the given working directory. + + working_dir : str + Path to the working directory with respect which we will resolve local relative paths + """ + self.definition_body = definition_body + self.definition_uri = definition_uri + self.working_dir = working_dir + + if not self.definition_body and not self.definition_uri: + raise ValueError("Require value for either DefinitionBody or DefinitionUri") + + def read(self): + """ + Gets the Swagger document from either of the given locations. If we fail to retrieve or parse the Swagger + file, this method will return None. + + Returns + ------- + dict: + Swagger document. None, if we cannot retrieve the document + """ + + swagger = None + + # First check if there is inline swagger + if self.definition_body: + swagger = self._read_from_definition_body() + + if not swagger and self.definition_uri: + # If not, then try to download it from the given URI + swagger = self._download_swagger(self.definition_uri) + + return swagger + + def _read_from_definition_body(self): + """ + Read the Swagger document from DefinitionBody. It could either be an inline Swagger dictionary or an + AWS::Include macro that contains location of the included Swagger. In the later case, we will download and + parse the Swagger document. + + Returns + ------- + dict + Swagger document, if we were able to parse. None, otherwise + """ + + # Let's try to parse it as AWS::Include Transform first. If not, then fall back to assuming the Swagger document + # was inclined directly into the body + location = parse_aws_include_transform(self.definition_body) + if location: + LOG.debug("Trying to download Swagger from %s", location) + return self._download_swagger(location) + + # Inline Swagger, just return the contents which should already be a dictionary + LOG.debug("Detected Inline Swagger definition") + return self.definition_body + + def _download_swagger(self, location): + """ + Download the file from given local or remote location and return it + + Parameters + ---------- + location : str or dict + Local path or S3 path to Swagger file to download. Consult the ``__init__.py`` documentation for specifics + on structure of this property. + + Returns + ------- + dict or None + Downloaded and parsed Swagger document. None, if unable to download + """ + + if not location: + return + + bucket, key, version = self._parse_s3_location(location) + if bucket and key: + LOG.debug("Downloading Swagger document from Bucket=%s, Key=%s, Version=%s", bucket, key, version) + swagger_str = self._download_from_s3(bucket, key, version) + return yaml_parse(swagger_str) + + if not isinstance(location, string_types): + # This is not a string and not a S3 Location dictionary. Probably something invalid + LOG.debug("Unable to download Swagger file. Invalid location: %s", location) + return + + # ``location`` is a string and not a S3 path. It is probably a local path. Let's resolve relative path if any + filepath = location + if self.working_dir: + # Resolve relative paths, if any, with respect to working directory + filepath = os.path.join(self.working_dir, location) + + if not os.path.exists(filepath): + LOG.debug("Unable to download Swagger file. File not found at location %s", filepath) + return + + LOG.debug("Reading Swagger document from local file at %s", filepath) + with open(filepath, "r") as fp: + return yaml_parse(fp.read()) + + @staticmethod + def _download_from_s3(bucket, key, version=None): + """ + Download a file from given S3 location, if available. + + Parameters + ---------- + bucket : str + S3 Bucket name + + key : str + S3 Bucket Key aka file path + + version : str + Optional Version ID of the file + + Returns + ------- + str + Contents of the file that was downloaded + + Raises + ------ + botocore.exceptions.ClientError if we were unable to download the file from S3 + """ + + s3 = boto3.client('s3') + + extra_args = {} + if version: + extra_args["VersionId"] = version + + with tempfile.TemporaryFile() as fp: + try: + s3.download_file( + bucket, key, fp, + ExtraArgs=extra_args) + + # go to start of file + fp.seek(0) + + # Read and return all the contents + return fp.read() + + except botocore.exceptions.ClientError: + LOG.error("Unable to download Swagger document from S3 Bucket=%s Key=%s Version=%s", + bucket, key, version) + raise + + @staticmethod + def _parse_s3_location(location): + """ + Parses the given location input as a S3 Location and returns the file's bucket, key and version as separate + values. Input can be in two different formats: + + 1. Dictionary with ``Bucket``, ``Key``, ``Version`` keys + 2. String of S3 URI in format ``s3:///?versionId=`` + + If the input is not in either of the above formats, this method will return (None, None, None) tuple for all + the values. + + Parameters + ---------- + location : str or dict + Location of the S3 file + + Returns + ------- + str + Name of the S3 Bucket. None, if bucket value was not found + str + Key of the file from S3. None, if key was not provided + str + Optional Version ID of the file. None, if version ID is not provided + """ + + bucket, key, version = None, None, None + if isinstance(location, dict): + # This is a S3 Location dictionary. Just grab the fields. It is very well possible that + # this dictionary has none of the fields we expect. Return None if the fields don't exist. + bucket, key, version = ( + location.get("Bucket"), + location.get("Key"), + location.get("Version") + ) + + elif isinstance(location, string_types) and location.startswith("s3://"): + # This is a S3 URI. Parse it using a standard URI parser to extract the components + + parsed = urlparse(location) + query = parse_qs(parsed.query) + + bucket = parsed.netloc + key = parsed.path.lstrip('/') # Leading '/' messes with S3 APIs. Remove it. + + # If there is a query string that has a single versionId field, + # set the object version and return + if query and 'versionId' in query and len(query['versionId']) == 1: + version = query['versionId'][0] + + return bucket, key, version diff --git a/samcli/commands/local/local.py b/samcli/commands/local/local.py new file mode 100644 index 0000000000..ce54fd7d21 --- /dev/null +++ b/samcli/commands/local/local.py @@ -0,0 +1,24 @@ +""" +Command group for "local" suite for commands. It provides common CLI arguments, template parsing capabilities, +setting up stdin/stdout etc +""" + +import click + +from .invoke.cli import cli as invoke_cli +from .start_api.cli import cli as start_api_cli +from .generate_event.cli import cli as generate_event_cli + + +@click.group() +def cli(): + """ + Run your Serverless application locally for quick development & testing + """ + pass # pragma: no cover + + +# Add individual commands under this group +cli.add_command(invoke_cli) +cli.add_command(start_api_cli) +cli.add_command(generate_event_cli) diff --git a/samcli/commands/local/start_api/__init__.py b/samcli/commands/local/start_api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/local/start_api/cli.py b/samcli/commands/local/start_api/cli.py new file mode 100644 index 0000000000..2cb4e88fe3 --- /dev/null +++ b/samcli/commands/local/start_api/cli.py @@ -0,0 +1,91 @@ +""" +CLI command for "local start-api" command +""" + +import logging +import click + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.cli_common.options import invoke_common_options +from samcli.commands.local.cli_common.invoke_context import InvokeContext +from samcli.commands.local.lib.exceptions import NoApisDefined +from samcli.commands.local.cli_common.user_exceptions import UserException +from samcli.commands.local.lib.local_api_service import LocalApiService +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + +LOG = logging.getLogger(__name__) + +HELP_TEXT = """ +Allows you to run your Serverless application locally for quick development & testing. + When run in a directory that contains your Serverless functions and your AWS SAM template, it will create a local HTTP + server hosting all of your functions. When accessed (via browser, cli etc), it will launch a Docker container locally + to invoke the function. It will read the CodeUri property of AWS::Serverless::Function resource to find the path in + your file system containing the Lambda Function code. This could be the project's root directory for interpreted + languages like Node & Python, or a build directory that stores your compiled artifacts or a JAR file. If you are using + a interpreted language, local changes will be available immediately in Docker container on every invoke. For more + compiled languages or projects requiring complex packing support, we recommended you run your own building solution +and point SAM to the directory or file containing build artifacts. +""" + + +@click.command("start-api", help=HELP_TEXT, short_help="Runs your APIs locally") +@click.option("--host", + default="127.0.0.1", + help="Local hostname or IP address to bind to (default: '127.0.0.1')") +@click.option("--port", "-p", + default=3000, + help="Local port number to listen on (default: '3000')") +@click.option("--static-dir", "-s", + default="public", + help="Any static assets (e.g. CSS/Javascript/HTML) files located in this directory " + "will be presented at /") +@invoke_common_options +@cli_framework_options +@pass_context +def cli(ctx, + # start-api Specific Options + host, port, static_dir, + + # Common Options for Lambda Invoke + template, env_vars, debug_port, debug_args, docker_volume_basedir, + docker_network, log_file, skip_pull_image, profile + ): + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, host, port, static_dir, template, env_vars, debug_port, debug_args, docker_volume_basedir, + docker_network, log_file, skip_pull_image, profile) # pragma: no cover + + +def do_cli(ctx, host, port, static_dir, template, env_vars, debug_port, debug_args, # pylint: disable=R0914 + docker_volume_basedir, docker_network, log_file, skip_pull_image, profile): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + + LOG.debug("local start-api command is called") + + # Pass all inputs to setup necessary context to invoke function locally. + # Handler exception raised by the processor for invalid args and print errors + + try: + with InvokeContext(template_file=template, + function_identifier=None, # Don't scope to one particular function + env_vars_file=env_vars, + debug_port=debug_port, + debug_args=debug_args, + docker_volume_basedir=docker_volume_basedir, + docker_network=docker_network, + log_file=log_file, + skip_pull_image=skip_pull_image, + aws_profile=profile) as invoke_context: + + service = LocalApiService(lambda_invoke_context=invoke_context, + port=port, + host=host, + static_dir=static_dir) + service.start() + + except NoApisDefined: + raise UserException("Template does not have any APIs connected to Lambda functions") + except InvalidSamDocumentException as ex: + raise UserException(str(ex)) diff --git a/samcli/commands/package/__init__.py b/samcli/commands/package/__init__.py new file mode 100644 index 0000000000..92ce038531 --- /dev/null +++ b/samcli/commands/package/__init__.py @@ -0,0 +1,26 @@ +""" +CLI command for "package" command +""" + +import click + +from samcli.cli.main import pass_context, common_options +from samcli.lib.samlib.cloudformation_command import execute_command + + +SHORT_HELP = "Package an AWS SAM application. This is an alias for 'aws cloudformation package'." + + +@click.command("package", short_help=SHORT_HELP, context_settings={"ignore_unknown_options": True}) +@click.argument("args", nargs=-1, type=click.UNPROCESSED) +@common_options +@pass_context +def cli(ctx, args): + + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(args) # pragma: no cover + + +def do_cli(args): + execute_command("package", args) diff --git a/samcli/commands/validate/__init__.py b/samcli/commands/validate/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/validate/lib/__init__.py b/samcli/commands/validate/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/commands/validate/lib/exceptions.py b/samcli/commands/validate/lib/exceptions.py new file mode 100644 index 0000000000..84f6210e3b --- /dev/null +++ b/samcli/commands/validate/lib/exceptions.py @@ -0,0 +1,10 @@ +""" +Custom Exceptions for 'sam validate' commands +""" + + +class InvalidSamDocumentException(Exception): + """ + Exception for Invalid Sam Documents + """ + pass diff --git a/samcli/commands/validate/lib/sam_template_validator.py b/samcli/commands/validate/lib/sam_template_validator.py new file mode 100644 index 0000000000..fbda164032 --- /dev/null +++ b/samcli/commands/validate/lib/sam_template_validator.py @@ -0,0 +1,127 @@ +""" +Library for Validating Sam Templates +""" +from samtranslator.public.exceptions import InvalidDocumentException +from samtranslator.parser.parser import Parser +from samtranslator.translator.translator import Translator +import six + +from .exceptions import InvalidSamDocumentException + + +class SamTemplateValidator(object): + + def __init__(self, sam_template, managed_policy_loader): + """ + Construct a SamTemplateValidator + + Design Details: + + managed_policy_loader is injected into the `__init__` to allow future expansion + and overriding capabilities. A typically pattern is to pass the name of the class into + the `__init__` as keyword args. As long as the class 'conforms' to the same 'interface'. + This allows the class to be changed by the client and allowing customization of the class being + initialized. Something I had in mind would be allowing a template to be run and checked + 'offline' (not needing aws creds). To make this an easier transition in the future, we ingest + the ManagedPolicyLoader class. + + Parameters + ---------- + sam_template dict + Dictionary representing a SAM Template + managed_policy_loader ManagedPolicyLoader + Sam ManagedPolicyLoader + """ + self.sam_template = sam_template + self.managed_policy_loader = managed_policy_loader + + self.sam_parser = Parser() + + def is_valid(self): + """ + Runs the SAM Translator to determine if the template provided is valid. This is similar to running a + ChangeSet in CloudFormation for a SAM Template + + Raises + ------- + InvalidSamDocumentException + If the template is not valid, an InvalidSamDocumentException is raised + """ + managed_policy_map = self.managed_policy_loader.load() + + sam_translator = Translator(managed_policy_map=managed_policy_map, + sam_parser=self.sam_parser, + plugins=[]) + + self._replace_local_codeuri() + + try: + sam_translator.translate(sam_template=self.sam_template, + parameter_values={}) + except InvalidDocumentException as e: + raise InvalidSamDocumentException( + reduce(lambda message, error: message + ' ' + error.message, e.causes, e.message)) + + def _replace_local_codeuri(self): + """ + Replaces the CodeUri in AWS::Serverless::Function and DefinitionUri in AWS::Serverless::Api to a fake + S3 Uri. This is to support running the SAM Translator with valid values for these fields. If this in not done, + the template is invalid in the eyes of SAM Translator (the translator does not support local paths) + """ + + all_resources = self.sam_template.get("Resources", {}) + + for _, resource in all_resources.items(): + + resource_type = resource.get("Type") + resource_dict = resource.get("Properties") + + if resource_type == "AWS::Serverless::Function": + + SamTemplateValidator._update_to_s3_uri("CodeUri", resource_dict) + + if resource_type == "AWS::Serverless::Api": + + SamTemplateValidator._update_to_s3_uri("DefinitionUri", resource_dict) + + @staticmethod + def is_s3_uri(uri): + """ + Checks the uri and determines if it is a valid S3 Uri + + Parameters + ---------- + uri str, required + Uri to check + + Returns + ------- + bool + Returns True if the uri given is an S3 uri, otherwise False + + """ + return isinstance(uri, six.string_types) and uri.startswith("s3://") + + @staticmethod + def _update_to_s3_uri(property_key, resource_property_dict, s3_uri_value="s3://bucket/value"): + """ + Updates the 'property_key' in the 'resource_property_dict' to the value of 's3_uri_value' + + Note: The function will mutate the resource_property_dict that is pass in + + Parameters + ---------- + property_key str, required + Key in the resource_property_dict + resource_property_dict dict, required + Property dictionary of a Resource in the template to replace + s3_uri_value str, optional + Value to update the value of the property_key to + """ + uri_property = resource_property_dict.get(property_key, ".") + + # ignore if dict or already an S3 Uri + if isinstance(uri_property, dict) or SamTemplateValidator.is_s3_uri(uri_property): + return + + resource_property_dict[property_key] = s3_uri_value diff --git a/samcli/commands/validate/validate.py b/samcli/commands/validate/validate.py new file mode 100644 index 0000000000..6b3c4aecc1 --- /dev/null +++ b/samcli/commands/validate/validate.py @@ -0,0 +1,65 @@ +""" +CLI Command for Validating a SAM Template +""" +import os + +import boto3 +import click +from samtranslator.translator.managed_policy_translator import ManagedPolicyLoader + + +from samcli.cli.main import pass_context, common_options as cli_framework_options +from samcli.commands.local.cli_common.options import template_common_option as template_option +from samcli.commands.local.cli_common.user_exceptions import InvalidSamTemplateException, SamTemplateNotFoundException +from samcli.yamlhelper import yaml_parse +from .lib.exceptions import InvalidSamDocumentException +from .lib.sam_template_validator import SamTemplateValidator + + +@click.command("validate", + short_help="Validate an AWS SAM template.") +@template_option +@cli_framework_options +@pass_context +def cli(ctx, template): + + # All logic must be implemented in the ``do_cli`` method. This helps with easy unit testing + + do_cli(ctx, template) # pragma: no cover + + +def do_cli(ctx, template): + """ + Implementation of the ``cli`` method, just separated out for unit testing purposes + """ + + sam_template = _read_sam_file(template) + + iam_client = boto3.client('iam') + validator = SamTemplateValidator(sam_template, ManagedPolicyLoader(iam_client)) + + try: + validator.is_valid() + except InvalidSamDocumentException as e: + click.secho("Template provided at '{}' was invalid SAM Template.".format(template), bg='red') + raise InvalidSamTemplateException(e.message) + + click.secho("{} is a valid SAM Template".format(template), fg='green') + + +def _read_sam_file(template): + """ + Reads the file (json and yaml supported) provided and returns the dictionary representation of the file. + + :param str template: Path to the template file + :return dict: Dictionary representing the SAM Template + :raises: SamTemplateNotFoundException when the template file does not exist + """ + if not os.path.exists(template): + click.secho("SAM Template Not Found", bg='red') + raise SamTemplateNotFoundException("Template at {} is not found".format(template)) + + with click.open_file(template, 'r') as sam_template: + sam_template = yaml_parse(sam_template.read()) + + return sam_template diff --git a/samcli/lib/__init__.py b/samcli/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/lib/samlib/__init__.py b/samcli/lib/samlib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/lib/samlib/cloudformation_command.py b/samcli/lib/samlib/cloudformation_command.py new file mode 100644 index 0000000000..b9af364997 --- /dev/null +++ b/samcli/lib/samlib/cloudformation_command.py @@ -0,0 +1,22 @@ +""" +Utility to call cloudformation command with args +""" + +import logging +import platform +import subprocess +import sys + +LOG = logging.getLogger(__name__) + + +def execute_command(command, args): + LOG.debug("%s command is called", command) + try: + aws_cmd = 'aws' if platform.system().lower() != 'windows' else 'aws.cmd' + subprocess.check_call([aws_cmd, 'cloudformation', command] + list(args)) + LOG.debug("%s command successful", command) + except subprocess.CalledProcessError as e: + # Underlying aws command will print the exception to the user + LOG.debug("Exception: %s", e) + sys.exit(e.returncode) diff --git a/samcli/lib/samlib/default_managed_policies.json b/samcli/lib/samlib/default_managed_policies.json new file mode 100644 index 0000000000..011382b900 --- /dev/null +++ b/samcli/lib/samlib/default_managed_policies.json @@ -0,0 +1,372 @@ +{ + "SecurityAudit": "arn:aws:iam::aws:policy/SecurityAudit", + "AWSElasticBeanstalkMulticontainerDocker": "arn:aws:iam::aws:policy/AWSElasticBeanstalkMulticontainerDocker", + "AWSGreengrassResourceAccessRolePolicy": "arn:aws:iam::aws:policy/service-role/AWSGreengrassResourceAccessRolePolicy", + "AmazonS3ReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess", + "AmazonEC2RoleforDataPipelineRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforDataPipelineRole", + "AWSElasticBeanstalkService": "arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkService", + "AWSQuickSightIoTAnalyticsAccess": "arn:aws:iam::aws:policy/AWSQuickSightIoTAnalyticsAccess", + "AWSElasticBeanstalkCustomPlatformforEC2Role": "arn:aws:iam::aws:policy/AWSElasticBeanstalkCustomPlatformforEC2Role", + "AWSStepFunctionsConsoleFullAccess": "arn:aws:iam::aws:policy/AWSStepFunctionsConsoleFullAccess", + "AWSCloudTrailFullAccess": "arn:aws:iam::aws:policy/AWSCloudTrailFullAccess", + "NetworkAdministrator": "arn:aws:iam::aws:policy/job-function/NetworkAdministrator", + "AWSCodePipelineApproverAccess": "arn:aws:iam::aws:policy/AWSCodePipelineApproverAccess", + "AWSDirectConnectReadOnlyAccess": "arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess", + "AmazonMobileAnalyticsFinancialReportAccess": "arn:aws:iam::aws:policy/AmazonMobileAnalyticsFinancialReportAccess", + "AWSDeepLensLambdaFunctionAccessPolicy": "arn:aws:iam::aws:policy/AWSDeepLensLambdaFunctionAccessPolicy", + "AutoScalingFullAccess": "arn:aws:iam::aws:policy/AutoScalingFullAccess", + "AmazonLexRunBotsOnly": "arn:aws:iam::aws:policy/AmazonLexRunBotsOnly", + "AmazonEC2RoleforAWSCodeDeploy": "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforAWSCodeDeploy", + "AWSLambdaReplicator": "arn:aws:iam::aws:policy/aws-service-role/AWSLambdaReplicator", + "CloudWatchEventsReadOnlyAccess": "arn:aws:iam::aws:policy/CloudWatchEventsReadOnlyAccess", + "CloudWatchActionsEC2Access": "arn:aws:iam::aws:policy/CloudWatchActionsEC2Access", + "ViewOnlyAccess": "arn:aws:iam::aws:policy/job-function/ViewOnlyAccess", + "AmazonECSTaskExecutionRolePolicy": "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy", + "AmazonMacieServiceRole": "arn:aws:iam::aws:policy/service-role/AmazonMacieServiceRole", + "ResourceGroupsandTagEditorFullAccess": "arn:aws:iam::aws:policy/ResourceGroupsandTagEditorFullAccess", + "AmazonESReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonESReadOnlyAccess", + "IAMReadOnlyAccess": "arn:aws:iam::aws:policy/IAMReadOnlyAccess", + "AWSCloud9User": "arn:aws:iam::aws:policy/AWSCloud9User", + "AmazonMachineLearningRealTimePredictionOnlyAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningRealTimePredictionOnlyAccess", + "AWSCloud9ServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSCloud9ServiceRolePolicy", + "AmazonMachineLearningCreateOnlyAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningCreateOnlyAccess", + "AmazonRoute53AutoNamingFullAccess": "arn:aws:iam::aws:policy/AmazonRoute53AutoNamingFullAccess", + "AWSXrayFullAccess": "arn:aws:iam::aws:policy/AWSXrayFullAccess", + "AWSElasticBeanstalkWebTier": "arn:aws:iam::aws:policy/AWSElasticBeanstalkWebTier", + "AWSConfigRoleForOrganizations": "arn:aws:iam::aws:policy/service-role/AWSConfigRoleForOrganizations", + "AmazonRDSFullAccess": "arn:aws:iam::aws:policy/AmazonRDSFullAccess", + "AWSIoTLogging": "arn:aws:iam::aws:policy/service-role/AWSIoTLogging", + "AWSConfigRole": "arn:aws:iam::aws:policy/service-role/AWSConfigRole", + "AWSStorageGatewayReadOnlyAccess": "arn:aws:iam::aws:policy/AWSStorageGatewayReadOnlyAccess", + "AWSCodeDeployDeployerAccess": "arn:aws:iam::aws:policy/AWSCodeDeployDeployerAccess", + "AmazonWorkMailReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonWorkMailReadOnlyAccess", + "AmazonSNSRole": "arn:aws:iam::aws:policy/service-role/AmazonSNSRole", + "AWSImportExportFullAccess": "arn:aws:iam::aws:policy/AWSImportExportFullAccess", + "AmazonAppStreamServiceAccess": "arn:aws:iam::aws:policy/service-role/AmazonAppStreamServiceAccess", + "AWSGlueConsoleFullAccess": "arn:aws:iam::aws:policy/AWSGlueConsoleFullAccess", + "ComprehendReadOnly": "arn:aws:iam::aws:policy/ComprehendReadOnly", + "AmazonMachineLearningBatchPredictionsAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningBatchPredictionsAccess", + "AWSEnhancedClassicNetworkingMangementPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSEnhancedClassicNetworkingMangementPolicy", + "SecretsManagerReadWrite": "arn:aws:iam::aws:policy/SecretsManagerReadWrite", + "AmazonMQFullAccess": "arn:aws:iam::aws:policy/AmazonMQFullAccess", + "AWSIoTConfigReadOnlyAccess": "arn:aws:iam::aws:policy/AWSIoTConfigReadOnlyAccess", + "AWSElasticLoadBalancingClassicServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSElasticLoadBalancingClassicServiceRolePolicy", + "SystemAdministrator": "arn:aws:iam::aws:policy/job-function/SystemAdministrator", + "AmazonEC2ContainerRegistryFullAccess": "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryFullAccess", + "CloudWatchEventsInvocationAccess": "arn:aws:iam::aws:policy/service-role/CloudWatchEventsInvocationAccess", + "AmazonECSServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonECSServiceRolePolicy", + "AmazonCognitoPowerUser": "arn:aws:iam::aws:policy/AmazonCognitoPowerUser", + "ElastiCacheServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/ElastiCacheServiceRolePolicy", + "AWSCloudFormationReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCloudFormationReadOnlyAccess", + "ApplicationAutoScalingForAmazonAppStreamAccess": "arn:aws:iam::aws:policy/service-role/ApplicationAutoScalingForAmazonAppStreamAccess", + "AWSCloud9EnvironmentMember": "arn:aws:iam::aws:policy/AWSCloud9EnvironmentMember", + "AmazonLexFullAccess": "arn:aws:iam::aws:policy/AmazonLexFullAccess", + "AmazonElastiCacheFullAccess": "arn:aws:iam::aws:policy/AmazonElastiCacheFullAccess", + "AWSBatchServiceRole": "arn:aws:iam::aws:policy/service-role/AWSBatchServiceRole", + "AmazonKinesisAnalyticsFullAccess": "arn:aws:iam::aws:policy/AmazonKinesisAnalyticsFullAccess", + "AWSApplicationAutoscalingDynamoDBTablePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingDynamoDBTablePolicy", + "AmazonElasticFileSystemFullAccess": "arn:aws:iam::aws:policy/AmazonElasticFileSystemFullAccess", + "AmazonEC2ContainerServiceAutoscaleRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceAutoscaleRole", + "AWSCodeDeployReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCodeDeployReadOnlyAccess", + "AWSHealthFullAccess": "arn:aws:iam::aws:policy/AWSHealthFullAccess", + "AmazonDynamoDBReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess", + "AmazonVPCFullAccess": "arn:aws:iam::aws:policy/AmazonVPCFullAccess", + "AmazonEC2RoleforSSM": "arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM", + "AmazonMobileAnalyticsNon-financialReportAccess": "arn:aws:iam::aws:policy/AmazonMobileAnalyticsNon-financialReportAccess", + "AmazonSageMakerReadOnly": "arn:aws:iam::aws:policy/AmazonSageMakerReadOnly", + "AWSCloudHSMReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCloudHSMReadOnlyAccess", + "AmazonCognitoDeveloperAuthenticatedIdentities": "arn:aws:iam::aws:policy/AmazonCognitoDeveloperAuthenticatedIdentities", + "AmazonRDSEnhancedMonitoringRole": "arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole", + "AWSCodeBuildReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCodeBuildReadOnlyAccess", + "AWSDirectoryServiceReadOnlyAccess": "arn:aws:iam::aws:policy/AWSDirectoryServiceReadOnlyAccess", + "AmazonCloudDirectoryReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonCloudDirectoryReadOnlyAccess", + "CloudSearchReadOnlyAccess": "arn:aws:iam::aws:policy/CloudSearchReadOnlyAccess", + "AWSElementalMediaStoreReadOnly": "arn:aws:iam::aws:policy/AWSElementalMediaStoreReadOnly", + "LexChannelPolicy": "arn:aws:iam::aws:policy/aws-service-role/LexChannelPolicy", + "AWSSSOServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSSSOServiceRolePolicy", + "AWSConfigRulesExecutionRole": "arn:aws:iam::aws:policy/service-role/AWSConfigRulesExecutionRole", + "AmazonChimeUserManagement": "arn:aws:iam::aws:policy/AmazonChimeUserManagement", + "IAMFullAccess": "arn:aws:iam::aws:policy/IAMFullAccess", + "IAMUserChangePassword": "arn:aws:iam::aws:policy/IAMUserChangePassword", + "AWSKeyManagementServicePowerUser": "arn:aws:iam::aws:policy/AWSKeyManagementServicePowerUser", + "AWSMobileHub_FullAccess": "arn:aws:iam::aws:policy/AWSMobileHub_FullAccess", + "AWSLambdaReplicatorInternal": "arn:aws:iam::aws:policy/aws-service-role/AWSLambdaReplicatorInternal", + "AWSOpsWorksCMServiceRole": "arn:aws:iam::aws:policy/service-role/AWSOpsWorksCMServiceRole", + "AmazonZocaloFullAccess": "arn:aws:iam::aws:policy/AmazonZocaloFullAccess", + "AWSCertificateManagerFullAccess": "arn:aws:iam::aws:policy/AWSCertificateManagerFullAccess", + "AmazonEC2ReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess", + "AmazonDynamoDBFullAccess": "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess", + "DAXServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/DAXServiceRolePolicy", + "AWSApplicationAutoscalingSageMakerEndpointPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingSageMakerEndpointPolicy", + "AmazonWorkSpacesApplicationManagerAdminAccess": "arn:aws:iam::aws:policy/AmazonWorkSpacesApplicationManagerAdminAccess", + "AmazonElasticMapReduceforEC2Role": "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceforEC2Role", + "AmazonSNSReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonSNSReadOnlyAccess", + "CloudHSMServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/CloudHSMServiceRolePolicy", + "AWSApplicationAutoscalingAppStreamFleetPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingAppStreamFleetPolicy", + "IAMUserSSHKeys": "arn:aws:iam::aws:policy/IAMUserSSHKeys", + "AmazonVPCCrossAccountNetworkInterfaceOperations": "arn:aws:iam::aws:policy/AmazonVPCCrossAccountNetworkInterfaceOperations", + "AmazonFreeRTOSFullAccess": "arn:aws:iam::aws:policy/AmazonFreeRTOSFullAccess", + "AmazonInspectorReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonInspectorReadOnlyAccess", + "AmazonEMRCleanupPolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonEMRCleanupPolicy", + "IAMSelfManageServiceSpecificCredentials": "arn:aws:iam::aws:policy/IAMSelfManageServiceSpecificCredentials", + "AWSQuicksightAthenaAccess": "arn:aws:iam::aws:policy/service-role/AWSQuicksightAthenaAccess", + "AmazonEC2ContainerServiceRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole", + "AmazonMechanicalTurkReadOnly": "arn:aws:iam::aws:policy/AmazonMechanicalTurkReadOnly", + "AmazonEC2ReportsAccess": "arn:aws:iam::aws:policy/AmazonEC2ReportsAccess", + "AWSElementalMediaStoreFullAccess": "arn:aws:iam::aws:policy/AWSElementalMediaStoreFullAccess", + "AWSBatchServiceEventTargetRole": "arn:aws:iam::aws:policy/service-role/AWSBatchServiceEventTargetRole", + "AWSCodeDeployFullAccess": "arn:aws:iam::aws:policy/AWSCodeDeployFullAccess", + "CloudWatchAgentServerPolicy": "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy", + "AWSApplicationAutoscalingRDSClusterPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingRDSClusterPolicy", + "AmazonVPCReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonVPCReadOnlyAccess", + "AmazonRoute53DomainsReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRoute53DomainsReadOnlyAccess", + "AWSElasticBeanstalkReadOnlyAccess": "arn:aws:iam::aws:policy/AWSElasticBeanstalkReadOnlyAccess", + "AWSStepFunctionsReadOnlyAccess": "arn:aws:iam::aws:policy/AWSStepFunctionsReadOnlyAccess", + "AWSSupportAccess": "arn:aws:iam::aws:policy/AWSSupportAccess", + "GreengrassOTAUpdateArtifactAccess": "arn:aws:iam::aws:policy/service-role/GreengrassOTAUpdateArtifactAccess", + "AmazonEC2ContainerServiceforEC2Role": "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role", + "AmazonKinesisVideoStreamsReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonKinesisVideoStreamsReadOnlyAccess", + "AWSMarketplaceFullAccess": "arn:aws:iam::aws:policy/AWSMarketplaceFullAccess", + "AWSOpsWorksCloudWatchLogs": "arn:aws:iam::aws:policy/AWSOpsWorksCloudWatchLogs", + "AWSStepFunctionsFullAccess": "arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess", + "AmazonSQSReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonSQSReadOnlyAccess", + "AmazonElasticMapReduceRole": "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceRole", + "AWSOpsWorksCMInstanceProfileRole": "arn:aws:iam::aws:policy/AWSOpsWorksCMInstanceProfileRole", + "AWSMarketplaceRead-only": "arn:aws:iam::aws:policy/AWSMarketplaceRead-only", + "AWSWAFFullAccess": "arn:aws:iam::aws:policy/AWSWAFFullAccess", + "AmazonSQSFullAccess": "arn:aws:iam::aws:policy/AmazonSQSFullAccess", + "AmazonMobileAnalyticsFullAccess": "arn:aws:iam::aws:policy/AmazonMobileAnalyticsFullAccess", + "AutoScalingConsoleFullAccess": "arn:aws:iam::aws:policy/AutoScalingConsoleFullAccess", + "QuickSightAccessForS3StorageManagementAnalyticsReadOnly": "arn:aws:iam::aws:policy/service-role/QuickSightAccessForS3StorageManagementAnalyticsReadOnly", + "AmazonESCognitoAccess": "arn:aws:iam::aws:policy/AmazonESCognitoAccess", + "AWSAppSyncSchemaAuthor": "arn:aws:iam::aws:policy/AWSAppSyncSchemaAuthor", + "AWSIoTConfigAccess": "arn:aws:iam::aws:policy/AWSIoTConfigAccess", + "AWSAppSyncPushToCloudWatchLogs": "arn:aws:iam::aws:policy/service-role/AWSAppSyncPushToCloudWatchLogs", + "AWSDataPipeline_PowerUser": "arn:aws:iam::aws:policy/AWSDataPipeline_PowerUser", + "AWSStorageGatewayFullAccess": "arn:aws:iam::aws:policy/AWSStorageGatewayFullAccess", + "AmazonElasticTranscoderReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonElasticTranscoderReadOnlyAccess", + "AmazonSSMServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonSSMServiceRolePolicy", + "AWSMigrationHubSMSAccess": "arn:aws:iam::aws:policy/service-role/AWSMigrationHubSMSAccess", + "AWSCertificateManagerReadOnly": "arn:aws:iam::aws:policy/AWSCertificateManagerReadOnly", + "AWSLambdaKinesisExecutionRole": "arn:aws:iam::aws:policy/service-role/AWSLambdaKinesisExecutionRole", + "AWSDeepLensServiceRolePolicy": "arn:aws:iam::aws:policy/service-role/AWSDeepLensServiceRolePolicy", + "AWSApplicationDiscoveryAgentAccess": "arn:aws:iam::aws:policy/AWSApplicationDiscoveryAgentAccess", + "AWSServiceCatalogAdminFullAccess": "arn:aws:iam::aws:policy/AWSServiceCatalogAdminFullAccess", + "AdministratorAccess": "arn:aws:iam::aws:policy/AdministratorAccess", + "CloudSearchFullAccess": "arn:aws:iam::aws:policy/CloudSearchFullAccess", + "AmazonInspectorServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonInspectorServiceRolePolicy", + "AmazonGlacierFullAccess": "arn:aws:iam::aws:policy/AmazonGlacierFullAccess", + "AWSConnector": "arn:aws:iam::aws:policy/AWSConnector", + "FMSServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/FMSServiceRolePolicy", + "AWSXrayWriteOnlyAccess": "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess", + "AmazonMachineLearningRoleforRedshiftDataSource": "arn:aws:iam::aws:policy/service-role/AmazonMachineLearningRoleforRedshiftDataSource", + "AmazonSESReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonSESReadOnlyAccess", + "AmazonAppStreamFullAccess": "arn:aws:iam::aws:policy/AmazonAppStreamFullAccess", + "AWSMobileHub_ReadOnly": "arn:aws:iam::aws:policy/AWSMobileHub_ReadOnly", + "AWSEC2FleetServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSEC2FleetServiceRolePolicy", + "AWSElementalMediaPackageFullAccess": "arn:aws:iam::aws:policy/AWSElementalMediaPackageFullAccess", + "AWSQuickSightListIAM": "arn:aws:iam::aws:policy/service-role/AWSQuickSightListIAM", + "AmazonAPIGatewayPushToCloudWatchLogs": "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs", + "AmazonDynamoDBFullAccesswithDataPipeline": "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccesswithDataPipeline", + "AmazonAppStreamReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonAppStreamReadOnlyAccess", + "AWSGlueServiceRole": "arn:aws:iam::aws:policy/service-role/AWSGlueServiceRole", + "AWSServiceCatalogEndUserFullAccess": "arn:aws:iam::aws:policy/AWSServiceCatalogEndUserFullAccess", + "AmazonElasticTranscoderRole": "arn:aws:iam::aws:policy/service-role/AmazonElasticTranscoderRole", + "AWSMarketplaceGetEntitlements": "arn:aws:iam::aws:policy/AWSMarketplaceGetEntitlements", + "SupportUser": "arn:aws:iam::aws:policy/job-function/SupportUser", + "AWSIoTOTAUpdate": "arn:aws:iam::aws:policy/service-role/AWSIoTOTAUpdate", + "AutoScalingServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AutoScalingServiceRolePolicy", + "AmazonZocaloReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonZocaloReadOnlyAccess", + "AmazonPollyFullAccess": "arn:aws:iam::aws:policy/AmazonPollyFullAccess", + "AWSQuickSightDescribeRDS": "arn:aws:iam::aws:policy/service-role/AWSQuickSightDescribeRDS", + "AWSCloudHSMRole": "arn:aws:iam::aws:policy/service-role/AWSCloudHSMRole", + "AWSGlueServiceNotebookRole": "arn:aws:iam::aws:policy/service-role/AWSGlueServiceNotebookRole", + "CloudWatchEventsServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/CloudWatchEventsServiceRolePolicy", + "AmazonRedshiftReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRedshiftReadOnlyAccess", + "AWSLambdaInvocation-DynamoDB": "arn:aws:iam::aws:policy/AWSLambdaInvocation-DynamoDB", + "AmazonRekognitionServiceRole": "arn:aws:iam::aws:policy/service-role/AmazonRekognitionServiceRole", + "AWSQuickSightDescribeRedshift": "arn:aws:iam::aws:policy/service-role/AWSQuickSightDescribeRedshift", + "AmazonAPIGatewayAdministrator": "arn:aws:iam::aws:policy/AmazonAPIGatewayAdministrator", + "AWSCodeBuildDeveloperAccess": "arn:aws:iam::aws:policy/AWSCodeBuildDeveloperAccess", + "AmazonEC2FullAccess": "arn:aws:iam::aws:policy/AmazonEC2FullAccess", + "AWSCodeCommitPowerUser": "arn:aws:iam::aws:policy/AWSCodeCommitPowerUser", + "AmazonRoute53AutoNamingReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRoute53AutoNamingReadOnlyAccess", + "AWSCodeDeployRole": "arn:aws:iam::aws:policy/service-role/AWSCodeDeployRole", + "ServerMigrationConnector": "arn:aws:iam::aws:policy/ServerMigrationConnector", + "CloudWatchLogsReadOnlyAccess": "arn:aws:iam::aws:policy/CloudWatchLogsReadOnlyAccess", + "PowerUserAccess": "arn:aws:iam::aws:policy/PowerUserAccess", + "AWSMarketplaceManageSubscriptions": "arn:aws:iam::aws:policy/AWSMarketplaceManageSubscriptions", + "AmazonRDSReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess", + "ServiceCatalogEndUserAccess": "arn:aws:iam::aws:policy/ServiceCatalogEndUserAccess", + "AWSOpsWorksRole": "arn:aws:iam::aws:policy/service-role/AWSOpsWorksRole", + "AmazonSSMReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess", + "AWSCodePipelineCustomActionAccess": "arn:aws:iam::aws:policy/AWSCodePipelineCustomActionAccess", + "AmazonRoute53AutoNamingRegistrantAccess": "arn:aws:iam::aws:policy/AmazonRoute53AutoNamingRegistrantAccess", + "AmazonMachineLearningReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningReadOnlyAccess", + "AmazonESFullAccess": "arn:aws:iam::aws:policy/AmazonESFullAccess", + "AWSConfigUserAccess": "arn:aws:iam::aws:policy/AWSConfigUserAccess", + "DatabaseAdministrator": "arn:aws:iam::aws:policy/job-function/DatabaseAdministrator", + "CloudWatchLogsFullAccess": "arn:aws:iam::aws:policy/CloudWatchLogsFullAccess", + "AmazonSSMAutomationRole": "arn:aws:iam::aws:policy/service-role/AmazonSSMAutomationRole", + "AmazonMachineLearningFullAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningFullAccess", + "AmazonSageMakerFullAccess": "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess", + "ServerMigrationServiceRole": "arn:aws:iam::aws:policy/service-role/ServerMigrationServiceRole", + "AWSLambdaVPCAccessExecutionRole": "arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole", + "AmazonSESFullAccess": "arn:aws:iam::aws:policy/AmazonSESFullAccess", + "AmazonTranscribeReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonTranscribeReadOnlyAccess", + "AmazonKinesisAnalyticsReadOnly": "arn:aws:iam::aws:policy/AmazonKinesisAnalyticsReadOnly", + "AmazonRekognitionReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRekognitionReadOnlyAccess", + "AmazonInspectorFullAccess": "arn:aws:iam::aws:policy/AmazonInspectorFullAccess", + "AmazonElasticMapReduceforAutoScalingRole": "arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceforAutoScalingRole", + "AWSImportExportReadOnlyAccess": "arn:aws:iam::aws:policy/AWSImportExportReadOnlyAccess", + "AmazonMQReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonMQReadOnlyAccess", + "AWSElasticBeanstalkEnhancedHealth": "arn:aws:iam::aws:policy/service-role/AWSElasticBeanstalkEnhancedHealth", + "AmazonGuardDutyServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonGuardDutyServiceRolePolicy", + "AWSAppSyncAdministrator": "arn:aws:iam::aws:policy/AWSAppSyncAdministrator", + "AWSCodeBuildAdminAccess": "arn:aws:iam::aws:policy/AWSCodeBuildAdminAccess", + "AWSServiceRoleForEC2ScheduledInstances": "arn:aws:iam::aws:policy/aws-service-role/AWSServiceRoleForEC2ScheduledInstances", + "AWSDeviceFarmFullAccess": "arn:aws:iam::aws:policy/AWSDeviceFarmFullAccess", + "ComprehendFullAccess": "arn:aws:iam::aws:policy/ComprehendFullAccess", + "AWSAgentlessDiscoveryService": "arn:aws:iam::aws:policy/AWSAgentlessDiscoveryService", + "CloudWatchReadOnlyAccess": "arn:aws:iam::aws:policy/CloudWatchReadOnlyAccess", + "AmazonElasticMapReduceReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonElasticMapReduceReadOnlyAccess", + "CloudWatchAgentAdminPolicy": "arn:aws:iam::aws:policy/CloudWatchAgentAdminPolicy", + "AWSCodeStarServiceRole": "arn:aws:iam::aws:policy/service-role/AWSCodeStarServiceRole", + "AmazonMacieSetupRole": "arn:aws:iam::aws:policy/service-role/AmazonMacieSetupRole", + "AWSLambdaENIManagementAccess": "arn:aws:iam::aws:policy/service-role/AWSLambdaENIManagementAccess", + "AWSOpsWorksInstanceRegistration": "arn:aws:iam::aws:policy/AWSOpsWorksInstanceRegistration", + "AWSDirectoryServiceFullAccess": "arn:aws:iam::aws:policy/AWSDirectoryServiceFullAccess", + "CloudWatchEventsBuiltInTargetExecutionAccess": "arn:aws:iam::aws:policy/service-role/CloudWatchEventsBuiltInTargetExecutionAccess", + "AWSIoTFullAccess": "arn:aws:iam::aws:policy/AWSIoTFullAccess", + "ServiceCatalogAdminReadOnlyAccess": "arn:aws:iam::aws:policy/ServiceCatalogAdminReadOnlyAccess", + "AWSGreengrassFullAccess": "arn:aws:iam::aws:policy/AWSGreengrassFullAccess", + "AWSCodeCommitFullAccess": "arn:aws:iam::aws:policy/AWSCodeCommitFullAccess", + "AlexaForBusinessGatewayExecution": "arn:aws:iam::aws:policy/AlexaForBusinessGatewayExecution", + "AWSMigrationHubFullAccess": "arn:aws:iam::aws:policy/AWSMigrationHubFullAccess", + "AWSMarketplaceMeteringFullAccess": "arn:aws:iam::aws:policy/AWSMarketplaceMeteringFullAccess", + "CloudFrontFullAccess": "arn:aws:iam::aws:policy/CloudFrontFullAccess", + "AmazonAthenaFullAccess": "arn:aws:iam::aws:policy/AmazonAthenaFullAccess", + "AWSCodeDeployRoleForLambda": "arn:aws:iam::aws:policy/service-role/AWSCodeDeployRoleForLambda", + "AWSElasticLoadBalancingServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSElasticLoadBalancingServiceRolePolicy", + "AmazonKinesisFullAccess": "arn:aws:iam::aws:policy/AmazonKinesisFullAccess", + "AWSApplicationAutoscalingEMRInstanceGroupPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingEMRInstanceGroupPolicy", + "AWSArtifactAccountSync": "arn:aws:iam::aws:policy/service-role/AWSArtifactAccountSync", + "AWSBatchFullAccess": "arn:aws:iam::aws:policy/AWSBatchFullAccess", + "AmazonRoute53FullAccess": "arn:aws:iam::aws:policy/AmazonRoute53FullAccess", + "AWSTrustedAdvisorServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSTrustedAdvisorServiceRolePolicy", + "AWSCodePipelineFullAccess": "arn:aws:iam::aws:policy/AWSCodePipelineFullAccess", + "AmazonWorkMailFullAccess": "arn:aws:iam::aws:policy/AmazonWorkMailFullAccess", + "TranslateReadOnly": "arn:aws:iam::aws:policy/TranslateReadOnly", + "AmazonDMSVPCManagementRole": "arn:aws:iam::aws:policy/service-role/AmazonDMSVPCManagementRole", + "AWSCodeCommitReadOnly": "arn:aws:iam::aws:policy/AWSCodeCommitReadOnly", + "CloudWatchEventsFullAccess": "arn:aws:iam::aws:policy/CloudWatchEventsFullAccess", + "AWSDataPipelineRole": "arn:aws:iam::aws:policy/service-role/AWSDataPipelineRole", + "AmazonMobileAnalyticsWriteOnlyAccess": "arn:aws:iam::aws:policy/AmazonMobileAnalyticsWriteOnlyAccess", + "AWSLambdaFullAccess": "arn:aws:iam::aws:policy/AWSLambdaFullAccess", + "APIGatewayServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/APIGatewayServiceRolePolicy", + "DataScientist": "arn:aws:iam::aws:policy/job-function/DataScientist", + "AmazonLexReadOnly": "arn:aws:iam::aws:policy/AmazonLexReadOnly", + "AWSDataPipeline_FullAccess": "arn:aws:iam::aws:policy/AWSDataPipeline_FullAccess", + "AWSCloud9Administrator": "arn:aws:iam::aws:policy/AWSCloud9Administrator", + "AmazonRDSServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonRDSServiceRolePolicy", + "AmazonMachineLearningManageRealTimeEndpointOnlyAccess": "arn:aws:iam::aws:policy/AmazonMachineLearningManageRealTimeEndpointOnlyAccess", + "AutoScalingReadOnlyAccess": "arn:aws:iam::aws:policy/AutoScalingReadOnlyAccess", + "AWSApplicationAutoscalingECSServicePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingECSServicePolicy", + "AmazonECS_FullAccess": "arn:aws:iam::aws:policy/AmazonECS_FullAccess", + "AmazonMechanicalTurkFullAccess": "arn:aws:iam::aws:policy/AmazonMechanicalTurkFullAccess", + "AmazonS3FullAccess": "arn:aws:iam::aws:policy/AmazonS3FullAccess", + "AmazonKinesisFirehoseReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonKinesisFirehoseReadOnlyAccess", + "AWSCodeStarFullAccess": "arn:aws:iam::aws:policy/AWSCodeStarFullAccess", + "AmazonElasticsearchServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonElasticsearchServiceRolePolicy", + "AmazonWorkSpacesAdmin": "arn:aws:iam::aws:policy/AmazonWorkSpacesAdmin", + "AmazonMechanicalTurkCrowdReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonMechanicalTurkCrowdReadOnlyAccess", + "AmazonRoute53DomainsFullAccess": "arn:aws:iam::aws:policy/AmazonRoute53DomainsFullAccess", + "AmazonEC2ContainerRegistryReadOnly": "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly", + "AmazonRekognitionFullAccess": "arn:aws:iam::aws:policy/AmazonRekognitionFullAccess", + "AWSLambdaRole": "arn:aws:iam::aws:policy/service-role/AWSLambdaRole", + "AWSApplicationAutoscalingEC2SpotFleetRequestPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSApplicationAutoscalingEC2SpotFleetRequestPolicy", + "CloudFrontReadOnlyAccess": "arn:aws:iam::aws:policy/CloudFrontReadOnlyAccess", + "AmazonCloudDirectoryFullAccess": "arn:aws:iam::aws:policy/AmazonCloudDirectoryFullAccess", + "AWSIoTRuleActions": "arn:aws:iam::aws:policy/service-role/AWSIoTRuleActions", + "AmazonEC2SpotFleetTaggingRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetTaggingRole", + "AWSLambdaDynamoDBExecutionRole": "arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole", + "AmazonElastiCacheReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess", + "AWSMigrationHubDiscoveryAccess": "arn:aws:iam::aws:policy/service-role/AWSMigrationHubDiscoveryAccess", + "AWSLambdaExecute": "arn:aws:iam::aws:policy/AWSLambdaExecute", + "AWSIoTDataAccess": "arn:aws:iam::aws:policy/AWSIoTDataAccess", + "AmazonChimeReadOnly": "arn:aws:iam::aws:policy/AmazonChimeReadOnly", + "AlexaForBusinessDeviceSetup": "arn:aws:iam::aws:policy/AlexaForBusinessDeviceSetup", + "AmazonRedshiftFullAccess": "arn:aws:iam::aws:policy/AmazonRedshiftFullAccess", + "AmazonDRSVPCManagement": "arn:aws:iam::aws:policy/AmazonDRSVPCManagement", + "AWSAccountUsageReportAccess": "arn:aws:iam::aws:policy/AWSAccountUsageReportAccess", + "VMImportExportRoleForAWSConnector": "arn:aws:iam::aws:policy/service-role/VMImportExportRoleForAWSConnector", + "AWSDirectConnectFullAccess": "arn:aws:iam::aws:policy/AWSDirectConnectFullAccess", + "AutoScalingNotificationAccessRole": "arn:aws:iam::aws:policy/service-role/AutoScalingNotificationAccessRole", + "AmazonElasticMapReduceFullAccess": "arn:aws:iam::aws:policy/AmazonElasticMapReduceFullAccess", + "AmazonEC2ContainerServiceFullAccess": "arn:aws:iam::aws:policy/AmazonEC2ContainerServiceFullAccess", + "AmazonCognitoReadOnly": "arn:aws:iam::aws:policy/AmazonCognitoReadOnly", + "AWSApplicationDiscoveryServiceFullAccess": "arn:aws:iam::aws:policy/AWSApplicationDiscoveryServiceFullAccess", + "AmazonDMSRedshiftS3Role": "arn:aws:iam::aws:policy/service-role/AmazonDMSRedshiftS3Role", + "AmazonSSMAutomationApproverAccess": "arn:aws:iam::aws:policy/AmazonSSMAutomationApproverAccess", + "AWSMobileHub_ServiceUseOnly": "arn:aws:iam::aws:policy/service-role/AWSMobileHub_ServiceUseOnly", + "AmazonAPIGatewayInvokeFullAccess": "arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess", + "ReadOnlyAccess": "arn:aws:iam::aws:policy/ReadOnlyAccess", + "DynamoDBReplicationServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/DynamoDBReplicationServiceRolePolicy", + "AmazonSSMMaintenanceWindowRole": "arn:aws:iam::aws:policy/service-role/AmazonSSMMaintenanceWindowRole", + "AmazonGuardDutyFullAccess": "arn:aws:iam::aws:policy/AmazonGuardDutyFullAccess", + "AWSWAFReadOnlyAccess": "arn:aws:iam::aws:policy/AWSWAFReadOnlyAccess", + "AutoScalingConsoleReadOnlyAccess": "arn:aws:iam::aws:policy/AutoScalingConsoleReadOnlyAccess", + "AmazonRoute53ReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonRoute53ReadOnlyAccess", + "AmazonGuardDutyReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonGuardDutyReadOnlyAccess", + "AmazonElasticFileSystemReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonElasticFileSystemReadOnlyAccess", + "AmazonEC2ContainerRegistryPowerUser": "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryPowerUser", + "AWSElasticBeanstalkFullAccess": "arn:aws:iam::aws:policy/AWSElasticBeanstalkFullAccess", + "AmazonSSMFullAccess": "arn:aws:iam::aws:policy/AmazonSSMFullAccess", + "Billing": "arn:aws:iam::aws:policy/job-function/Billing", + "AWSElasticBeanstalkServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSElasticBeanstalkServiceRolePolicy", + "LexBotPolicy": "arn:aws:iam::aws:policy/aws-service-role/LexBotPolicy", + "AmazonDMSCloudWatchLogsRole": "arn:aws:iam::aws:policy/service-role/AmazonDMSCloudWatchLogsRole", + "AWSOrganizationsServiceTrustPolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSOrganizationsServiceTrustPolicy", + "AmazonEC2SpotFleetAutoscaleRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetAutoscaleRole", + "AWSIoTThingsRegistration": "arn:aws:iam::aws:policy/service-role/AWSIoTThingsRegistration", + "IsengardControllerPolicy": "arn:aws:iam::aws:policy/aws-service-role/IsengardControllerPolicy", + "AmazonRDSDirectoryServiceAccess": "arn:aws:iam::aws:policy/service-role/AmazonRDSDirectoryServiceAccess", + "AmazonElasticTranscoderJobsSubmitter": "arn:aws:iam::aws:policy/AmazonElasticTranscoderJobsSubmitter", + "AWSCodePipelineReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCodePipelineReadOnlyAccess", + "AWSEC2SpotFleetServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSEC2SpotFleetServiceRolePolicy", + "AlexaForBusinessReadOnlyAccess": "arn:aws:iam::aws:policy/AlexaForBusinessReadOnlyAccess", + "AWSOpsWorksRegisterCLI": "arn:aws:iam::aws:policy/AWSOpsWorksRegisterCLI", + "CloudWatchFullAccess": "arn:aws:iam::aws:policy/CloudWatchFullAccess", + "AmazonEC2ContainerServiceEventsRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceEventsRole", + "AWSAccountActivityAccess": "arn:aws:iam::aws:policy/AWSAccountActivityAccess", + "AmazonGlacierReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess", + "AWSCloudHSMFullAccess": "arn:aws:iam::aws:policy/AWSCloudHSMFullAccess", + "AWSMigrationHubDMSAccess": "arn:aws:iam::aws:policy/service-role/AWSMigrationHubDMSAccess", + "AWSAppSyncInvokeFullAccess": "arn:aws:iam::aws:policy/AWSAppSyncInvokeFullAccess", + "RDSCloudHsmAuthorizationRole": "arn:aws:iam::aws:policy/service-role/RDSCloudHsmAuthorizationRole", + "AmazonTranscribeFullAccess": "arn:aws:iam::aws:policy/AmazonTranscribeFullAccess", + "AmazonChimeFullAccess": "arn:aws:iam::aws:policy/AmazonChimeFullAccess", + "AmazonKinesisReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonKinesisReadOnlyAccess", + "AmazonKinesisVideoStreamsFullAccess": "arn:aws:iam::aws:policy/AmazonKinesisVideoStreamsFullAccess", + "AWSEC2SpotServiceRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AWSEC2SpotServiceRolePolicy", + "AWSResourceGroupsReadOnlyAccess": "arn:aws:iam::aws:policy/AWSResourceGroupsReadOnlyAccess", + "AWSLambdaBasicExecutionRole": "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", + "AWSCloudTrailReadOnlyAccess": "arn:aws:iam::aws:policy/AWSCloudTrailReadOnlyAccess", + "AWSXrayReadOnlyAccess": "arn:aws:iam::aws:policy/AWSXrayReadOnlyAccess", + "AWSPriceListServiceFullAccess": "arn:aws:iam::aws:policy/AWSPriceListServiceFullAccess", + "AmazonRedshiftServiceLinkedRolePolicy": "arn:aws:iam::aws:policy/aws-service-role/AmazonRedshiftServiceLinkedRolePolicy", + "AWSOpsWorksFullAccess": "arn:aws:iam::aws:policy/AWSOpsWorksFullAccess", + "AmazonElasticTranscoderFullAccess": "arn:aws:iam::aws:policy/AmazonElasticTranscoderFullAccess", + "AWSElasticBeanstalkWorkerTier": "arn:aws:iam::aws:policy/AWSElasticBeanstalkWorkerTier", + "AWSLambdaReadOnlyAccess": "arn:aws:iam::aws:policy/AWSLambdaReadOnlyAccess", + "AmazonSNSFullAccess": "arn:aws:iam::aws:policy/AmazonSNSFullAccess", + "AlexaForBusinessFullAccess": "arn:aws:iam::aws:policy/AlexaForBusinessFullAccess", + "SimpleWorkflowFullAccess": "arn:aws:iam::aws:policy/SimpleWorkflowFullAccess", + "ResourceGroupsandTagEditorReadOnlyAccess": "arn:aws:iam::aws:policy/ResourceGroupsandTagEditorReadOnlyAccess", + "AmazonKinesisFirehoseFullAccess": "arn:aws:iam::aws:policy/AmazonKinesisFirehoseFullAccess", + "AmazonMacieFullAccess": "arn:aws:iam::aws:policy/AmazonMacieFullAccess", + "AmazonEC2SpotFleetRole": "arn:aws:iam::aws:policy/service-role/AmazonEC2SpotFleetRole", + "AmazonPollyReadOnlyAccess": "arn:aws:iam::aws:policy/AmazonPollyReadOnlyAccess", + "AWSElementalMediaPackageReadOnly": "arn:aws:iam::aws:policy/AWSElementalMediaPackageReadOnly", + "AmazonMechanicalTurkCrowdFullAccess": "arn:aws:iam::aws:policy/AmazonMechanicalTurkCrowdFullAccess" +} \ No newline at end of file diff --git a/samcli/lib/samlib/local_uri_plugin.py b/samcli/lib/samlib/local_uri_plugin.py new file mode 100644 index 0000000000..e7ec0294af --- /dev/null +++ b/samcli/lib/samlib/local_uri_plugin.py @@ -0,0 +1,23 @@ +""" +Plugin to validate and convert local paths for CodeUri and DefinitionUri into mock S3 paths. This is required +for SAM Parser and Validator to work because the underlying SAM library expects the URIs to be S3 paths. +""" + +from samtranslator.public.plugins import BasePlugin + + +class SupportLocalUriPlugin(BasePlugin): + + _SERVERLESS_FUNCTION = "AWS::Serverless::Function" + + def __init__(self): + """ + Initialize the plugin + """ + super(SupportLocalUriPlugin, self).__init__(SupportLocalUriPlugin.__name__) + + def on_before_transform_resource(self, logical_id, resource_type, resource_properties): + + if resource_type == self._SERVERLESS_FUNCTION and not resource_properties.get("CodeUri"): + # If CodeUri is *not* present, set it to "." which is functionally equivalent + resource_properties["CodeUri"] = "." diff --git a/samcli/lib/samlib/wrapper.py b/samcli/lib/samlib/wrapper.py new file mode 100644 index 0000000000..fe07319067 --- /dev/null +++ b/samcli/lib/samlib/wrapper.py @@ -0,0 +1,145 @@ +""" +Wrapper for the SAM Translator and Parser classes. + +##### NOTE ##### +This module uses internal packages of SAM Translator library in order to provide a nice interface for the CLI. This is +a tech debt that we have decided to take on. This will be eventually thrown away when SAM Translator exposes a +rich public interface. +""" + +import copy +import os +import json +import boto3 + +# SAM Translator Library Internal module imports # +from samtranslator.model.exceptions import \ + InvalidDocumentException, InvalidTemplateException, InvalidResourceException, InvalidEventException +from samtranslator.validator.validator import SamTemplateValidator +from samtranslator.model import ResourceTypeResolver, sam_resources +from samtranslator.plugins import LifeCycleEvents +from samtranslator.translator.translator import prepare_plugins, Translator +from samtranslator.translator.managed_policy_translator import ManagedPolicyLoader +from samtranslator.parser.parser import Parser + +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException +from .local_uri_plugin import SupportLocalUriPlugin + + +class SamTranslatorWrapper(object): + + _thisdir = os.path.dirname(os.path.abspath(__file__)) + _DEFAULT_MANAGED_POLICIES_FILE = os.path.join(_thisdir, "default_managed_policies.json") + + def __init__(self, sam_template, offline_fallback=True): + """ + + Parameters + ---------- + sam_template dict: + SAM Template dictionary + offline_fallback bool: + Set it to True to make the translator work entirely offline, if internet is not available + """ + self.local_uri_plugin = SupportLocalUriPlugin() + self.extra_plugins = [ + # Extra plugin specific to the SAM CLI that will support local paths for CodeUri & DefinitionUri + self.local_uri_plugin + ] + + self._sam_template = sam_template + self._offline_fallback = offline_fallback + + def run_plugins(self, convert_local_uris=True): + template_copy = self.template + + additional_plugins = [] + if convert_local_uris: + # Add all the plugins to convert local path if asked to. + additional_plugins.append(self.local_uri_plugin) + + parser = _SamParserReimplemented() + all_plugins = prepare_plugins(additional_plugins) + + try: + parser.parse(template_copy, all_plugins) # parse() will run all configured plugins + except InvalidDocumentException as e: + raise InvalidSamDocumentException( + reduce(lambda message, error: message + ' ' + error.message, e.causes, e.message)) + + return template_copy + + def __translate(self, parameter_values): + """ + This method is unused and a Work In Progress + """ + + template_copy = self.template + + sam_parser = Parser() + sam_translator = Translator(managed_policy_map=self.__managed_policy_map(), + sam_parser=sam_parser, + # Default plugins are already initialized within the Translator + plugins=self.extra_plugins) + + return sam_translator.translate(sam_template=template_copy, + parameter_values=parameter_values) + + @property + def template(self): + return copy.deepcopy(self._sam_template) + + def __managed_policy_map(self): + """ + This method is unused and a Work In Progress + """ + try: + iam_client = boto3.client('iam') + return ManagedPolicyLoader(iam_client).load() + except Exception as ex: + + if self._offline_fallback: + # If offline flag is set, then fall back to the list of default managed policies + # This should be sufficient for most cases + with open(self._DEFAULT_MANAGED_POLICIES_FILE, 'r') as fp: + return json.load(fp) + + # Offline is not enabled. So just raise the exception + raise ex + + +class _SamParserReimplemented(object): + """ + Re-implementation (almost copy) of Parser class from SAM Translator + """ + + def parse(self, sam_template, sam_plugins): + self._validate(sam_template) + sam_plugins.act(LifeCycleEvents.before_transform_template, sam_template) + macro_resolver = ResourceTypeResolver(sam_resources) + document_errors = [] + + for logical_id, resource in sam_template["Resources"].items(): + try: + if macro_resolver.can_resolve(resource): + macro_resolver \ + .resolve_resource_type(resource) \ + .from_dict(logical_id, resource, sam_plugins=sam_plugins) + except (InvalidResourceException, InvalidEventException) as e: + document_errors.append(e) + + if document_errors: + raise InvalidDocumentException(document_errors) + + def _validate(self, sam_template): + """ Validates the template and parameter values and raises exceptions if there's an issue + + :param dict sam_template: SAM template + """ + + if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \ + or not sam_template["Resources"]: + raise InvalidDocumentException( + [InvalidTemplateException("'Resources' section is required")]) + + SamTemplateValidator.validate(sam_template) diff --git a/samcli/local/__init__.py b/samcli/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/apigw/__init__.py b/samcli/local/apigw/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/apigw/path_converter.py b/samcli/local/apigw/path_converter.py new file mode 100644 index 0000000000..c862b51efc --- /dev/null +++ b/samcli/local/apigw/path_converter.py @@ -0,0 +1,55 @@ +""" +Converter class that handles the conversion of paths from Api Gateway to Flask and back. +""" + +import re + +FLASK_PATH_PARAMS = "/" +APIGW_PATH_PARAMS_ESCAPED = r"/{proxy\+}" +APIGW_PATH_PARAMS = "/{proxy+}" +LEFT_BRACKET = "{" +RIGHT_BRACKET = "}" +LEFT_ANGLE_BRACKET = "<" +RIGHT_ANGLE_BRACKET = ">" + +APIGW_TO_FLASK_REGEX = re.compile(APIGW_PATH_PARAMS_ESCAPED) +FLASK_TO_APIGW_REGEX = re.compile(FLASK_PATH_PARAMS) + + +class PathConverter(object): + + @staticmethod + def convert_path_to_flask(path): + """ + Converts a Path from an Api Gateway defined path to one that is accepted by Flask + + Examples: + + '/id/{id}' => '/id/' + '/{proxy+}' => '/' + + :param str path: Path to convert to Flask defined path + :return str: Path representing a Flask path + """ + proxy_sub_path = APIGW_TO_FLASK_REGEX.sub(FLASK_PATH_PARAMS, path) + + # Replace the '{' and '}' with '<' and '>' respectively + return proxy_sub_path.replace(LEFT_BRACKET, LEFT_ANGLE_BRACKET).replace(RIGHT_BRACKET, RIGHT_ANGLE_BRACKET) + + @staticmethod + def convert_path_to_api_gateway(path): + """ + Converts a Path from a Flask defined path to one that is accepted by Api Gateway + + Examples: + + '/id/' => '/id/{id}' + '/' => '/{proxy+}' + + :param str path: Path to convert to Api Gateway defined path + :return str: Path representing an Api Gateway path + """ + proxy_sub_path = FLASK_TO_APIGW_REGEX.sub(APIGW_PATH_PARAMS, path) + + # Replace the '<' and '>' with '{' and '}' respectively + return proxy_sub_path.replace(LEFT_ANGLE_BRACKET, LEFT_BRACKET).replace(RIGHT_ANGLE_BRACKET, RIGHT_BRACKET) diff --git a/samcli/local/apigw/service.py b/samcli/local/apigw/service.py new file mode 100644 index 0000000000..e21312187c --- /dev/null +++ b/samcli/local/apigw/service.py @@ -0,0 +1,386 @@ +"""API Gateway Local Service""" +import io +import json +import logging +import base64 + +from flask import Flask, request, Response + +from samcli.local.lambdafn.exceptions import FunctionNotFound +from samcli.local.events.api_event import ContextIdentity, RequestContext, ApiGatewayLambdaEvent +from .service_error_responses import ServiceErrorResponses +from .path_converter import PathConverter + +LOG = logging.getLogger(__name__) + + +class Route(object): + + def __init__(self, methods, function_name, path, binary_types=None): + """ + Creates an ApiGatewayRoute + + :param list(str) methods: List of HTTP Methods + :param function_name: Name of the Lambda function this API is connected to + :param str path: Path off the base url + """ + self.methods = methods + self.function_name = function_name + self.path = path + self.binary_types = binary_types or [] + + +class Service(object): + + _DEFAULT_PORT = 3000 + _DEFAULT_HOST = '127.0.0.1' + + def __init__(self, routing_list, lambda_runner, static_dir=None, port=None, host=None, stderr=None): + """ + Creates an ApiGatewayService + + :param list(ApiGatewayCallModel) routing_list: A list of the Model that represent + the service paths to create. + :param samcli.commands.local.lib.local_lambda.LocalLambdaRunner lambda_runner: The Lambda runner class capable + of invoking the function + :param str static_dir: Directory from which to serve static files + :param int port: Optional. port for the service to start listening on + Defaults to 3000 + :param str host: Optional. host to start the service on + Defaults to '0.0.0.0' + :param io.BaseIO stderr: Optional stream where the stderr from Docker container should be written to + """ + self.routing_list = routing_list + self.lambda_runner = lambda_runner + self.static_dir = static_dir + self.port = port or self._DEFAULT_PORT + self.host = host or self._DEFAULT_HOST + self._dict_of_routes = {} + self._app = None + self.stderr = stderr + + def create(self): + """ + Creates a Flask Application that can be started. + """ + + self._app = Flask(__name__, + static_url_path="", # Mount static files at root '/' + static_folder=self.static_dir # Serve static files from this directory + ) + + for api_gateway_route in self.routing_list: + path = PathConverter.convert_path_to_flask(api_gateway_route.path) + for route_key in self._generate_route_keys(api_gateway_route.methods, + path): + self._dict_of_routes[route_key] = api_gateway_route + + self._app.add_url_rule(path, + endpoint=path, + view_func=self._request_handler, + methods=api_gateway_route.methods) + + self._construct_error_handling() + + def _generate_route_keys(self, methods, path): + """ + Generates the key to the _dict_of_routes based on the list of methods + and path supplied + + :param list(str) methods: List of HTTP Methods + :param str path: Path off the base url + :return: str of Path:Method + """ + for method in methods: + yield self._route_key(method, path) + + @staticmethod + def _route_key(method, path): + return '{}:{}'.format(path, method) + + def _construct_error_handling(self): + """ + Updates the Flask app with Error Handlers for different Error Codes + """ + # Both path and method not present + self._app.register_error_handler(404, ServiceErrorResponses.route_not_found) + # Path is present, but method not allowed + self._app.register_error_handler(405, ServiceErrorResponses.route_not_found) + # Something went wrong + self._app.register_error_handler(500, ServiceErrorResponses.lambda_failure_response) + + def run(self): + """ + This starts up the (threaded) Local Server. + Note: This is a **blocking call** + + :raise RuntimeError: If the service was not created + """ + + if not self._app: + raise RuntimeError("The application must be created before running") + + # Flask can operate as a single threaded server (which is default) and a multi-threaded server which is + # more for development. When the Lambda container is going to be debugged, then it does not make sense + # to turn on multi-threading because customers can realistically attach only one container at a time to + # the debugger. Keeping this single threaded also enables the Lambda Runner to handle Ctrl+C in order to + # kill the container gracefully (Ctrl+C can be handled only by the main thread) + multi_threaded = not self.lambda_runner.is_debugging() + + LOG.debug("Local API Server starting up. Multi-threading = %s", multi_threaded) + self._app.run(threaded=multi_threaded, host=self.host, port=self.port) + + def _request_handler(self, **kwargs): + """ + We handle all requests to the host:port. The general flow of handling a request is as follows + + * Fetch request from the Flask Global state. This is where Flask places the request and is per thread so + multiple requests are still handled correctly + * Find the Lambda function to invoke by doing a look up based on the request.endpoint and method + * If we don't find the function, we will throw a 502 (just like the 404 and 405 responses we get + from Flask. + * Since we found a Lambda function to invoke, we construct the Lambda Event from the request + * Then Invoke the Lambda function (docker container) + * We then transform the response or errors we get from the Invoke and return the data back to + the caller + + :param kwargs dict: Keyword Args that are passed to the function from Flask. This happens when we have + Path Parameters. + :return: Response object + """ + route = self._get_current_route(request) + + try: + event = self._construct_event(request, self.port, route.binary_types) + except UnicodeDecodeError: + return ServiceErrorResponses.lambda_failure_response() + + stdout_stream = io.BytesIO() + + try: + self.lambda_runner.invoke(route.function_name, event, stdout=stdout_stream, stderr=self.stderr) + except FunctionNotFound: + return ServiceErrorResponses.lambda_not_found_response() + + lambda_response, lambda_logs = self._get_lambda_output(stdout_stream) + + if self.stderr and lambda_logs: + # Write the logs to stderr if available. + self.stderr.write(lambda_logs) + + try: + (status_code, headers, body) = self._parse_lambda_output(lambda_response, + route.binary_types, + request) + except (KeyError, TypeError, ValueError): + LOG.error("Function returned an invalid response (must include one of: body, headers or " + "statusCode in the response object). Response received: %s", lambda_response) + return ServiceErrorResponses.lambda_failure_response() + + return self._service_response(body, headers, status_code) + + @staticmethod + def _service_response(body, headers, status_code): + """ + Constructs a Flask Response from the body, headers, and status_code. + + :param str body: Response body as a string + :param dict headers: headers for the response + :param int status_code: status_code for response + :return: Flask Response + """ + response = Response(body) + response.headers = headers + response.status_code = status_code + return response + + def _get_current_route(self, flask_request): + """ + Get the route (Route) based on the current request + + :param request flask_request: Flask Request + :return: Route matching the endpoint and method of the request + """ + endpoint = flask_request.endpoint + method = flask_request.method + + route_key = self._route_key(method, endpoint) + route = self._dict_of_routes.get(route_key, None) + + if not route: + LOG.debug("Lambda function for the route not found. This should not happen because Flask is " + "already configured to serve all path/methods given to the service. " + "Path=%s Method=%s RouteKey=%s", endpoint, method, route_key) + raise KeyError("Lambda function for the route not found") + + return route + + @staticmethod + def _get_lambda_output(stdout_stream): + """ + This method will extract read the given stream and return the response from Lambda function separated out + from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function + wrote directly to stdout using System.out.println or equivalents. + + Parameters + ---------- + stdout_stream : io.BaseIO + Stream to fetch data from + + Returns + ------- + str + String data containing response from Lambda function + str + String data containng logs statements, if any. + """ + # We only want the last line of stdout, because it's possible that + # the function may have written directly to stdout using + # System.out.println or similar, before docker-lambda output the result + stdout_data = stdout_stream.getvalue().rstrip('\n') + + # Usually the output is just one line and contains response as JSON string, but if the Lambda function + # wrote anything directly to stdout, there will be additional lines. So just extract the last line as + # response and everything else as log output. + lambda_response = stdout_data + lambda_logs = None + + last_line_position = stdout_data.rfind('\n') + if last_line_position > 0: + # So there are multiple lines. Separate them out. + # Everything but the last line are logs + lambda_logs = stdout_data[:last_line_position] + # Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around + lambda_response = stdout_data[last_line_position:].strip() + + return lambda_response, lambda_logs + + # Consider moving this out to its own class. Logic is started to get dense and looks messy @jfuss + @staticmethod + def _parse_lambda_output(lambda_output, binary_types, flask_request): + """ + Parses the output from the Lambda Container + + :param str lambda_output: Output from Lambda Invoke + :return: Tuple(int, dict, str, bool) + """ + json_output = json.loads(lambda_output) + + if not isinstance(json_output, dict): + raise TypeError("Lambda returned %{s} instead of dict", type(json_output)) + + status_code = json_output.get("statusCode") or 200 + headers = json_output.get("headers") or {} + body = json_output.get("body") or "no data" + is_base_64_encoded = json_output.get("isBase64Encoded") or False + + if not isinstance(status_code, int) or status_code <= 0: + message = "statusCode must be a positive int" + LOG.error(message) + raise TypeError(message) + + # If the customer doesn't define Content-Type default to application/json + if "Content-Type" not in headers: + LOG.info("No Content-Type given. Defaulting to 'application/json'.") + headers["Content-Type"] = "application/json" + + if Service._should_base64_decode_body(binary_types, flask_request, headers, is_base_64_encoded): + body = base64.b64decode(body) + + return status_code, headers, body + + @staticmethod + def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded): + """ + Whether or not the body should be decoded from Base64 to Binary + + Parameters + ---------- + binary_types list(basestring) + Corresponds to self.binary_types (aka. what is parsed from SAM Template + flask_request flask.request + Flask request + lamba_response_headers dict + Headers Lambda returns + is_base_64_encoded bool + True if the body is Base64 encoded + + Returns + ------- + True if the body from the request should be converted to binary, otherwise false + + """ + best_match_mimetype = flask_request.accept_mimetypes.best_match([lamba_response_headers["Content-Type"]]) + is_best_match_in_binary_types = best_match_mimetype in binary_types or '*/*' in binary_types + + return best_match_mimetype and is_best_match_in_binary_types and is_base_64_encoded + + @staticmethod + def _construct_event(flask_request, port, binary_types): + """ + Helper method that constructs the Event to be passed to Lambda + + :param request flask_request: Flask Request + :return: String representing the event + """ + + identity = ContextIdentity(source_ip=flask_request.remote_addr) + + endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint) + method = flask_request.method + + request_data = flask_request.data + + request_mimetype = flask_request.mimetype + + is_base_64 = Service._should_base64_encode(binary_types, request_mimetype) + + if is_base_64: + LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.") + request_data = base64.b64encode(request_data) + elif request_data: + # Flask does not parse/decode the request data. We should do it ourselves + request_data = request_data.decode('utf-8') + + context = RequestContext(resource_path=endpoint, + http_method=method, + stage="prod", + identity=identity, + path=endpoint) + + event_headers = dict(flask_request.headers) + event_headers["X-Forwarded-Proto"] = flask_request.scheme + event_headers["X-Forwarded-Port"] = str(port) + + event = ApiGatewayLambdaEvent(http_method=method, + body=request_data, + resource=endpoint, + request_context=context, + query_string_params=flask_request.args, + headers=event_headers, + path_parameters=flask_request.view_args, + path=flask_request.path, + is_base_64_encoded=is_base_64) + + event_str = json.dumps(event.to_dict()) + LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str) + return event_str + + @staticmethod + def _should_base64_encode(binary_types, request_mimetype): + """ + Whether or not to encode the data from the request to Base64 + + Parameters + ---------- + binary_types list(basestring) + Corresponds to self.binary_types (aka. what is parsed from SAM Template + request_mimetype str + Mimetype for the request + + Returns + ------- + True if the data should be encoded to Base64 otherwise False + + """ + return request_mimetype in binary_types or "*/*" in binary_types diff --git a/samcli/local/apigw/service_error_responses.py b/samcli/local/apigw/service_error_responses.py new file mode 100644 index 0000000000..e32f6ec23a --- /dev/null +++ b/samcli/local/apigw/service_error_responses.py @@ -0,0 +1,44 @@ +"""Class container to hold common Service Responses""" + +from flask import jsonify, make_response + + +class ServiceErrorResponses(object): + + _NO_LAMBDA_INTEGRATION = {"message": "No function defined for resource method"} + _MISSING_AUTHENTICATION = {"message": "Missing Authentication Token"} + _LAMBDA_FAILURE = {"message": "Internal server error"} + + HTTP_STATUS_CODE_502 = 502 + HTTP_STATUS_CODE_403 = 403 + + @staticmethod + def lambda_failure_response(*args): + """ + Helper function to create a Lambda Failure Response + + :return: A Flask Response + """ + response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE) + return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) + + @staticmethod + def lambda_not_found_response(*args): + """ + Constructs a Flask Response for when a Lambda function is not found for an endpoint + + :return: a Flask Response + """ + response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION) + return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) + + @staticmethod + def route_not_found(*args): + """ + Constructs a Flask Response for when a API Route (path+method) is not found. This is usually + HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840) + + :return: a Flask Response + """ + response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION) + return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403) diff --git a/samcli/local/docker/__init__.py b/samcli/local/docker/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/docker/attach_api.py b/samcli/local/docker/attach_api.py new file mode 100644 index 0000000000..08c1824e1a --- /dev/null +++ b/samcli/local/docker/attach_api.py @@ -0,0 +1,173 @@ +""" +Wrapper to Docker Attach API +""" + +import struct +from docker.utils.socket import read, read_exactly, SocketError + + +def attach(docker_client, container, stdout=True, stderr=True, logs=False): + """ + + Implements a method that wraps Docker Attach API to attach to a container and demux stdout and stderr data from the + single data stream that Docker API returns. + + The signature of this method is intentionally similar to Docker Python SDK's ``attach()`` method except for the + addition of one parameter called `demux` which, if set to True, will return an iterator that provides the stream + data along with a stream type identifier. Caller can handle the data appropriately. + + Parameters + ---------- + docker_client : docker.Client + Docker client used to talk to Docker daemon + + container : docker.container + Instance of the container to attach to + + stdout : bool + Do you want to get stdout data? + + stderr : bool + Do you want to get stderr data? + + logs : bool + Do you want to include the container's previous output? + """ + + headers = { + "Connection": "Upgrade", + "Upgrade": "tcp" + } + + query_params = { + "stdout": 1 if stdout else 0, + "stderr": 1 if stderr else 0, + "logs": 1 if logs else 0, + "stream": 1, # Yes, we always stream + "stdin": 0, # We don't support stdin + } + + # API client is a lower level Docker client that wraps the Docker APIs. It has methods that will help us + # talk to the API directly. It is an instance of ``docker.APIClient``. We are going to use private methods of + # class here because it is sometimes more convenient. + api_client = docker_client.api + + # URL where the Docker daemon is running + url = "{}/containers/{}/attach".format(api_client.base_url, container.id) + + # Send out the attach request and read the socket for response + response = api_client._post(url, headers=headers, params=query_params, stream=True) # pylint: disable=W0212 + socket = api_client._get_raw_response_socket(response) # pylint: disable=W0212 + + return _read_socket(socket) + + +def _read_socket(socket): + """ + The stdout and stderr data from the container multiplexed into one stream of response from the Docker API. + It follows the protocol described here https://docs.docker.com/engine/api/v1.30/#operation/ContainerAttach. + The stream starts with a 8 byte header that contains the frame type and also payload size. Follwing that is the + actual payload of given size. Once you read off this payload, we are ready to read the next header. + + This method will follow this protocol to read payload from the stream and return an iterator that returns + a tuple containing the frame type and frame data. Callers can handle the data appropriately based on the frame + type. + + Stdout => Frame Type = 1 + Stderr => Frame Type = 2 + + + Parameters + ---------- + socket + Socket to read responses from + + Yields + ------- + int + Type of the stream (1 => stdout, 2 => stderr) + str + Data in the stream + """ + + # Keep reading the stream until the stream terminates + while True: + + try: + + payload_type, payload_size = _read_header(socket) + if payload_size < 0: + # Something is wrong with the data stream. Payload size can't be less than zero + break + + for data in _read_payload(socket, payload_size): + yield payload_type, data + + except SocketError: + # There isn't enough data in the stream. Probably the socket terminated + break + + +def _read_payload(socket, payload_size): + """ + From the given socket, reads and yields payload of the given size. With sockets, we don't receive all data at + once. Therefore this method will yield each time we read some data from the socket until the payload_size has + reached or socket has no more data. + + Parameters + ---------- + socket + Socket to read from + + payload_size : int + Size of the payload to read. Exactly these many bytes are read from the socket before stopping the yield. + + Yields + ------- + int + Type of the stream (1 => stdout, 2 => stderr) + str + Data in the stream + """ + + remaining = payload_size + while remaining > 0: + + # Try and read as much as possible + data = read(socket, remaining) + if data is None: + # ``read`` will terminate with an empty string. This is just a transient state where we didn't get any data + continue + + if len(data) == 0: # pylint: disable=C1801 + # Empty string. Socket does not have any more data. We are done here even if we haven't read full payload + break + + remaining -= len(data) + yield data + + +def _read_header(socket): + """ + Reads the header from socket stream to determine the size of next frame to read. Header is 8 bytes long, where + the first byte is the stream type and last four bytes (bigendian) is size of the payload + + header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} + + Parameters + ---------- + socket + Socket to read the responses from + + Returns + ------- + int + Type of the frame + int + Size of the payload + """ + + data = read_exactly(socket, 8) + + # >BxxxL is the struct notation to unpack data in correct header format in big-endian + return struct.unpack('>BxxxL', data) diff --git a/samcli/local/docker/container.py b/samcli/local/docker/container.py new file mode 100644 index 0000000000..aa2357c5d7 --- /dev/null +++ b/samcli/local/docker/container.py @@ -0,0 +1,253 @@ +""" +Representation of a generic Docker container +""" + +import logging +import docker + +from samcli.local.docker.attach_api import attach + +LOG = logging.getLogger(__name__) + + +class Container(object): + """ + Represents an instance of a Docker container with a specific configuration. The container is not actually created + or executed until the appropriate methods are called. Each container instance is uniquely identified by an ID that + the Docker Daemon creates when the container is started. + + NOTE: This class does not download container images. It should be pulled separately and made available before + creating a container with this class + """ + + # This frame type value is coming directly from Docker Attach Stream API spec + _STDOUT_FRAME_TYPE = 1 + _STDERR_FRAME_TYPE = 2 + + def __init__(self, + image, + cmd, + working_dir, + host_dir, + memory_limit_mb=None, + exposed_ports=None, + entrypoint=None, + env_vars=None, + docker_client=None): + """ + Initializes the class with given configuration. This does not automatically create or run the container. + + :param string image: Name of the Docker image to create container with + :param string working_dir: Working directory for the container + :param string host_dir: Directory in the host operating system that should be mounted to the ``working_dir`` on + container + :param list cmd: Command to pass to container + :param int memory_limit_mb: Optional. Max limit of memory in MegaBytes this Lambda function can use. + :param dict exposed_ports: Optional. Dict of ports to expose + :param list entrypoint: Optional. Entry point process for the container. Defaults to the value in Dockerfile + :param dict env_vars: Optional. Dict of environment variables to setup in the container + """ + + self._image = image + self._cmd = cmd + self._working_dir = working_dir + self._host_dir = host_dir + self._exposed_ports = exposed_ports + self._entrypoint = entrypoint + self._env_vars = env_vars + self._memory_limit_mb = memory_limit_mb + self._network_id = None + + # Use the given Docker client or create new one + self.docker_client = docker_client or docker.from_env() + + # Runtime properties of the container. They won't have value until container is created or started + self.id = None + + def create(self): + """ + Calls Docker API to creates the Docker container instance. Creating the container does *not* run the container. + Use ``start`` method to run the container + + :return string: ID of the created container + :raise RuntimeError: If this method is called after a container already has been created + """ + + if self.is_created(): + raise RuntimeError("This container already exists. Cannot create again.") + + LOG.info("Mounting %s as %s:ro inside runtime container", self._host_dir, self._working_dir) + + kwargs = { + "command": self._cmd, + "working_dir": self._working_dir, + "volumes": { + self._host_dir: { + # Mount the host directory as "read only" directory inside container at working_dir + # https://docs.docker.com/storage/bind-mounts + # Mount the host directory as "read only" inside container + "bind": self._working_dir, + "mode": "ro" + } + }, + # We are not running an interactive shell here. + "tty": False + } + + if self._env_vars: + kwargs["environment"] = self._env_vars + + if self._exposed_ports: + kwargs["ports"] = self._exposed_ports + + if self._entrypoint: + kwargs["entrypoint"] = self._entrypoint + + if self._memory_limit_mb: + # Ex: 128m => 128MB + kwargs["mem_limit"] = "{}m".format(self._memory_limit_mb) + + real_container = self.docker_client.containers.create(self._image, **kwargs) + self.id = real_container.id + + if self.network_id: + network = self.docker_client.networks.get(self.network_id) + network.connect(self.id) + + return self.id + + def delete(self): + """ + Removes a container that was created earlier. + """ + + if not self.is_created(): + LOG.debug("Container was not created. Skipping deletion") + return + + try: + self.docker_client.containers\ + .get(self.id)\ + .remove(force=True) # Remove a container, even if it is running + except docker.errors.NotFound: + # Container is already not there + LOG.debug("Container with ID %s does not exist. Skipping deletion", self.id) + except docker.errors.APIError as ex: + msg = str(ex) + removal_in_progress = ("removal of container" in msg) and ("is already in progress" in msg) + + # When removal is already started, Docker API will throw an exception + # Skip such exceptions. + if not removal_in_progress: + raise ex + + self.id = None + + def start(self, input_data=None): + """ + Calls Docker API to start the container. The container must be created at the first place to run. + It waits for the container to complete, fetches both stdout and stderr logs and returns through the + given streams. + + :param input_data: Optional. Input data sent to the container through container's stdin. + :param io.StringIO stdout: Optional. IO Stream to that receives stdout text from container. + :param io.StringIO stderr: Optional. IO Stream that receives stderr text from container + """ + + if input_data: + raise ValueError("Passing input through container's stdin is not supported") + + if not self.is_created(): + raise RuntimeError("Container does not exist. Cannot start this container") + + # Get the underlying container instance from Docker API + real_container = self.docker_client.containers.get(self.id) + + # Start the container + real_container.start() + + def wait_for_logs(self, stdout=None, stderr=None): + + # Return instantly if we don't have to fetch any logs + if not stdout and not stderr: + return + + if not self.is_created(): + raise RuntimeError("Container does not exist. Cannot get logs for this container") + + real_container = self.docker_client.containers.get(self.id) + + # Fetch both stdout and stderr streams from Docker as a single iterator. + logs_itr = attach(self.docker_client, + container=real_container, + stdout=True, + stderr=True, + logs=True) + + self._write_container_output(logs_itr, stdout=stdout, stderr=stderr) + + @staticmethod + def _write_container_output(output_itr, stdout=None, stderr=None): + """ + Based on the data returned from the Container output, via the iterator, write it to the appropriate streams + + Parameters + ---------- + output_itr: Iterator + Iterator returned by the Docker Attach command + stdout: io.BaseIO, optional + Stream to write stdout data from Container into + stderr: io.BaseIO, optional + Stream to write stderr data from the Container into + """ + + # Iterator returns a tuple of (frame_type, data) where the frame type determines which stream we write output + # to + for frame_type, data in output_itr: + + if frame_type == Container._STDOUT_FRAME_TYPE and stdout: + # Frame type 1 is stdout data. + stdout.write(data) + + elif frame_type == Container._STDERR_FRAME_TYPE and stderr: + # Frame type 2 is stderr data. + stderr.write(data) + + else: + # Either an unsupported frame type or stream for this frame type is not configured + LOG.debug("Dropping Docker container output because of unconfigured frame type. " + "Frame Type: %s. Data: %s", frame_type, data) + + @property + def network_id(self): + """ + Gets the ID of the network this container connects to + :return string: ID of the network + """ + return self._network_id + + @network_id.setter + def network_id(self, value): + """ + Set the ID of network that this container should connect to + + :param string value: Value of the network ID + """ + self._network_id = value + + @property + def image(self): + """ + Returns the image used by this container + + :return string: Name of the container image + """ + return self._image + + def is_created(self): + """ + Checks if a container exists? + + :return bool: True if the container was created + """ + return self.id is not None diff --git a/samcli/local/docker/lambda_container.py b/samcli/local/docker/lambda_container.py new file mode 100644 index 0000000000..ac397e93c8 --- /dev/null +++ b/samcli/local/docker/lambda_container.py @@ -0,0 +1,221 @@ +""" +Represents Lambda runtime containers. +""" +from enum import Enum + +from .container import Container + + +class Runtime(Enum): + nodejs = "nodejs" + nodejs43 = "nodejs4.3" + nodejs610 = "nodejs6.10" + nodejs810 = "nodejs8.10" + python27 = "python2.7" + python36 = "python3.6" + java8 = "java8" + go1x = "go1.x" + dotnetcore20 = "dotnetcore2.0" + + @classmethod + def has_value(cls, value): + """ + Checks if the enum has this value + + :param string value: Value to check + :return bool: True, if enum has the value + """ + return any(value == item.value for item in cls) + + +class LambdaContainer(Container): + """ + Represents a Lambda runtime container. This class knows how to setup entry points, environment variables, + exposed ports etc specific to Lambda runtime container. The container management functionality (create/start/stop) + is provided by the base class + """ + + _IMAGE_REPO_NAME = "lambci/lambda" + _WORKING_DIR = "/var/task" + + def __init__(self, + runtime, + handler, + code_dir, + memory_mb=128, + env_vars=None, + debug_port=None, + debug_args=None): + """ + Initializes the class + + :param string runtime: Name of the Lambda runtime + :param string handler: Handler of the function to run + :param string code_dir: Directory where the Lambda function code is present. This directory will be mounted + to the container to execute + :param int memory_mb: Optional. Max limit of memory in MegaBytes this Lambda function can use. + :param dict env_vars: Optional. Dictionary containing environment variables passed to container + :param int debug_port: Optional. Bind the runtime's debugger to this port + :param string debug_args: Optional. Extra arguments passed to the entry point to setup debugging + """ + + if not Runtime.has_value(runtime): + raise ValueError("Unsupported Lambda runtime {}".format(runtime)) + + image = LambdaContainer._get_image(runtime) + ports = LambdaContainer._get_exposed_ports(debug_port) + entry = LambdaContainer._get_entry_point(runtime, debug_port, debug_args) + cmd = [handler] + + super(LambdaContainer, self).__init__(image, + cmd, + self._WORKING_DIR, + code_dir, + memory_limit_mb=memory_mb, + exposed_ports=ports, + entrypoint=entry, + env_vars=env_vars) + + @staticmethod + def _get_exposed_ports(debug_port): + """ + Return Docker container port binding information. If a debug port is given, then we will ask Docker to + bind to same port both inside and outside the container ie. Runtime process is started in debug mode with + at given port inside the container and exposed to the host machine at the same port + + :param int debug_port: Optional, integer value of debug port + :return dict: Dictionary containing port binding information. None, if debug_port was not given + """ + if not debug_port: + return None + + return { + # container port : host port + debug_port: debug_port + } + + @staticmethod + def _get_image(runtime): + """ + Returns the name of Docker Image for the given runtime + + :param string runtime: Name of the runtime + :return: Name of Docker Image for the given runtime + """ + return "{}:{}".format(LambdaContainer._IMAGE_REPO_NAME, runtime) + + @staticmethod + def _get_entry_point(runtime, debug_port=None, debug_args=None): + """ + Returns the entry point for the container. The default value for the entry point is already configured in the + Dockerfile. We override this default specifically when enabling debugging. The overridden entry point includes + a few extra flags to start the runtime in debug mode. + + :param string runtime: Lambda function runtime name + :param int debug_port: Optional, port for debugger + :param string debug_args: Optional additional arguments passed to the entry point. + :return list: List containing the new entry points. Each element in the list is one portion of the command. + ie. if command is ``node index.js arg1 arg2``, then this list will be ["node", "index.js", "arg1", "arg2"] + """ + + if not debug_port: + return None + + debug_args_list = [] + if debug_args: + debug_args_list = debug_args.split(" ") + + # configs from: https://github.com/lambci/docker-lambda + # to which we add the extra debug mode options + entrypoint = None + if runtime == Runtime.java8.value: + + entrypoint = ["/usr/bin/java"] \ + + debug_args_list \ + + [ + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,quiet=y,address=" + str(debug_port), + "-XX:MaxHeapSize=1336935k", + "-XX:MaxMetaspaceSize=157286k", + "-XX:ReservedCodeCacheSize=78643k", + "-XX:+UseSerialGC", + # "-Xshare:on", doesn't work in conjunction with the debug options + "-XX:-TieredCompilation", + "-Djava.net.preferIPv4Stack=true", + "-jar", + "/var/runtime/lib/LambdaJavaRTEntry-1.0.jar", + ] + + elif runtime == Runtime.nodejs.value: + + entrypoint = ["/usr/bin/node"] \ + + debug_args_list \ + + [ + "--debug-brk=" + str(debug_port), + "--nolazy", + "--max-old-space-size=1229", + "--max-new-space-size=153", + "--max-executable-size=153", + "--expose-gc", + "/var/runtime/node_modules/awslambda/bin/awslambda", + ] + + elif runtime == Runtime.nodejs43.value: + + entrypoint = ["/usr/local/lib64/node-v4.3.x/bin/node"] \ + + debug_args_list \ + + [ + "--debug-brk=" + str(debug_port), + "--nolazy", + "--max-old-space-size=2547", + "--max-semi-space-size=150", + "--max-executable-size=160", + "--expose-gc", + "/var/runtime/node_modules/awslambda/index.js", + ] + + elif runtime == Runtime.nodejs610.value: + + entrypoint = ["/var/lang/bin/node"] \ + + debug_args_list \ + + [ + "--debug-brk=" + str(debug_port), + "--nolazy", + "--max-old-space-size=2547", + "--max-semi-space-size=150", + "--max-executable-size=160", + "--expose-gc", + "/var/runtime/node_modules/awslambda/index.js", + ] + + elif runtime == Runtime.nodejs810.value: + + entrypoint = ["/var/lang/bin/node"] \ + + debug_args_list \ + + [ + # Node8 requires the host to be explicitly set in order to bind to localhost + # instead of 127.0.0.1. https://github.com/nodejs/node/issues/11591#issuecomment-283110138 + "--inspect-brk=0.0.0.0:" + str(debug_port), + "--nolazy", + "--expose-gc", + "--max-semi-space-size=150", + "--max-old-space-size=2707", + "/var/runtime/node_modules/awslambda/index.js", + ] + + elif runtime == Runtime.python27.value: + + entrypoint = ["/usr/bin/python2.7"] \ + + debug_args_list \ + + [ + "/var/runtime/awslambda/bootstrap.py" + ] + + elif runtime == Runtime.python36.value: + + entrypoint = ["/var/lang/bin/python3.6"] \ + + debug_args_list \ + + [ + "/var/runtime/awslambda/bootstrap.py" + ] + + return entrypoint diff --git a/samcli/local/docker/manager.py b/samcli/local/docker/manager.py new file mode 100644 index 0000000000..35bcc61d60 --- /dev/null +++ b/samcli/local/docker/manager.py @@ -0,0 +1,115 @@ +""" +Provides classes that interface with Docker to create, execute and manage containers. +""" + +import logging +import sys +import docker + +LOG = logging.getLogger(__name__) + + +class ContainerManager(object): + """ + This class knows how to interface with Docker to create, execute and manage the container's life cycle. It can + run multiple containers in parallel, and also comes with the ability to reuse existing containers in order to + serve requests faster. It is also thread-safe. + """ + + def __init__(self, + docker_network_id=None, + docker_client=None, + skip_pull_image=False): + """ + Instantiate the container manager + + :param docker_network_id: Optional Docker network to run this container in. + :param docker_client: Optional docker client object + :param bool skip_pull_image: Should we pull new Docker container image? + """ + + self.skip_pull_image = skip_pull_image + self.docker_network_id = docker_network_id + self.docker_client = docker_client or docker.from_env() + + def run(self, container, input_data=None, warm=False): + """ + Create and run a Docker container based on the given configuration. + + :param samcli.local.docker.container.Container container: Container to create and run + :param input_data: Optional. Input data sent to the container through container's stdin. + :param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will + be created for every request. + :raises DockerImageNotFoundException: If the Docker image was not available in the server + """ + + if warm: + raise ValueError("The facility to invoke warm container does not exist") + + image_name = container.image + + # Pull a new image if: a) Image is not available OR b) We are not asked to skip pulling the image + if not self.has_image(image_name) or not self.skip_pull_image: + self.pull_image(image_name) + else: + LOG.info("Requested to skip pulling images ...\n") + + if not container.is_created(): + # Create the container first before running. + # Create the container in appropriate Docker network + container.network_id = self.docker_network_id + container.create() + + container.start(input_data=input_data) + + def stop(self, container): + """ + Stop and delete the container + + :param samcli.local.docker.container.Container container: Container to stop + """ + container.delete() + + def pull_image(self, image_name, stream=None): + """ + Ask Docker to pull the container image with given name. + + :param string image_name: Name of the image + :param stream: Optional stream to write output to. Defaults to stderr + :raises DockerImageNotFoundException: If the Docker image was not available in the server + """ + stream = stream or sys.stderr + try: + result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True) + except docker.errors.ImageNotFound as ex: + raise DockerImageNotFoundException(str(ex)) + + # io streams, especially StringIO, work only with unicode strings + stream.write(u"\nFetching {} Docker container image...".format(image_name)) + + # Each line contains information on progress of the pull. Each line is a JSON string + for _ in result_itr: + # For every line, print a dot to show progress + stream.write(u'.') + stream.flush() + + # We are done. Go to the next line + stream.write(u"\n") + + def has_image(self, image_name): + """ + Is the container image with given name available? + + :param string image_name: Name of the image + :return bool: True, if image is available. False, otherwise + """ + + try: + self.docker_client.images.get(image_name) + return True + except docker.errors.ImageNotFound: + return False + + +class DockerImageNotFoundException(Exception): + pass diff --git a/samcli/local/events/__init__.py b/samcli/local/events/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/events/api_event.py b/samcli/local/events/api_event.py new file mode 100644 index 0000000000..83ee88845a --- /dev/null +++ b/samcli/local/events/api_event.py @@ -0,0 +1,201 @@ +"""Holds Classes for API Gateway to Lambda Events""" + + +class ContextIdentity(object): + + def __init__(self, + api_key=None, + user_arn=None, + cognito_authentication_type=None, + caller=None, + user_agent="Custom User Agent String", + user=None, + cognito_identity_pool_id=None, + cognito_authentication_provider=None, + source_ip="127.0.0.1", + account_id=None): + """ + Constructs a ContextIdentity + + :param str api_key: API Key used for the request + :param str user_arn: ARN of the caller + :param str cognito_authentication_type: Auth Type used + :param str caller: Caller that make the request + :param str user_agent: User agent (Default: Custom User Agent String) + :param str user: User + :param str cognito_identity_pool_id: Identity Pool Id used + :param str cognito_authentication_provider: Auth Provider + :param str source_ip: Source Ip of the request (Default: 127.0.0.1) + :param str account_id: Account Id of the request + """ + self.api_key = api_key + self.user_arn = user_arn + self.cognito_authentication_type = cognito_authentication_type + self.caller = caller + self.user_agent = user_agent + self.user = user + self.cognito_identity_pool_id = cognito_identity_pool_id + self.cognito_authentication_provider = cognito_authentication_provider + self.source_ip = source_ip + self.account_id = account_id + + def to_dict(self): + """ + Constructs an dictionary representation of the Identity Object to be used in serializing to JSON + + :return: dict representing the object + """ + json_dict = {"apiKey": self.api_key, + "userArn": self.user_arn, + "cognitoAuthenticationType": self.cognito_authentication_type, + "caller": self.caller, + "userAgent": self.user_agent, + "user": self.user, + "cognitoIdentityPoolId": self.cognito_identity_pool_id, + "cognitoAuthenticationProvider": self.cognito_authentication_provider, + "sourceIp": self.source_ip, + "accountId": self.account_id + } + + return json_dict + + +class RequestContext(object): + + def __init__(self, + resource_id="123456", + api_id="1234567890", + resource_path=None, + http_method=None, + request_id="c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + account_id="123456789012", + stage=None, + identity=None, + extended_request_id=None, + path=None): + """ + Constructs a RequestContext + + :param str resource_id: Resource Id of the Request (Default: 123456) + :param str api_id: Api Id for the Request (Default: 1234567890) + :param str resource_path: Path for the Request + :param str http_method: HTTPMethod for the request + :param str request_id: Request Id for the request (Default: c6af9ac6-7b61-11e6-9a41-93e8deadbeef) + :param str account_id: Account Id of the Request (Default: 123456789012) + :param str stage: Api Gateway Stage + :param ContextIdentity identity: Identity for the Request + :param str extended_request_id: + :param str path: + """ + + self.resource_id = resource_id + self.api_id = api_id + self.resource_path = resource_path + self.http_method = http_method + self.request_id = request_id + self.account_id = account_id + self.stage = stage + self.identity = identity + self.extended_request_id = extended_request_id + self.path = path + + def to_dict(self): + """ + Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON + + :return: dict representing the object + """ + identity_dict = {} + if self.identity: + identity_dict = self.identity.to_dict() + + json_dict = {"resourceId": self.resource_id, + "apiId": self.api_id, + "resourcePath": self.resource_path, + "httpMethod": self.http_method, + "requestId": self.request_id, + "accountId": self.account_id, + "stage": self.stage, + "identity": identity_dict, + "extendedRequestId": self.extended_request_id, + "path": self.path + } + + return json_dict + + +class ApiGatewayLambdaEvent(object): + + def __init__(self, + http_method=None, + body=None, + resource=None, + request_context=None, + query_string_params=None, + headers=None, + path_parameters=None, + stage_variables=None, + path=None, + is_base_64_encoded=False): + """ + Constructs an ApiGatewayLambdaEvent + + :param str http_method: HTTPMethod of the request + :param str body: Body or data for the request + :param str resource: Resource for the reqeust + :param RequestContext request_context: RequestContext for the request + :param dict query_string_params: Query String parameters + :param dict headers: dict of the request Headers + :param dict path_parameters: Path Parameters + :param dict stage_variables: API Gateway Stage Variables + :param str path: Path of the request + :param bool is_base_64_encoded: True if the data is base64 encoded. + """ + + if not isinstance(query_string_params, dict) and \ + query_string_params is not None: + raise TypeError("'query_string_params' must be of type dict or None") + + if not isinstance(headers, dict) and headers is not None: + raise TypeError("'headers' must be of type dict or None") + + if not isinstance(path_parameters, dict) and path_parameters is not None: + raise TypeError("'path_parameters' must be of type dict or None") + + if not isinstance(stage_variables, dict) and stage_variables is not None: + raise TypeError("'stage_variables' must be of type dict or None") + + self.http_method = http_method + self.body = body + self.resource = resource + self.request_context = request_context + self.query_string_params = query_string_params + self.headers = headers + self.path_parameters = path_parameters + self.stage_variables = stage_variables + self.path = path + self.is_base_64_encoded = is_base_64_encoded + + def to_dict(self): + """ + Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON + + :return: dict representing the object + """ + request_context_dict = {} + if self.request_context: + request_context_dict = self.request_context.to_dict() + + json_dict = {"httpMethod": self.http_method, + "body": self.body if self.body else None, + "resource": self.resource, + "requestContext": request_context_dict, + "queryStringParameters": dict(self.query_string_params) if self.query_string_params else None, + "headers": dict(self.headers) if self.headers else None, + "pathParameters": dict(self.path_parameters) if self.path_parameters else None, + "stageVariables": dict(self.stage_variables) if self.stage_variables else None, + "path": self.path, + "isBase64Encoded": self.is_base_64_encoded + } + + return json_dict diff --git a/samcli/local/init/__init__.py b/samcli/local/init/__init__.py new file mode 100644 index 0000000000..209c1e96a4 --- /dev/null +++ b/samcli/local/init/__init__.py @@ -0,0 +1,86 @@ +""" +Init module to scaffold a project app from a template +""" +import logging +import os + +from cookiecutter.main import cookiecutter +from cookiecutter.exceptions import CookiecutterException +from samcli.local.init.exceptions import GenerateProjectFailedError + +LOG = logging.getLogger(__name__) + +_init_path = os.path.dirname(__file__) +_templates = os.path.join(_init_path, 'templates') + +RUNTIME_TEMPLATE_MAPPING = { + "python3.6": os.path.join(_templates, "cookiecutter-aws-sam-hello-python"), + "python2.7": os.path.join(_templates, "cookiecutter-aws-sam-hello-python"), + "python": os.path.join(_templates, "cookiecutter-aws-sam-hello-python"), + "nodejs6.10": os.path.join(_templates, "cookiecutter-aws-sam-hello-nodejs"), + "nodejs8.10": os.path.join(_templates, "cookiecutter-aws-sam-hello-nodejs"), + "nodejs4.3": os.path.join(_templates, "cookiecutter-aws-sam-hello-nodejs"), + "nodejs": os.path.join(_templates, "cookiecutter-aws-sam-hello-nodejs"), + "dotnetcore2.0": os.path.join(_templates, "cookiecutter-aws-sam-hello-dotnet"), + "dotnetcore1.0": os.path.join(_templates, "cookiecutter-aws-sam-hello-dotnet"), + "dotnetcore": os.path.join(_templates, "cookiecutter-aws-sam-hello-dotnet"), + "dotnet": os.path.join(_templates, "cookiecutter-aws-sam-hello-dotnet"), + "go1.x": os.path.join(_templates, "cookiecutter-aws-sam-hello-golang"), + "go": os.path.join(_templates, "cookiecutter-aws-sam-hello-golang"), + "java8": os.path.join(_templates, "cookiecutter-aws-sam-hello-java"), + "java": os.path.join(_templates, "cookiecutter-aws-sam-hello-java") +} + + +def generate_project( + location=None, runtime="nodejs", + output_dir=".", name='sam-sample-app', no_input=False): + """Generates project using cookiecutter and options given + + Generate project scaffolds a project using default templates if user + doesn't provide one via location parameter. Default templates are + automatically chosen depending on runtime given by the user. + + Parameters + ---------- + location: Path, optional + Git, HTTP, Local path or Zip containing cookiecutter template + (the default is None, which means no custom template) + runtime: str, optional + Lambda Runtime (the default is "nodejs", which creates a nodejs project) + output_dir: str, optional + Output directory where project should be generated + (the default is ".", which implies current folder) + name: str, optional + Name of the project + (the default is "sam-sample-app", which implies a project named sam-sample-app will be created) + no_input : bool, optional + Whether to prompt for input or to accept default values + (the default is False, which prompts the user for values it doesn't know for baking) + + Raises + ------ + GenerateProjectFailedError + If the process of baking a project fails + """ + + params = { + "template": location if location else RUNTIME_TEMPLATE_MAPPING[runtime], + "output_dir": output_dir, + "no_input": no_input + } + + LOG.debug("Parameters dict created with input given") + LOG.debug("%s", params) + + if not location and name is not None: + params['extra_context'] = {'project_name': name, 'runtime': runtime} + params['no_input'] = True + LOG.debug("Parameters dict updated with project name as extra_context") + LOG.debug("%s", params) + + try: + LOG.debug("Baking a new template with cookiecutter with all parameters") + cookiecutter(**params) + except CookiecutterException as e: + raise GenerateProjectFailedError(project=name, provider_error=e) diff --git a/samcli/local/init/exceptions.py b/samcli/local/init/exceptions.py new file mode 100644 index 0000000000..e53981e8d6 --- /dev/null +++ b/samcli/local/init/exceptions.py @@ -0,0 +1,17 @@ +""" +Custom Exceptions for Init module +""" + + +class InitErrorException(Exception): + fmt = 'An unspecified error occurred' + + def __init__(self, **kwargs): + msg = self.fmt.format(**kwargs) + Exception.__init__(self, msg) + self.kwargs = kwargs + + +class GenerateProjectFailedError(InitErrorException): + fmt = \ + ("An error ocurred while generating this {project}: {provider_error}") diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/.gitignore new file mode 100644 index 0000000000..74ea25e0e5 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/.gitignore @@ -0,0 +1,168 @@ + +# Created by https://www.gitignore.io/api/osx,linux,python,windows + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,linux,python,windows \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/LICENSE b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/LICENSE new file mode 100644 index 0000000000..f19aaa6d09 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/LICENSE @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/Pipfile b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/Pipfile new file mode 100644 index 0000000000..a22660daae --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/Pipfile @@ -0,0 +1,13 @@ +[[source]] + +url = "https://pypi.python.org/simple" +verify_ssl = true +name = "pypi" + +[packages] + +[dev-packages] + +cookiecutter = "*" +pytest-cookies = "*" +pytest = "*" diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/README.md new file mode 100644 index 0000000000..a324e12e26 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/README.md @@ -0,0 +1,42 @@ +# Cookiecutter SAM for dotNet based Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and dotnet 2.0. + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-dotnet`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + + +License +------- + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/cookiecutter.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/cookiecutter.json new file mode 100644 index 0000000000..135672404c --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/cookiecutter.json @@ -0,0 +1,3 @@ +{ + "project_name": "Name of the project" +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/setup.cfg b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/setup.cfg new file mode 100644 index 0000000000..eee4ab11a7 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/setup.cfg @@ -0,0 +1,2 @@ +[install] +prefix= \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/tests/test_cookiecutter.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/tests/test_cookiecutter.py new file mode 100644 index 0000000000..285b06b26c --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/tests/test_cookiecutter.py @@ -0,0 +1,47 @@ +""" + Tests cookiecutter baking process and rendered content +""" + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={ + 'project_name': 'hello sam' + }) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'hello sam' + assert result.project.isdir() + assert result.project.join('.gitignore').isfile() + assert result.project.join('template.yaml').isfile() + assert result.project.join('README.md').isfile() + assert result.project.join('src').isdir() + assert result.project.join('test').isdir() + assert result.project.join('src', 'HelloWorld').isdir() + assert result.project.join( + 'src', 'HelloWorld', 'HelloWorld.csproj').isfile() + assert result.project.join('src', 'HelloWorld', 'Program.cs').isfile() + assert result.project.join( + 'src', 'HelloWorld', 'aws-lambda-tools-defaults.json').isfile() + assert result.project.join( + 'test', 'HelloWorld.Test', 'FunctionTest.cs').isfile() + assert result.project.join( + 'test', 'HelloWorld.Test', 'HelloWorld.Tests.csproj').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'my_lambda'}) + app_file = result.project.join('src', 'HelloWorld', 'Program.cs') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "GetCallingIP", + "GetStringAsync", + "location", + "message", + "hello world", + "StatusCode" + ) + + for content in contents: + assert content in app_content diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/.gitignore new file mode 100644 index 0000000000..9baa19505f --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/.gitignore @@ -0,0 +1,405 @@ + +# Created by https://www.gitignore.io/api/macos,linux,windows,sublimetext,dotsettings,visualstudio,visualstudiocode + +### DotSettings ### +*.DotSettings +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### SublimeText ### +# cache files for sublime text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# workspace files are user-specific +*.sublime-workspace + +# project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using SublimeText +# *.sublime-project + +# sftp configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Uncomment the next line to ignore your web deploy settings. +# By default, sensitive information, such as encrypted password +# should be stored in the .pubxml.user file. +#*.pubxml +*.pubxml.user +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +### VisualStudio Patch ### +# By default, sensitive information, such as encrypted password +# should be stored in the .pubxml.user file. + + +# End of https://www.gitignore.io/api/macos,linux,windows,sublimetext,dotsettings,visualstudio,visualstudiocode \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/README.md new file mode 100644 index 0000000000..a530dc0ee3 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,130 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} + +## Requirements + +* AWS CLI already configured with at least PowerUser permission +* [Docker installed](https://www.docker.com/community-edition) +* [SAM Local installed](https://github.com/awslabs/aws-sam-cli) +* [DotNet Core installed](https://www.microsoft.com/net/download/macos) + +## Setup process + +### Creating the project and its dependencies + +In this example we use DotNet Core CLI to bundle our project with its dependencies: + +```bash +dotnet publish src/HelloWorld +``` + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +**SAM Local** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + {{cookiecutter.project_name}}: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + + +If the previous command run successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +## Packaging and deployment + +AWS Lambda C# runtime requires a flat folder with all dependencies including the application. SAM will use `CodeUri` property to know where to look up for both application and dependencies: + +```yaml +... + FirstFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: src/HelloWorld/bin/Debug/netcoreapp2.0/publish + ... +``` + +First and foremost, we need an `S3 bucket` where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don't have a S3 bucket to store code artifacts then this is a good time to create one: + +```bash +aws s3 mb s3://BUCKET_NAME +``` + +Next, run the following command to package our Lambda function to S3: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME +``` + +Next, the following command will create a Cloudformation Stack and deploy your SAM resources. + +```bash +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM +``` + +> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.** + +After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL: + +```bash +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --query 'Stacks[].Outputs' +``` +## Testing + +For testing our code, we use XUnit and you can use `dotnet test` to run tests defined under `test/` + +```bash +dotnet test test/HelloWorld.Test +``` +# Appendix + +## AWS CLI commands + +AWS CLI commands to package, deploy and describe outputs defined within the cloudformation stack: + +```bash +aws cloudformation package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME + +aws cloudformation deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyParameterSample=MySampleValue + +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs' +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/HelloWorld.csproj b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/HelloWorld.csproj new file mode 100644 index 0000000000..be4feb0f72 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/HelloWorld.csproj @@ -0,0 +1,19 @@ + + + + netcoreapp2.0 + true + + + + + + + + + + + + + + diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Program.cs b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Program.cs new file mode 100644 index 0000000000..32f4d6b7e0 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Program.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Net.Http; +using System.Net.Http.Headers; +using Newtonsoft.Json; + +using Amazon.Lambda.Core; +using Amazon.Lambda.APIGatewayEvents; + +// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class. +[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] + +namespace HelloWorld +{ + + public class Function + { + + private static readonly HttpClient client = new HttpClient(); + + private static async Task GetCallingIP() + { + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + + var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); + + var msg = await stringTask; + return msg.Replace("\n",""); + } + + public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + + string location = GetCallingIP().Result; + Dictionary body = new Dictionary + { + { "message", "hello world" }, + { "location", location }, + }; + + return new APIGatewayProxyResponse + { + Body = JsonConvert.SerializeObject(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + } + } +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Readme.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Readme.md new file mode 100644 index 0000000000..5badecf662 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/Readme.md @@ -0,0 +1,45 @@ +# AWS Lambda Empty Function Project + +This starter project consists of: +* Function.cs - class file containing a class with a single function handler method +* aws-lambda-tools-defaults.json - default argument settings for use with Visual Studio and command line deployment tools for AWS + +You may also have a test project depending on the options selected. + +The generated function handler is a simple method accepting a string argument that returns the uppercase equivalent of the input string. Replace the body of this method, and parameters, to suit your needs. + +## Here are some steps to follow from Visual Studio: + +To deploy your function to AWS Lambda, right click the project in Solution Explorer and select *Publish to AWS Lambda*. + +To view your deployed function open its Function View window by double-clicking the function name shown beneath the AWS Lambda node in the AWS Explorer tree. + +To perform testing against your deployed function use the Test Invoke tab in the opened Function View window. + +To configure event sources for your deployed function, for example to have your function invoked when an object is created in an Amazon S3 bucket, use the Event Sources tab in the opened Function View window. + +To update the runtime configuration of your deployed function use the Configuration tab in the opened Function View window. + +To view execution logs of invocations of your function use the Logs tab in the opened Function View window. + +## Here are some steps to follow to get started from the command line: + +Once you have edited your function you can use the following command lines to build, test and deploy your function to AWS Lambda from the command line (these examples assume the project name is *EmptyFunction*): + +Restore dependencies +``` + cd "{{cookiecutter.project_name}}" + dotnet restore +``` + +Execute unit tests +``` + cd "{{cookiecutter.project_name}}/test/{{cookiecutter.project_name}}.Tests" + dotnet test +``` + +Deploy function to AWS Lambda +``` + cd "{{cookiecutter.project_name}}/src/{{cookiecutter.project_name}}" + dotnet lambda deploy-function +``` diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/aws-lambda-tools-defaults.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/aws-lambda-tools-defaults.json new file mode 100644 index 0000000000..b050733aca --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/src/HelloWorld/aws-lambda-tools-defaults.json @@ -0,0 +1,16 @@ +{ + "Information": [ + "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.", + "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.", + "dotnet lambda help", + "All the command line options for the Lambda command can be specified in this file." + ], + "profile": "default", + "region": "us-east-2", + "configuration": "Release", + "framework": "netcoreapp2.0", + "function-runtime": "dotnetcore2.0", + "function-memory-size": 256, + "function-timeout": 30, + "function-handler": "HelloWorld::HelloWorld.Function::FunctionHandler" +} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/template.yaml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 0000000000..6602b37f39 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,42 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 10 + + +Resources: + + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: src/HelloWorld/bin/Debug/netcoreapp2.0/publish + Handler: HelloWorld::HelloWorld.Function::FunctionHandler + Runtime: dotnetcore2.0 + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + +Outputs: + + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/FunctionTest.cs b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/FunctionTest.cs new file mode 100644 index 0000000000..96881f0c67 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/FunctionTest.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Net.Http; +using System.Net.Http.Headers; + +using Newtonsoft.Json; +using Xunit; +using Amazon.Lambda.Core; +using Amazon.Lambda.TestUtilities; +using Amazon.Lambda.APIGatewayEvents; + +namespace HelloWorld.Tests +{ + public class FunctionTest + { + private static readonly HttpClient client = new HttpClient(); + + private static async Task GetCallingIP() + { + client.DefaultRequestHeaders.Accept.Clear(); + client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client"); + + var stringTask = client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false); + + var msg = await stringTask; + return msg.Replace("\n",""); + } + + [Fact] + public void TestHelloWorldFunctionHandler() + { + TestLambdaContext context; + APIGatewayProxyRequest request; + APIGatewayProxyResponse response; + + request = new APIGatewayProxyRequest(); + context = new TestLambdaContext(); + string location = GetCallingIP().Result; + Dictionary body = new Dictionary + { + { "message", "hello world" }, + { "location", location }, + }; + + var ExpectedResponse = new APIGatewayProxyResponse + { + Body = JsonConvert.SerializeObject(body), + StatusCode = 200, + Headers = new Dictionary { { "Content-Type", "application/json" } } + }; + + var function = new Function(); + response = function.FunctionHandler(request, context); + + Console.WriteLine("Lambda Response: \n" + response.Body); + Console.WriteLine("Expected Response: \n" + ExpectedResponse.Body); + + Assert.Equal(ExpectedResponse.Body, response.Body); + Assert.Equal(ExpectedResponse.Headers, response.Headers); + Assert.Equal(ExpectedResponse.StatusCode, response.StatusCode); + } + } +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/HelloWorld.Tests.csproj b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/HelloWorld.Tests.csproj new file mode 100644 index 0000000000..cb5448d587 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-dotnet/{{cookiecutter.project_name}}/test/HelloWorld.Test/HelloWorld.Tests.csproj @@ -0,0 +1,21 @@ + + + + netcoreapp2.0 + + + + + + + + + + + + + + + + + diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/README.md new file mode 100644 index 0000000000..d6af33a924 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/README.md @@ -0,0 +1,49 @@ +# Cookiecutter SAM for golang Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless App based on Serverless Application Model (SAM). + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``\\{\\{cookiecutter.project_slug\\}\\}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-golang`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + +## Options + +Option | Description +------------------------------------------------- | --------------------------------------------------------------------------------- +`include_apigw` | Includes sample code for API Gateway Proxy integration for Lambda and a Catch All method in SAM as a starting point +`include_xray` | Includes both sample code for getting started with AWS X-Ray and adds necessary permission and `Tracing` to your function +`include_safe_deployment` | Sends by default 10% of traffic for every 1 minute to a newly deployed function using [CodeDeploy + SAM integration](https://github.com/awslabs/serverless-application-model/blob/master/docs/safe_lambda_deployments.rst) - Linear10PercentEvery1Minute +`include_experimental_make` | Includes a `Makefile` for advanced users to automate packaging, build, tests and SAM Local - Only works on OSX/Linux at the moment + +## Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) +* [Bruno Alla's Lambda function template](https://github.com/browniebroke/cookiecutter-lambda-function) + +## License + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/cookiecutter.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/cookiecutter.json new file mode 100644 index 0000000000..4ed0aa2924 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/cookiecutter.json @@ -0,0 +1,3 @@ +{ + "project_name": "Name of the project" +} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/requirements-dev.txt b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/requirements-dev.txt new file mode 100644 index 0000000000..b10c8d1048 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/requirements-dev.txt @@ -0,0 +1,4 @@ +cookiecutter==1.6.0 +flake8==3.5.0 +pytest==3.3.2 +pytest-cookies==0.3.0 diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/tests/__init__.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/tests/test_bake_project.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/tests/test_bake_project.py new file mode 100644 index 0000000000..9d32aebfe0 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/tests/test_bake_project.py @@ -0,0 +1,79 @@ +from contextlib import contextmanager + +import os +import subprocess + + +@contextmanager +def inside_dir(dirpath): + """ + Execute code from inside the given directory + :param dirpath: String, path of the directory the command is being run. + """ + old_path = os.getcwd() + try: + os.chdir(dirpath) + yield + finally: + os.chdir(old_path) + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'test_project' + + assert result.project.isdir() + assert result.project.join('README.md').isfile() + assert result.project.join('template.yaml').isfile() + assert result.project.join('hello-world').isdir() + assert result.project.join('hello-world', 'main.go').isfile() + assert result.project.join('hello-world', 'main_test.go').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('hello-world', 'main.go') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "github.com/aws/aws-lambda-go/events", + "resp, err := http.Get(DefaultHTTPGetAddress)", + "lambda.Start(handler)" + ) + + for content in contents: + assert content in app_content + + +def test_app_test_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('hello-world', 'main_test.go') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "DefaultHTTPGetAddress = \"http://127.0.0.1:12345\"", + "DefaultHTTPGetAddress = ts.URL", + "Successful Request" + ) + + for content in contents: + assert content in app_content + + +def test_app_template_content(cookies): + result = cookies.bake(extra_context={'project_name': 'test_project'}) + app_file = result.project.join('template.yaml') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "Runtime: go1.x", + "HelloWorldFunction", + ) + + for content in contents: + assert content in app_content diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/Makefile b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/Makefile new file mode 100644 index 0000000000..78a2494dba --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/Makefile @@ -0,0 +1,10 @@ +.PHONY: deps clean build + +deps: + go get -u ./... + +clean: + rm -rf ./hello-world/hello-world + +build: + GOOS=linux GOARCH=amd64 go build -o hello-world/hello-world ./hello-world \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/README.md new file mode 100644 index 0000000000..849d17bc91 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,187 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── Makefile <-- Make to automate build +├── README.md <-- This instructions file +├── hello-world <-- Source code for a lambda function +│ ├── main.go <-- Lambda function code +│ └── main_test.go <-- Unit tests +└── template.yaml +``` + +## Requirements + +* AWS CLI already configured with at least PowerUser permission +* [Docker installed](https://www.docker.com/community-edition) +* [Golang](https://golang.org) + +## Setup process + +### Installing dependencies + +In this example we use the built-in `go get` and the only dependency we need is AWS Lambda Go SDK: + +```shell +go get -u github.com/aws/aws-lambda-go/... +``` + +**NOTE:** As you change your application code as well as dependencies during development, you might want to research how to handle dependencies in Golang at scale. + +### Building + +Golang is a staticly compiled language, meaning that in order to run it you have to build the executeable target. + +You can issue the following command in a shell to build it: + +```shell +GOOS=linux GOARCH=amd64 go build -o hello-world/hello-world ./hello-world +``` + +**NOTE**: If you're not building the function on a Linux machine, you will need to specify the `GOOS` and `GOARCH` environment variables, this allows Golang to build your function for another system architecture and ensure compatability. + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda Python runtime requires a flat folder with all dependencies including the application. SAM will use `CodeUri` property to know where to look up for both application and dependencies: + +```yaml +... + FirstFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: hello_world/ + ... +``` + +First and foremost, we need a `S3 bucket` where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don't have a S3 bucket to store code artifacts then this is a good time to create one: + +```bash +aws s3 mb s3://BUCKET_NAME +``` + +Next, run the following command to package our Lambda function to S3: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME +``` + +Next, the following command will create a Cloudformation Stack and deploy your SAM resources. + +```bash +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM +``` + +> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.** + +After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL: + +```bash +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --query 'Stacks[].Outputs' +``` + +### Testing + +We use `testing` package that is built-in in Golang and you can simply run the following command to run our tests: + +```shell +go test -v ./hello-world/ +``` +# Appendix + +### Golang installation + +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install + +A quickstart way would be to use Homebrew, chocolatey or your linux package manager. + +#### Homebrew (Mac) + +Issue the following command from the terminal: + +```shell +brew install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +brew update +brew upgrade golang +``` + +#### Chocolatey (Windows) + +Issue the following command from the powershell: + +```shell +choco install golang +``` + +If it's already installed, run the following command to ensure it's the latest version: + +```shell +choco upgrade golang +``` +## AWS CLI commands + +AWS CLI commands to package, deploy and describe outputs defined within the cloudformation stack: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME + +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyParameterSample=MySampleValue + +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs' +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main.go b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main.go new file mode 100644 index 0000000000..8c105bd0ac --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "errors" + "fmt" + "io/ioutil" + "net/http" + + "github.com/aws/aws-lambda-go/events" + "github.com/aws/aws-lambda-go/lambda" +) + +var ( + // DefaultHTTPGetAddress Default Address + DefaultHTTPGetAddress = "https://checkip.amazonaws.com" + + // ErrNoIP No IP found in response + ErrNoIP = errors.New("No IP in HTTP response") + + // ErrNon200Response non 200 status code in response + ErrNon200Response = errors.New("Non 200 Response found") +) + +func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { + resp, err := http.Get(DefaultHTTPGetAddress) + if err != nil { + return events.APIGatewayProxyResponse{}, err + } + + if resp.StatusCode != 200 { + return events.APIGatewayProxyResponse{}, ErrNon200Response + } + + ip, err := ioutil.ReadAll(resp.Body) + if err != nil { + return events.APIGatewayProxyResponse{}, err + } + + if len(ip) == 0 { + return events.APIGatewayProxyResponse{}, ErrNoIP + } + + return events.APIGatewayProxyResponse{ + Body: fmt.Sprintf("Hello, %v", string(ip)), + StatusCode: 200, + }, nil +} + +func main() { + lambda.Start(handler) +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main_test.go b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main_test.go new file mode 100644 index 0000000000..bb1d2a2f1c --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/hello-world/main_test.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/aws/aws-lambda-go/events" +) + +func TestHandler(t *testing.T) { + t.Run("Unable to get IP", func(t *testing.T) { + DefaultHTTPGetAddress = "http://127.0.0.1:12345" + + _, err := handler(events.APIGatewayProxyRequest{}) + if err == nil { + t.Fatal("Error failed to trigger with an invalid request") + } + }) + + t.Run("Non 200 Response", func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(500) + })) + defer ts.Close() + + DefaultHTTPGetAddress = ts.URL + + _, err := handler(events.APIGatewayProxyRequest{}) + if err != nil && err.Error() != ErrNon200Response.Error() { + t.Fatalf("Error failed to trigger with an invalid HTTP response: %v", err) + } + }) + + t.Run("Unable decode IP", func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(500) + })) + defer ts.Close() + + DefaultHTTPGetAddress = ts.URL + + _, err := handler(events.APIGatewayProxyRequest{}) + if err == nil { + t.Fatal("Error failed to trigger with an invalid HTTP response") + } + }) + + t.Run("Successful Request", func(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(200) + fmt.Fprintf(w, "127.0.0.1") + })) + defer ts.Close() + + DefaultHTTPGetAddress = ts.URL + + _, err := handler(events.APIGatewayProxyRequest{}) + if err != nil { + t.Fatal("Everything should be ok") + } + }) +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/template.yaml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 0000000000..96d7aa160b --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-golang/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,42 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 5 + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: hello-world/ + Handler: hello-world + Runtime: go1.x + Tracing: Active # https://docs.aws.amazon.com/lambda/latest/dg/lambda-x-ray.html + Events: + CatchAll: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: GET + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + +Outputs: + HelloWorldAPI: + Description: "API Gateway endpoint URL for Prod environment for First Function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + + HelloWorldFunction: + Description: "First Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/LICENSE b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/LICENSE new file mode 100644 index 0000000000..f19aaa6d09 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/LICENSE @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/README.md new file mode 100644 index 0000000000..ec9954e48b --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/README.md @@ -0,0 +1,42 @@ +# Cookiecutter SAM for Java Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and Java. + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-java`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + + +License +------- + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/cookiecutter.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/cookiecutter.json new file mode 100644 index 0000000000..9d928e8536 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/cookiecutter.json @@ -0,0 +1,4 @@ +{ + "project_name": "Name of the project", + "runtime": "java8" +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/tests/test_cookiecutter.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/tests/test_cookiecutter.py new file mode 100644 index 0000000000..8f2a6cf519 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/tests/test_cookiecutter.py @@ -0,0 +1,41 @@ +""" + Tests cookiecutter baking process and rendered content +""" + +def test_project_tree(cookies): + result = cookies.bake(extra_context={ + 'project_name': 'hello sam' + }) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'hello sam' + assert result.project.isdir() + assert result.project.join('template.yaml').isfile() + assert result.project.join('README.md').isfile() + assert result.project.join('src').isdir() + assert result.project.join('src', 'main').isdir() + assert result.project.join('src', 'main', 'java').isdir() + assert result.project.join('src', 'main', 'java', 'helloworld').isdir() + assert result.project.join('src', 'main', 'java', 'helloworld', 'App.java').isfile() + assert result.project.join('src', 'main', 'java', 'helloworld', 'GatewayResponse.java').isfile() + assert result.project.join('src', 'test', 'java').isdir() + assert result.project.join('src', 'test', 'java', 'helloworld').isdir() + assert result.project.join('src', 'test', 'java', 'helloworld', 'AppTest.java').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'my_lambda'}) + app_file = result.project.join('src', 'main', 'java', 'helloworld', 'App.java') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "package helloword", + "class App implements RequestHandler", + "https://checkip.amazonaws.com", + "return new GatewayResponse", + "getPageContents", + ) + + for content in contents: + assert content in app_content diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/README.md new file mode 100644 index 0000000000..b95a44ac1c --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,147 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── README.md <-- This instructions file +├── pom.xml <-- Java dependencies +├── src +│ ├── main +│ │ └── java +│ │ └── helloworld <-- Source code for a lambda function +│ │ ├── App.java <-- Lambda function code +│ │ └── GatewayResponse.java <-- POJO for API Gateway Responses object +│ └── test <-- Unit tests +│ └── java +│ └── helloworld +│ └── AppTest.java +└── template.yaml +``` + +## Requirements + +* AWS CLI already configured with at least PowerUser permission +* [Java SE Development Kit 8 installed](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) +* [Docker installed](https://www.docker.com/community-edition) +* [Maven](https://maven.apache.org/install.html) + +## Setup process + +### Installing dependencies + +We use `maven` to install our dependencies and package our application into a JAR file: + +```bash +mvn package +``` +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda Java runtime accepts either a zip file or a standalone JAR file - We use the latter in this example. SAM will use `CodeUri` property to know where to look up for both application and dependencies: + +```yaml +... + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: target/HelloWorld-1.0.jar + Handler: helloworld.App::handleRequest +``` + +Firstly, we need a `S3 bucket` where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don't have a S3 bucket to store code artifacts then this is a good time to create one: + +```bash +aws s3 mb s3://BUCKET_NAME +``` + +Next, run the following command to package our Lambda function to S3: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME +``` + +Next, the following command will create a Cloudformation Stack and deploy your SAM resources. + +```bash +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM +``` + +> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.** + +After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL: + +```bash +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --query 'Stacks[].Outputs' +``` + +## Testing + +We use `JUnit` for testing our code and you can simply run the following command to run our tests: + +```bash +mvn test +``` + +# Appendix + +## AWS CLI commands + +AWS CLI commands to package, deploy and describe outputs defined within the cloudformation stack: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME + +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyParameterSample=MySampleValue + +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs' +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/pom.xml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/pom.xml new file mode 100644 index 0000000000..b0346a7f5f --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + helloworld + HelloWorld + 1.0 + jar + A sample Hello World created for SAM CLI. + + 1.8 + 1.8 + + + + + com.amazonaws + aws-lambda-java-core + 1.1.0 + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.1.1 + + + + + package + + shade + + + + + + + diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/App.java b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/App.java new file mode 100644 index 0000000000..f89a7f499d --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/App.java @@ -0,0 +1,49 @@ +package helloworld; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import java.util.StringJoiner; + +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; + +/** + * Handler for requests to Lambda function. + */ +public class App implements RequestHandler { + + public Object handleRequest(final Object input, final Context context) { + Map headers = new HashMap<>(); + headers.put("Content-Type", "application/json"); + headers.put("X-Custom-Header", "application/json"); + try { + final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); + String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); + return new GatewayResponse(output, headers, 200); + } catch (IOException e) { + return new GatewayResponse("{}", headers, 400); + } + } + + private String getPageContents(String address) throws IOException{ + BufferedReader br = null; + StringJoiner lines = new StringJoiner(System.lineSeparator()); + try { + URL url = new URL(address); + br = new BufferedReader(new InputStreamReader(url.openStream())); + String line; + while ((line = br.readLine()) != null) { + lines.add(line); + } + } finally { + if (br != null) { + br.close(); + } + } + return lines.toString(); + } +} diff --git a/samples/java/src/main/java/com/aws/codestar/projecttemplates/GatewayResponse.java b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/GatewayResponse.java similarity index 94% rename from samples/java/src/main/java/com/aws/codestar/projecttemplates/GatewayResponse.java rename to samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/GatewayResponse.java index 0d3bb005a0..ea58a79c99 100644 --- a/samples/java/src/main/java/com/aws/codestar/projecttemplates/GatewayResponse.java +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/main/java/helloworld/GatewayResponse.java @@ -1,4 +1,4 @@ -package com.aws.codestar.projecttemplates; +package helloworld; import java.util.Collections; import java.util.HashMap; diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/test/java/helloworld/AppTest.java b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/test/java/helloworld/AppTest.java new file mode 100644 index 0000000000..e64bdfc55a --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/src/test/java/helloworld/AppTest.java @@ -0,0 +1,21 @@ +package helloworld; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +public class AppTest { + @Test + public void successfulResponse() { + App app = new App(); + GatewayResponse result = (GatewayResponse) app.handleRequest(null, null); + assertEquals(result.getStatusCode(), 200); + assertEquals(result.getHeaders().get("Content-Type"), "application/json"); + String content = result.getBody(); + assertNotNull(content); + assertTrue(content.contains("\"message\"")); + assertTrue(content.contains("\"hello world\"")); + assertTrue(content.contains("\"location\"")); + } +} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/template.yaml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 0000000000..bd687f3e32 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-java/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,44 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 20 + + +Resources: + + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: target/HelloWorld-1.0.jar + Handler: helloworld.App::handleRequest + Runtime: java8 + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + +Outputs: + + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/.gitignore new file mode 100644 index 0000000000..74ea25e0e5 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/.gitignore @@ -0,0 +1,168 @@ + +# Created by https://www.gitignore.io/api/osx,linux,python,windows + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,linux,python,windows \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/LICENSE b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/LICENSE new file mode 100644 index 0000000000..f19aaa6d09 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/LICENSE @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/Pipfile b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/Pipfile new file mode 100644 index 0000000000..a22660daae --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/Pipfile @@ -0,0 +1,13 @@ +[[source]] + +url = "https://pypi.python.org/simple" +verify_ssl = true +name = "pypi" + +[packages] + +[dev-packages] + +cookiecutter = "*" +pytest-cookies = "*" +pytest = "*" diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/README.md new file mode 100644 index 0000000000..4644aac6bf --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/README.md @@ -0,0 +1,42 @@ +# Cookiecutter SAM for Node Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and NodeJS. + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-nodejs`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + + +License +------- + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/cookiecutter.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/cookiecutter.json new file mode 100644 index 0000000000..1462701ea8 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/cookiecutter.json @@ -0,0 +1,4 @@ +{ + "project_name": "Name of the project", + "runtime": "nodejs8.10" +} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/setup.cfg b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/setup.cfg new file mode 100644 index 0000000000..eee4ab11a7 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/setup.cfg @@ -0,0 +1,2 @@ +[install] +prefix= \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/tests/test_cookiecutter.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/tests/test_cookiecutter.py new file mode 100644 index 0000000000..cd70e453ff --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/tests/test_cookiecutter.py @@ -0,0 +1,41 @@ +""" + Tests cookiecutter baking process and rendered content +""" + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={ + 'project_name': 'hello sam' + }) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'hello sam' + assert result.project.isdir() + assert result.project.join('.gitignore').isfile() + assert result.project.join('template.yaml').isfile() + assert result.project.join('README.md').isfile() + assert result.project.join('hello_world').isdir() + assert result.project.join('hello_world', 'app.js').isfile() + assert result.project.join('hello_world', 'package.json').isfile() + assert result.project.join('hello_world', 'yarn.lock').isfile() + assert result.project.join('hello_world', 'tests').isdir() + assert result.project.join('hello_world', 'tests', 'unit', 'test.spec.js').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'my_lambda'}) + app_file = result.project.join('hello_world', 'app.js') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "const axios", + "JSON.stringify", + "location", + "message", + "hello world", + "statusCode" + ) + + for content in contents: + assert content in app_content diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/.gitignore new file mode 100644 index 0000000000..eb1db5fbec --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/.gitignore @@ -0,0 +1,129 @@ + +# Created by https://www.gitignore.io/api/osx,node,linux,windows + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### Node ### +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,node,linux,windows \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/README.md new file mode 100644 index 0000000000..181cfcd428 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,153 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── README.md <-- This instructions file +├── hello_world <-- Source code for a lambda function +│ ├── app.js <-- Lambda function code +│ ├── package.json <-- NodeJS dependencies +│ └── tests <-- Unit tests +│ └── unit +│ └── test_handler.js +└── template.yaml <-- SAM template +``` + +## Requirements + +* AWS CLI already configured with at least PowerUser permission +{%- if cookiecutter.runtime == 'nodejs6.10' %} +* [NodeJS 6.10 installed](https://nodejs.org/en/download/releases/) +{%- elif cookiecutter.runtime =='nodejs4.3' %} +* [NodeJS 4.3 installed](https://nodejs.org/en/download/releases/) +{%- else %} +* [NodeJS 8.10+ installed](https://nodejs.org/en/download/) +{%- endif %} +* [Docker installed](https://www.docker.com/community-edition) + +## Setup process + +### Installing dependencies + +In this example we use `npm` but you can use `yarn` if you prefer to manage NodeJS dependencies: + +```bash +cd hello_world +npm install +cd ../ +``` + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda NodeJS runtime requires a flat folder with all dependencies including the application. SAM will use `CodeUri` property to know where to look up for both application and dependencies: + +```yaml +... + FirstFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: hello_world/ + ... +``` + +Firstly, we need a `S3 bucket` where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don't have a S3 bucket to store code artifacts then this is a good time to create one: + +```bash +aws s3 mb s3://BUCKET_NAME +``` + +Next, run the following command to package our Lambda function to S3: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME +``` + +Next, the following command will create a Cloudformation Stack and deploy your SAM resources. + +```bash +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM +``` + +> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.** + +After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL: + +```bash +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --query 'Stacks[].Outputs' +``` + +## Testing + +We use `jest` for testing our code and it is already added in `package.json` under `scripts`, so that we can simply run the following command to run our tests: + +```bash +cd hello_world +npm run test +``` + +# Appendix + +## AWS CLI commands + +AWS CLI commands to package, deploy and describe outputs defined within the cloudformation stack: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME + +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyParameterSample=MySampleValue + +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs' +``` + +**NOTE**: Alternatively this could be part of package.json scripts section. + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/app.js b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/app.js new file mode 100644 index 0000000000..e56ef07f4a --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/app.js @@ -0,0 +1,48 @@ +{%- if cookiecutter.runtime == 'nodejs4.3' %} +var axios = require('axios') +var url = 'http://checkip.amazonaws.com/'; +var response; +{%- else %} +const axios = require('axios') +const url = 'http://checkip.amazonaws.com/'; +let response; +{%- endif %} + +{% if cookiecutter.runtime == 'nodejs6.10' or cookiecutter.runtime == 'nodejs4.3' %} +exports.lambda_handler = function (event, context, callback) { + axios(url) + .then(function (ret) { + response = { + 'statusCode': 200, + 'body': JSON.stringify({ + message: 'hello world', + location: ret.data.trim() + }) + } + callback(null, response); + }) + .catch(function (err) { + console.log(err); + callback(err, ""); + }); +}; +{% else %} +exports.lambda_handler = async (event, context, callback) => { + try { + const ret = await axios(url); + response = { + 'statusCode': 200, + 'body': JSON.stringify({ + message: 'hello world', + location: ret.data.trim() + }) + } + } + catch (err) { + console.log(err); + callback(err, null); + } + + callback(null, response) +}; +{% endif %} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/package.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/package.json new file mode 100644 index 0000000000..1c0951db9a --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/package.json @@ -0,0 +1,19 @@ +{ + "name": "hello_world", + "version": "1.0.0", + "description": "hello world sample for NodeJS", + "main": "src/index.js", + "repository": "https://github.com/aws-samples/cookiecutter-aws-sam-hello-nodejs", + "author": "SAM CLI", + "license": "MIT", + "dependencies": { + "axios": "^0.18.0" + }, + "scripts": { + "test": "mocha tests/unit/" + }, + "devDependencies": { + "chai": "^4.1.2", + "mocha": "^5.1.1" + } +} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/tests/unit/test_handler.js b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/tests/unit/test_handler.js new file mode 100644 index 0000000000..ef45ec8035 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/hello_world/tests/unit/test_handler.js @@ -0,0 +1,45 @@ +'use strict'; + +const app = require('../../app.js'); +const chai = require('chai'); +const expect = chai.expect; +var event, context; + +{% if cookiecutter.runtime == 'nodejs6.10' or cookiecutter.runtime == 'nodejs4.3' %} +describe('Tests Handler', function () { + it('verifies successful response', function (done) { + app.lambda_handler(event, context, function (err, result) { + try { + expect(result).to.be.an('object'); + expect(result.statusCode).to.equal(200); + expect(result.body).to.be.an('string'); + + let response = JSON.parse(result.body); + + expect(response).to.be.an('object'); + expect(response.message).to.be.equal("hello world"); + expect(response.location).to.be.an("string"); + done(); + } catch (e) { + done(e); + } + }); + }); +}); +{% else %} +describe('Tests index', function () { + it('verifies successful response', async () => { + const result = await app.lambda_handler(event, context, (err, result) => { + expect(result).to.be.an('object'); + expect(result.statusCode).to.equal(200); + expect(result.body).to.be.an('string'); + + let response = JSON.parse(result.body); + + expect(response).to.be.an('object'); + expect(response.message).to.be.equal("hello world"); + expect(response.location).to.be.an("string"); + }); + }); +}); +{% endif %} diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/template.yaml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 0000000000..bae7593a3d --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,50 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 3 + + +Resources: + + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: hello_world/ + Handler: app.lambda_handler + {%- if cookiecutter.runtime == 'nodejs6.10' %} + Runtime: nodejs6.10 + {%- elif cookiecutter.runtime =='nodejs4.3' %} + Runtime: nodejs4.3 + {%- else %} + Runtime: nodejs8.10 + {%- endif %} + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + +Outputs: + + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/.gitignore new file mode 100644 index 0000000000..74ea25e0e5 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/.gitignore @@ -0,0 +1,168 @@ + +# Created by https://www.gitignore.io/api/osx,linux,python,windows + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/osx,linux,python,windows \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/LICENSE b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/LICENSE new file mode 100644 index 0000000000..f19aaa6d09 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/LICENSE @@ -0,0 +1,14 @@ +MIT No Attribution + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/Pipfile b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/Pipfile new file mode 100644 index 0000000000..a22660daae --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/Pipfile @@ -0,0 +1,13 @@ +[[source]] + +url = "https://pypi.python.org/simple" +verify_ssl = true +name = "pypi" + +[packages] + +[dev-packages] + +cookiecutter = "*" +pytest-cookies = "*" +pytest = "*" diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/README.md new file mode 100644 index 0000000000..1b5721f31b --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/README.md @@ -0,0 +1,42 @@ +# Cookiecutter SAM for Python Lambda functions + +This is a [Cookiecutter](https://github.com/audreyr/cookiecutter) template to create a Serverless Hello World App based on Serverless Application Model (SAM) and Python. + +It is important to note that you should not try to `git clone` this project but use `cookiecutter` CLI instead as ``{{cookiecutter.project_name}}`` will be rendered based on your input and therefore all variables and files will be rendered properly. + +## Requirements + +Install `cookiecutter` command line: + +**Pip users**: + +* `pip install cookiecutter` + +**Homebrew users**: + +* `brew install cookiecutter` + +**Windows or Pipenv users**: + +* `pipenv install cookiecutter` + +**NOTE**: [`Pipenv`](https://github.com/pypa/pipenv) is the new and recommended Python packaging tool that works across multiple platforms and makes Windows a first-class citizen. + +## Usage + +Generate a new SAM based Serverless App: `cookiecutter gh:aws-samples/cookiecutter-aws-sam-hello-python`. + +You'll be prompted a few questions to help this cookiecutter template to scaffold this project and after its completed you should see a new folder at your current path with the name of the project you gave as input. + +**NOTE**: After you understand how cookiecutter works (cookiecutter.json, mainly), you can fork this repo and apply your own mechanisms to accelerate your development process and this can be followed for any programming language and OS. + + +# Credits + +* This project has been generated with [Cookiecutter](https://github.com/audreyr/cookiecutter) + + +License +------- + +This project is licensed under the terms of the [MIT License with no attribution](/LICENSE) diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/cookiecutter.json b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/cookiecutter.json new file mode 100644 index 0000000000..1b996b510e --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/cookiecutter.json @@ -0,0 +1,4 @@ +{ + "project_name": "Name of the project", + "runtime": "python3.6" +} \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/setup.cfg b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/setup.cfg new file mode 100644 index 0000000000..eee4ab11a7 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/setup.cfg @@ -0,0 +1,2 @@ +[install] +prefix= \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/tests/test_cookiecutter.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/tests/test_cookiecutter.py new file mode 100644 index 0000000000..361b9f2d02 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/tests/test_cookiecutter.py @@ -0,0 +1,42 @@ +""" + Tests cookiecutter baking process and rendered content +""" + + +def test_project_tree(cookies): + result = cookies.bake(extra_context={ + 'project_name': 'hello sam' + }) + assert result.exit_code == 0 + assert result.exception is None + assert result.project.basename == 'hello sam' + assert result.project.isdir() + assert result.project.join('requirements.txt').isfile() + assert result.project.join('.gitignore').isfile() + assert result.project.join('template.yaml').isfile() + assert result.project.join('README.md').isfile() + assert result.project.join('hello_world').isdir() + assert result.project.join('hello_world', 'app.py').isfile() + assert result.project.join('hello_world', '__init__.py').isfile() + assert result.project.join('tests').isdir() + assert result.project.join('tests', 'unit', '__init__.py').isfile() + assert result.project.join('tests', 'unit', 'test_handler.py').isfile() + + +def test_app_content(cookies): + result = cookies.bake(extra_context={'project_name': 'my_lambda'}) + app_file = result.project.join('hello_world', 'app.py') + app_content = app_file.readlines() + app_content = ''.join(app_content) + + contents = ( + "import requests", + "Sample pure Lambda function", + "location", + "message", + "hello world", + "statusCode" + ) + + for content in contents: + assert content in app_content diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/.gitignore b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/.gitignore new file mode 100644 index 0000000000..4808264dbf --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/.gitignore @@ -0,0 +1,244 @@ + +# Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Ruby plugin and RubyMine +/.rakeTasks + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Build folder + +*/build/* + +# End of https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode \ No newline at end of file diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/README.md b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/README.md new file mode 100644 index 0000000000..097e180ca9 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/README.md @@ -0,0 +1,190 @@ +# {{ cookiecutter.project_name }} + +This is a sample template for {{ cookiecutter.project_name }} - Below is a brief explanation of what we have generated for you: + +```bash +. +├── README.md <-- This instructions file +├── hello_world <-- Source code for a lambda function +│ ├── __init__.py +│ └── app.py <-- Lambda function code +├── requirements.txt <-- Python dependencies +├── template.yaml <-- SAM template +└── tests <-- Unit tests + └── unit + ├── __init__.py + └── test_handler.py +``` + +## Requirements + +* AWS CLI already configured with at least PowerUser permission +{%- if cookiecutter.runtime == 'python3.6' %} +* [Python 3 installed](https://www.python.org/downloads/) +{%- else %} +* [Python 2.7 installed](https://www.python.org/downloads/) +{%- endif %} +* [Docker installed](https://www.docker.com/community-edition) +* [Python Virtual Environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/) + +## Setup process + +### Installing dependencies + +[AWS Lambda requires a flat folder](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html) with the application as well as its dependencies. Therefore, we need to have a 2 step process in order to enable local testing as well as packaging/deployment later on - This consist of two commands you can run as follows: + +```bash +pip install -r requirements.txt -t hello_world/build/ +cp hello_world/*.py hello_world/build/ +``` + +1. Step 1 install our dependencies into ``build`` folder +2. Step 2 copies our application into ``build`` folder + +**NOTE:** As you change your application code as well as dependencies during development you'll need to make sure these steps are repated in order to execute your Lambda and/or API Gateway locally. + +### Local development + +**Invoking function locally through local API Gateway** + +```bash +sam local start-api +``` + +If the previous command ran successfully you should now be able to hit the following local endpoint to invoke your function `http://localhost:3000/hello` + +**SAM CLI** is used to emulate both Lambda and API Gateway locally and uses our `template.yaml` to understand how to bootstrap this environment (runtime, where the source code is, etc.) - The following excerpt is what the CLI will read in order to initialize an API and its routes: + +```yaml +... +Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get +``` + +## Packaging and deployment + +AWS Lambda Python runtime requires a flat folder with all dependencies including the application. SAM will use `CodeUri` property to know where to look up for both application and dependencies: + +```yaml +... + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + CodeUri: hello_world/ + ... +``` + +Firstly, we need a `S3 bucket` where we can upload our Lambda functions packaged as ZIP before we deploy anything - If you don't have a S3 bucket to store code artifacts then this is a good time to create one: + +```bash +aws s3 mb s3://BUCKET_NAME +``` + +Next, run the following command to package our Lambda function to S3: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME +``` + +Next, the following command will create a Cloudformation Stack and deploy your SAM resources. + +```bash +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM +``` + +> **See [Serverless Application Model (SAM) HOWTO Guide](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md) for more details in how to get started.** + +After deployment is complete you can run the following command to retrieve the API Gateway Endpoint URL: + +```bash +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --query 'Stacks[].Outputs' +``` + +## Testing + +We use **Pytest** for testing our code and you can install it using pip: ``pip install pytest`` + +Next, we run `pytest` against our `tests` folder to run our initial unit tests: + +```bash +python -m pytest tests/ -v +``` + +**NOTE**: It is recommended to use a Python Virtual environment to separate your application development from your system Python installation. + +# Appendix + +### Python Virtual environment + +{%- if cookiecutter.runtime == 'python3.6' %} +**In case you're new to this**, python3 comes with `virtualenv` library by default so you can simply run the following: + +1. Create a new virtual environment +2. Install dependencies in the new virtual environment + +```bash +python3 -m venv .venv +. .venv/bin/activate +pip install -r requirements.txt +``` +{%- else %} +**In case you're new to this**, python2 `virtualenv` module is not available in the standard library so we need to install it and then we can install our dependencies: + +1. Create a new virtual environment +2. Install dependencies in the new virtual environment + +```bash +pip install virtualenv +virtualenv .venv +. .venv/bin/activate +pip install -r requirements.txt +``` +{%- endif %} + + +**NOTE:** You can find more information about Virtual Environment at [Python Official Docs here](https://docs.python.org/3/tutorial/venv.html). Alternatively, you may want to look at [Pipenv](https://github.com/pypa/pipenv) as the new way of setting up development workflows +## AWS CLI commands + +AWS CLI commands to package, deploy and describe outputs defined within the cloudformation stack: + +```bash +sam package \ + --template-file template.yaml \ + --output-template-file packaged.yaml \ + --s3-bucket REPLACE_THIS_WITH_YOUR_S3_BUCKET_NAME + +sam deploy \ + --template-file packaged.yaml \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} \ + --capabilities CAPABILITY_IAM \ + --parameter-overrides MyParameterSample=MySampleValue + +aws cloudformation describe-stacks \ + --stack-name {{ cookiecutter.project_name.lower().replace(' ', '-') }} --query 'Stacks[].Outputs' +``` + +## Bringing to the next level + +Here are a few ideas that you can use to get more acquainted as to how this overall process works: + +* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Update unit test to capture that +* Package & Deploy + +Next, you can use the following resources to know more about beyond hello world samples and how others structure their Serverless applications: + +* [AWS Serverless Application Repository](https://aws.amazon.com/serverless/serverlessrepo/) +* [Chalice Python Serverless framework](https://github.com/aws/chalice) +* Sample Python with 3rd party dependencies, pipenv and Makefile: ``sam init --location https://github.com/aws-samples/cookiecutter-aws-sam-python`` diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/hello_world/__init__.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/hello_world/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/hello_world/app.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/hello_world/app.py new file mode 100644 index 0000000000..741d41760c --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/hello_world/app.py @@ -0,0 +1,25 @@ +import json + +import requests + + +def lambda_handler(event, context): + """Sample pure Lambda function + + Arguments: + event LambdaEvent -- Lambda Event received from Invoke API + context LambdaContext -- Lambda Context runtime methods and attributes + + Returns: + dict -- {'statusCode': int, 'body': dict} + """ + + ip = requests.get('http://checkip.amazonaws.com/') + + return { + "statusCode": 200, + "body": json.dumps({ + 'message': 'hello world', + 'location': ip.text.replace('\n', ''), + }) + } diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/requirements.txt b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/requirements.txt new file mode 100644 index 0000000000..271baf7e23 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/requirements.txt @@ -0,0 +1 @@ +requests==2.18.4 diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/template.yaml b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/template.yaml new file mode 100644 index 0000000000..c45a873c21 --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/template.yaml @@ -0,0 +1,48 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + {{ cookiecutter.project_name }} + + Sample SAM Template for {{ cookiecutter.project_name }} + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 3 + + +Resources: + + HelloWorldFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: hello_world/build/ + Handler: app.lambda_handler + {%- if cookiecutter.runtime == 'python3.6' %} + Runtime: python3.6 + {%- else %} + Runtime: python2.7 + {%- endif %} + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Events: + HelloWorld: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + +Outputs: + + HelloWorldApi: + Description: "API Gateway endpoint URL for Prod stage for Hello World function" + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/" + + HelloWorldFunction: + Description: "Hello World Lambda Function ARN" + Value: !GetAtt HelloWorldFunction.Arn + + HelloWorldFunctionIamRole: + Description: "Implicit IAM Role created for Hello World function" + Value: !GetAtt HelloWorldFunctionRole.Arn diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/tests/unit/__init__.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/tests/unit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/tests/unit/test_handler.py b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/tests/unit/test_handler.py new file mode 100644 index 0000000000..522935a3ce --- /dev/null +++ b/samcli/local/init/templates/cookiecutter-aws-sam-hello-python/{{cookiecutter.project_name}}/tests/unit/test_handler.py @@ -0,0 +1,96 @@ +import json +import pytest +from hello_world import app + + +@pytest.fixture() +def apigw_event(): + """ Generates API GW Event""" + + return { + "body": "{ \"test\": \"body\"}", + "resource": "/{proxy+}", + "requestContext": { + "resourceId": "123456", + "apiId": "1234567890", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "accountId": "123456789012", + "identity": { + "apiKey": "", + "userArn": "", + "cognitoAuthenticationType": "", + "caller": "", + "userAgent": "Custom User Agent String", + "user": "", + "cognitoIdentityPoolId": "", + "cognitoIdentityId": "", + "cognitoAuthenticationProvider": "", + "sourceIp": "127.0.0.1", + "accountId": "" + }, + "stage": "prod" + }, + "queryStringParameters": { + "foo": "bar" + }, + "headers": { + "Via": + "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "Accept-Language": + "en-US,en;q=0.8", + "CloudFront-Is-Desktop-Viewer": + "true", + "CloudFront-Is-SmartTV-Viewer": + "false", + "CloudFront-Is-Mobile-Viewer": + "false", + "X-Forwarded-For": + "127.0.0.1, 127.0.0.2", + "CloudFront-Viewer-Country": + "US", + "Accept": + "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Upgrade-Insecure-Requests": + "1", + "X-Forwarded-Port": + "443", + "Host": + "1234567890.execute-api.us-east-1.amazonaws.com", + "X-Forwarded-Proto": + "https", + "X-Amz-Cf-Id": + "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==", + "CloudFront-Is-Tablet-Viewer": + "false", + "Cache-Control": + "max-age=0", + "User-Agent": + "Custom User Agent String", + "CloudFront-Forwarded-Proto": + "https", + "Accept-Encoding": + "gzip, deflate, sdch" + }, + "pathParameters": { + "proxy": "/examplepath" + }, + "httpMethod": "POST", + "stageVariables": { + "baz": "qux" + }, + "path": "/examplepath" + } + + +def test_lambda_handler(apigw_event): + + ret = app.lambda_handler(apigw_event, "") + assert ret['statusCode'] == 200 + + for key in ('message', 'location'): + assert key in ret['body'] + + data = json.loads(ret['body']) + assert data['message'] == 'hello world' diff --git a/samcli/local/lambdafn/__init__.py b/samcli/local/lambdafn/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/samcli/local/lambdafn/config.py b/samcli/local/lambdafn/config.py new file mode 100644 index 0000000000..a1194a0141 --- /dev/null +++ b/samcli/local/lambdafn/config.py @@ -0,0 +1,52 @@ +""" +Lambda Function configuration data required by the runtime +""" + +from .env_vars import EnvironmentVariables + + +class FunctionConfig(object): + """ + Data class to store function configuration. This class is a flavor of function configuration passed to + AWS Lambda APIs on the cloud. It is limited to properties that make sense in a local testing environment. + """ + + _DEFAULT_TIMEOUT_SECONDS = 3 + _DEFAULT_MEMORY = 128 + + def __init__(self, + name, + runtime, + handler, + code_abs_path, + memory=None, + timeout=None, + env_vars=None): + """ + Initialize the class. + + :param string name: Name of the function + :param string runtime: Runtime of function + :param string handler: Handler method + :param string code_abs_path: Absolute path to the code + :param integer memory: Function memory limit in MB + :param integer timeout: Function timeout in seconds + :param samcli.local.lambdafn.env_vars.EnvironmentVariables env_vars: Optional, Environment variables. + If it not provided, this class will generate one for you based on the function properties + """ + + self.name = name + self.runtime = runtime + self.handler = handler + self.code_abs_path = code_abs_path + self.memory = memory or self._DEFAULT_MEMORY + self.timeout = timeout or self._DEFAULT_TIMEOUT_SECONDS + + if not env_vars: + env_vars = EnvironmentVariables(self.memory, self.timeout, self.handler) + + self.env_vars = env_vars + # Re-apply memory & timeout because those could have been set to default values + self.env_vars.handler = self.handler + self.env_vars.memory = self.memory + self.env_vars.timeout = self.timeout diff --git a/samcli/local/lambdafn/env_vars.py b/samcli/local/lambdafn/env_vars.py new file mode 100644 index 0000000000..6badb4b027 --- /dev/null +++ b/samcli/local/lambdafn/env_vars.py @@ -0,0 +1,197 @@ +""" +Supplies the environment variables necessary to set up Local Lambda runtime +""" + + +class EnvironmentVariables(object): + """ + Use this class to get the environment variables necessary to run the Lambda function. It returns the AWS specific + variables (credentials, regions, etc) along with any environment variables configured on the function. + + Customers define the name of the environment variables along with default values, if any, when creating the + function. In order to test the function with different scenarios, customers can override values for some of the + variables. This class supports three mechanisms of providing values to environment variables. + If a variable is given a value through all the three mechanisms, then the value from higher priority will be used: + + Priority (Highest to Lowest): + - Override Values - User specified these + - Shell Environment Values - Came from the shell environment + - Default Values - Hard coded values + + If a variable does *not* get a value from either of the above mechanisms, it is given a value of "" (empty string). + If the value of a variable is an intrinsic function dict/list, then it is given a value of "" (empty string). + + If real AWS Credentials were supplied, this class will expose them through appropriate environment variables. + If not, this class will provide the following placeholder values to AWS Credentials: + region = "us-east-1" + key = "defaultkey" + secret = "defaultsecret" + """ + + _BLANK_VALUE = "" + _DEFAULT_AWS_CREDS = { + "region": "us-east-1", + "key": "defaultkey", + "secret": "defaultsecret" + } + + def __init__(self, + function_memory=None, + function_timeout=None, + function_handler=None, + variables=None, + shell_env_values=None, + override_values=None, + aws_creds=None): + """ + Initializes this class. It takes in two sets of properties: + a) (Required) Function information + b) (Optional) Environment variable configured on the function + + :param integer function_memory: Memory size of the function in megabytes + :param integer function_timeout: Function's timeout in seconds + :param string function_handler: Handler of the function + :param dict variables: Optional. Dict whose key is the environment variable names and value is the default + values for the variable. + :param dict shell_env_values: Optional. Dict containing values for the variables grabbed from the shell's + environment. + :param dict override_values: Optional. Dict containing values for the variables that will override the values + from ``default_values`` and ``shell_env_values``. + :param dict aws_creds: Optional. Dictionary containing AWS credentials passed to the Lambda runtime through + environment variables. It should contain "key", "secret", "region" and optional "sessiontoken" keys + """ + + self._function = { + "memory": function_memory, + "timeout": function_timeout, + "handler": function_handler + } + + self.variables = variables or {} + self.shell_env_values = shell_env_values or {} + self.override_values = override_values or {} + self.aws_creds = aws_creds or {} + + def resolve(self): + """ + Resolves the values from different sources and returns a dict of environment variables to use when running + the function locally. + + :return dict: Dict where key is the variable name and value is the value of the variable. Both key and values + are strings + """ + + # AWS_* variables must always be passed to the function, but user has the choice to override them + result = self._get_aws_variables() + + # Default value for the variable gets lowest priority + for name, value in self.variables.items(): + + # Shell environment values, second priority + if name in self.shell_env_values: + value = self.shell_env_values[name] + + # Overridden values, highest priority + if name in self.override_values: + value = self.override_values[name] + + # Any value must be a string when passed to Lambda runtime. + # Runtime expects a Map for environment variables + result[name] = self._stringify_value(value) + + return result + + def add_lambda_event_body(self, value): + """ + Adds the value of AWS_LAMBDA_EVENT_BODY environment variable. + """ + self.variables["AWS_LAMBDA_EVENT_BODY"] = value + + @property + def timeout(self): + return self._function["timeout"] + + @timeout.setter + def timeout(self, value): + self._function["timeout"] = value + + @property + def memory(self): + return self._function["memory"] + + @memory.setter + def memory(self, value): + self._function["memory"] = value + + @property + def handler(self): + return self._function["handler"] + + @handler.setter + def handler(self, value): + self._function["handler"] = value + + def _get_aws_variables(self): + """ + Returns the AWS specific environment variables that should be available in the Lambda runtime. + They are prefixed it "AWS_*". + + :return dict: Name and value of AWS environment variable + """ + + result = { + # Variable that says this function is running in Local Lambda + "AWS_SAM_LOCAL": "true", + + # Function configuration + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": str(self.memory), + "AWS_LAMBDA_FUNCTION_TIMEOUT": str(self.timeout), + "AWS_LAMBDA_FUNCTION_HANDLER": str(self._function["handler"]), + + # AWS Credentials - Use the input credentials or use the defaults + "AWS_REGION": self.aws_creds.get("region", self._DEFAULT_AWS_CREDS["region"]), + + "AWS_DEFAULT_REGION": self.aws_creds.get("region", self._DEFAULT_AWS_CREDS["region"]), + + "AWS_ACCESS_KEY_ID": self.aws_creds.get("key", self._DEFAULT_AWS_CREDS["key"]), + + "AWS_SECRET_ACCESS_KEY": self.aws_creds.get("secret", self._DEFAULT_AWS_CREDS["secret"]) + + # Additional variables we don't fill in + # "AWS_ACCOUNT_ID=" + # "AWS_LAMBDA_EVENT_BODY=", + # "AWS_LAMBDA_FUNCTION_NAME=", + # "AWS_LAMBDA_FUNCTION_VERSION=", + } + + # Session Token should be added **only** if the input creds have a token and the value is not empty. + if self.aws_creds.get("sessiontoken"): + result["AWS_SESSION_TOKEN"] = self.aws_creds.get("sessiontoken") + + return result + + def _stringify_value(self, value): + """ + This method stringifies values of environment variables. If the value of the method is a list or dictionary, + then this method will replace it with empty string. Values of environment variables in Lambda must be a string. + List or dictionary usually means they are intrinsic functions which have not been resolved. + + :param value: Value to stringify + :return string: Stringified value + """ + + # List/dict/None values are replaced with a blank + if isinstance(value, (dict, list, tuple)) or value is None: + result = self._BLANK_VALUE + + # str(True) will output "True". To maintain backwards compatibility we need to output "true" or "false" + elif value is True: + result = "true" + elif value is False: + result = "false" + + # value is a scalar type like int, str which can be stringified + else: + result = str(value) + + return result diff --git a/samcli/local/lambdafn/exceptions.py b/samcli/local/lambdafn/exceptions.py new file mode 100644 index 0000000000..f99ff10404 --- /dev/null +++ b/samcli/local/lambdafn/exceptions.py @@ -0,0 +1,10 @@ +""" +Custom exception used by Local Lambda execution +""" + + +class FunctionNotFound(Exception): + """ + Raised when the requested Lambda function is not found + """ + pass diff --git a/samcli/local/lambdafn/runtime.py b/samcli/local/lambdafn/runtime.py new file mode 100644 index 0000000000..88a3b02806 --- /dev/null +++ b/samcli/local/lambdafn/runtime.py @@ -0,0 +1,200 @@ +""" +Classes representing a local Lambda runtime +""" + +import os +import shutil +import zipfile +import tempfile +import signal +import logging +import threading +from contextlib import contextmanager + +from samcli.local.docker.lambda_container import LambdaContainer + +LOG = logging.getLogger(__name__) + + +class LambdaRuntime(object): + """ + This class represents a Local Lambda runtime. It can run the Lambda function code locally in a Docker container + and return results. Public methods exposed by this class are similar to the AWS Lambda APIs, for convenience only. + This class is **not** intended to be an local replica of the Lambda APIs. + """ + + SUPPORTED_ARCHIVE_EXTENSIONS = (".zip", ".jar", ".ZIP", ".JAR") + + def __init__(self, container_manager): + """ + Initialize the Local Lambda runtime + + :param samcli.local.docker.manager.ContainerManager container_manager: Instance of the ContainerManager class + that can run a local Docker container + """ + self._container_manager = container_manager + + def invoke(self, + function_config, + event, + debug_port=None, + debug_args=None, + stdout=None, + stderr=None): + """ + Invoke the given Lambda function locally. + + ##### NOTE: THIS IS A LONG BLOCKING CALL ##### + This method will block until either the Lambda function completes or timed out, which could be seconds. + A blocking call will block the thread preventing any other operations from happening. If you are using this + method in a web-server or in contexts where your application needs to be responsive when function is running, + take care to invoke the function in a separate thread. Co-Routines or micro-threads might not perform well + because the underlying implementation essentially blocks on a socket, which is synchronous. + + :param FunctionConfig function_config: Configuration of the function to invoke + :param event: String input event passed to Lambda function + :param integer debug_port: Optional, port to attach debugger to + :param string debug_args: Optional, additional args to pass to debugger + :param io.IOBase stdout: Optional. IO Stream to that receives stdout text from container. + :param io.IOBase stderr: Optional. IO Stream that receives stderr text from container + :raises Keyboard + """ + timer = None + + # Update with event input + environ = function_config.env_vars + environ.add_lambda_event_body(event) + # Generate a dictionary of environment variable key:values + env_vars = environ.resolve() + + with self._get_code_dir(function_config.code_abs_path) as code_dir: + + container = LambdaContainer(function_config.runtime, + function_config.handler, + code_dir, + memory_mb=function_config.memory, + env_vars=env_vars, + debug_port=debug_port, + debug_args=debug_args) + + try: + + # Start the container. This call returns immediately after the container starts + self._container_manager.run(container) + + # Setup appropriate interrupt - timeout or Ctrl+C - before function starts executing. + # + # Start the timer **after** container starts. Container startup takes several seconds, only after which, + # our Lambda function code will run. Starting the timer is a reasonable approximation that function has + # started running. + timer = self._configure_interrupt(function_config.name, + function_config.timeout, + container, + bool(debug_port)) + + # NOTE: BLOCKING METHOD + # Block the thread waiting to fetch logs from the container. This method will return after container + # terminates, either successfully or killed by one of the interrupt handlers above. + container.wait_for_logs(stdout=stdout, stderr=stderr) + + except KeyboardInterrupt: + # When user presses Ctrl+C, we receive a Keyboard Interrupt. This is especially very common when + # container is in debugging mode. We have special handling of Ctrl+C. So handle KeyboardInterrupt + # and swallow the exception. The ``finally`` block will also take care of cleaning it up. + LOG.debug("Ctrl+C was pressed. Aborting Lambda execution") + + finally: + # We will be done with execution, if either the execution completed or an interrupt was fired + # Any case, cleanup the timer and container. + # + # If we are in debugging mode, timer would not be created. So skip cleanup of the timer + if timer: + timer.cancel() + self._container_manager.stop(container) + + def _configure_interrupt(self, function_name, timeout, container, is_debugging): + """ + When a Lambda function is executing, we setup certain interrupt handlers to stop the execution. + Usually, we setup a function timeout interrupt to kill the container after timeout expires. If debugging though, + we don't enforce a timeout. But we setup a SIGINT interrupt to catch Ctrl+C and terminate the container. + + :param string function_name: Name of the function we are running + :param integer timeout: Timeout in seconds + :param samcli.local.docker.container.Container container: Instance of a container to terminate + :param bool is_debugging: Are we debugging? + :return threading.Timer: Timer object, if we setup a timer. None otherwise + """ + + def timer_handler(): + # NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures + LOG.info("Function '%s' timed out after %d seconds", function_name, timeout) + self._container_manager.stop(container) + + def signal_handler(sig, frame): + # NOTE: This handler runs in a separate thread. So don't try to mutate any non-thread-safe data structures + LOG.info("Execution of function %s was interrupted", function_name) + self._container_manager.stop(container) + + if is_debugging: + LOG.debug("Setting up SIGTERM interrupt handler") + signal.signal(signal.SIGTERM, signal_handler) + else: + # Start a timer, we'll use this to abort the function if it runs beyond the specified timeout + LOG.debug("Starting a timer for %s seconds for function '%s'", timeout, function_name) + timer = threading.Timer(timeout, timer_handler, ()) + timer.start() + return timer + + @contextmanager + def _get_code_dir(self, code_path): + """ + Method to get a path to a directory where the Lambda function code is available. This directory will + be mounted directly inside the Docker container. + + This method handles a few different cases for ``code_path``: + - ``code_path``is a existent zip/jar file: Unzip in a temp directory and return the temp directory + - ``code_path`` is a existent directory: Return this immediately + - ``code_path`` is a file/dir that does not exist: Return it as is. May be this method is not clever to + detect the existence of the path + + :param string code_path: Path to the code. This could be pointing at a file or folder either on a local + disk or in some network file system + :return string: Directory containing Lambda function code. It can be mounted directly in container + """ + + decompressed_dir = None + + try: + if os.path.isfile(code_path) and code_path.endswith(self.SUPPORTED_ARCHIVE_EXTENSIONS): + + decompressed_dir = _unzip_file(code_path) + yield decompressed_dir + + else: + LOG.debug("Code %s is not a zip/jar file", code_path) + yield code_path + finally: + if decompressed_dir: + shutil.rmtree(decompressed_dir) + + +def _unzip_file(filepath): + """ + Helper method to unzip a file to a temporary directory + + :param string filepath: Absolute path to this file + :return string: Path to the temporary directory where it was unzipped + """ + + temp_dir = tempfile.mkdtemp() + + LOG.info("Decompressing %s", filepath) + + zip_ref = zipfile.ZipFile(filepath, 'r') + zip_ref.extractall(temp_dir) + + # The directory that Python returns might have symlinks. The Docker File sharing settings will not resolve + # symlinks. Hence get the real path before passing to Docker. + # Especially useful in Mac OSX which returns /var/folders which is a symlink to /private/var/folders that is a + # part of Docker's Shared Files directories + return os.path.realpath(temp_dir) diff --git a/samcli/yamlhelper.py b/samcli/yamlhelper.py new file mode 100644 index 0000000000..c4d3365361 --- /dev/null +++ b/samcli/yamlhelper.py @@ -0,0 +1,67 @@ +""" +Helper to be able to parse/dump YAML files +""" + +import json +import six + +import yaml +from yaml.resolver import ScalarNode, SequenceNode + + +def intrinsics_multi_constructor(loader, tag_prefix, node): + """ + YAML constructor to parse CloudFormation intrinsics. + This will return a dictionary with key being the instrinsic name + """ + + # Get the actual tag name excluding the first exclamation + tag = node.tag[1:] + + # Some intrinsic functions doesn't support prefix "Fn::" + prefix = "Fn::" + if tag in ["Ref", "Condition"]: + prefix = "" + + cfntag = prefix + tag + + if tag == "GetAtt" and isinstance(node.value, six.string_types): + # ShortHand notation for !GetAtt accepts Resource.Attribute format + # while the standard notation is to use an array + # [Resource, Attribute]. Convert shorthand to standard format + value = node.value.split(".", 1) + + elif isinstance(node, ScalarNode): + # Value of this node is scalar + value = loader.construct_scalar(node) + + elif isinstance(node, SequenceNode): + # Value of this node is an array (Ex: [1,2]) + value = loader.construct_sequence(node) + + else: + # Value of this node is an mapping (ex: {foo: bar}) + value = loader.construct_mapping(node) + + return {cfntag: value} + + +def yaml_dump(dict_to_dump): + """ + Dumps the dictionary as a YAML document + :param dict_to_dump: + :return: + """ + return yaml.safe_dump(dict_to_dump, default_flow_style=False) + + +def yaml_parse(yamlstr): + """Parse a yaml string""" + try: + # PyYAML doesn't support json as well as it should, so if the input + # is actually just json it is better to parse it with the standard + # json parser. + return json.loads(yamlstr) + except ValueError: + yaml.SafeLoader.add_multi_constructor("!", intrinsics_multi_constructor) + return yaml.safe_load(yamlstr) diff --git a/samples/.gitignore b/samples/.gitignore deleted file mode 100644 index 07c98fb9ac..0000000000 --- a/samples/.gitignore +++ /dev/null @@ -1 +0,0 @@ -packaged-template.yaml diff --git a/samples/README.md b/samples/README.md deleted file mode 100644 index 9d8dc48d5d..0000000000 --- a/samples/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# AWS SAM Examples # - -To work with the example applications in this repository, first ensure that you've installed and configured the requirements listed below. Then follow the instructions in the README files in the application/language subdirectories. - -## Requirements ## - -* An AWS account -* The AWS Command Line Interface (AWS CLI) -* Docker -* SAM Local -* An Amazon S3 bucket -* (Optional) Maven - -To install the AWS CLI, follow the instructions at [Installing the AWS Command Line Interface](http://docs.aws.amazon.com/cli/latest/userguide/installing.html). - -To install Docker and SAM Local, follow the instructions at [Requirements for Using SAM Local](http://docs.aws.amazon.com/lambda/latest/dg/test-sam-local.html#sam-cli-requirements). - -To create an Amazon S3 bucket, follow the instructions at [Create a Bucket](http://docs.aws.amazon.com/AmazonS3/latest/gsg/CreatingABucket.html). - -To run the Java examples, you'll need to install Maven. For more information, see [Creating a .jar Deployment Package Using Maven without any IDE (Java) ](http://docs.aws.amazon.com/lambda/latest/dg/java-create-jar-pkg-maven-no-ide.html). - -## Recommended ## - -* [Postman](https://www.getpostman.com/) - -You can use Postman to test API Gateway. diff --git a/samples/api-event-source/node/index.js b/samples/api-event-source/node/index.js deleted file mode 100644 index 2f7a0af683..0000000000 --- a/samples/api-event-source/node/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -exports.handler = (event, context, callback) => { - - callback(null, { - statusCode: 200, - body: "OK" - }) - -} diff --git a/samples/api-event-source/node/template.yaml b/samples/api-event-source/node/template.yaml deleted file mode 100644 index acfeebf6a9..0000000000 --- a/samples/api-event-source/node/template.yaml +++ /dev/null @@ -1,18 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: | - An example RESTful service - -Resources: - ExampleFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: index.handler - Events: - ListCustomers: - Type: Api - Properties: - Path: / - Method: any diff --git a/samples/api-event-source/python/api.py b/samples/api-event-source/python/api.py deleted file mode 100644 index f8bb8bdbe0..0000000000 --- a/samples/api-event-source/python/api.py +++ /dev/null @@ -1,6 +0,0 @@ -def get(event, context): - return {"body": "GET OK", "statusCode": 200} - - -def put(event, context): - return {"body": "PUT OK", "statusCode": 200} diff --git a/samples/api-event-source/python/template.yaml b/samples/api-event-source/python/template.yaml deleted file mode 100644 index d96a29f0ae..0000000000 --- a/samples/api-event-source/python/template.yaml +++ /dev/null @@ -1,30 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: | - An example RESTful service - -Resources: - ExampleGetFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: python3.6 - Handler: api.get - Events: - GetItems: - Type: Api - Properties: - Path: / - Method: get - ExamplePutFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: python3.6 - Handler: api.put - Events: - PutItems: - Type: Api - Properties: - Path: / - Method: put - diff --git a/samples/go-lambda/README.md b/samples/go-lambda/README.md deleted file mode 100644 index ef06b35c42..0000000000 --- a/samples/go-lambda/README.md +++ /dev/null @@ -1,18 +0,0 @@ -This is a very simple Hello World application written in Golang. - -### Instructions - -1. Build the binary to be compatible with Linux: `GOOS=linux go build main.go` -2. Zip up the binary: `zip main.zip ./main` -3. Invoke locally -```bash -$ echo '"world"' | sam local invoke - -2018/01/23 16:00:46 Successfully parsed template.yaml -2018/01/23 16:00:46 Connected to Docker 1.30 -2018/01/23 16:00:46 Fetching lambci/lambda:go1.x image for go1.x runtime... -.... -"Hello world!" - -``` - diff --git a/samples/go-lambda/main.go b/samples/go-lambda/main.go deleted file mode 100644 index 0609d6d3b2..0000000000 --- a/samples/go-lambda/main.go +++ /dev/null @@ -1,14 +0,0 @@ -package main - -import ( - "fmt" - "github.com/aws/aws-lambda-go/lambda" -) - -func HandleRequest(name string) (string, error) { - return fmt.Sprintf("Hello %s!", name), nil -} - -func main() { - lambda.Start(HandleRequest) -} diff --git a/samples/go-lambda/template.yaml b/samples/go-lambda/template.yaml deleted file mode 100644 index 74dbf3165a..0000000000 --- a/samples/go-lambda/template.yaml +++ /dev/null @@ -1,12 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Hello World Go Lambda function - -Resources: - - Function: - Type: AWS::Serverless::Function - Properties: - Handler: main - CodeUri: ./main.zip - Runtime: go1.x diff --git a/samples/hello-world/golang/README.md b/samples/hello-world/golang/README.md deleted file mode 100644 index 045a7a39e0..0000000000 --- a/samples/hello-world/golang/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# AWS SAM Hello World Example # - -A simple AWS SAM template that specifies a single Lambda function. - -## Usage ## - -To create and deploy the SAM Hello World example, first ensure that you've met the requirements described in the [root README](../../README.md). Then follow the steps below. - -### Build your package ### - - GOOS=linux go build -o main - -### Test your application locally ### - -Use [SAM Local](https://github.com/awslabs/aws-sam-local) to run your Lambda function locally: - - sam local invoke "HelloWorld" -e event.json - -### Package artifacts ### - -Run the following command, replacing `BUCKET-NAME` with the name of your bucket: - - sam package --template-file template.yaml --s3-bucket BUCKET-NAME --output-template-file packaged-template.yaml - -This creates a new template file, packaged-template.yaml, that you will use to deploy your serverless application. - -### Deploy to AWS CloudFormation ### - -Run the following command, replacing `MY-NEW-STACK` with a name for your CloudFormation stack. - - sam deploy --template-file packaged-template.yaml --stack-name MY-NEW-STACK --capabilities CAPABILITY_IAM - -This uploads your template to an S3 bucket and deploys the specified resources using AWS CloudFormation. diff --git a/samples/hello-world/golang/main.go b/samples/hello-world/golang/main.go deleted file mode 100644 index 9944e2aa6f..0000000000 --- a/samples/hello-world/golang/main.go +++ /dev/null @@ -1,22 +0,0 @@ -package main - -import ( - "fmt" - "log" - "context" - "github.com/aws/aws-lambda-go/lambda" -) - -type Event map[string]interface{} - -func HandleRequest(ctx context.Context, event Event) (string, error) { - log.Print("value1 = ", event["key1"] ) - log.Print("value2 = ", event["key2"] ) - log.Print("value3 = ", event["key3"] ) - - return fmt.Sprintf("Hello World"), nil -} - -func main() { - lambda.Start(HandleRequest) -} diff --git a/samples/hello-world/golang/template.yaml b/samples/hello-world/golang/template.yaml deleted file mode 100644 index fed1a828af..0000000000 --- a/samples/hello-world/golang/template.yaml +++ /dev/null @@ -1,11 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: A simple Hello World Serverless project -Resources: - HelloWorld: - Type: AWS::Serverless::Function - Properties: - Runtime: go1.x - Handler: main - CodeUri: . diff --git a/samples/hello-world/java/README.md b/samples/hello-world/java/README.md deleted file mode 100644 index db3f250282..0000000000 --- a/samples/hello-world/java/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# AWS SAM Hello World Example # - -A simple AWS SAM template that specifies a single Lambda function. - -## Usage ## - -To create and deploy the SAM Hello World example, first ensure that you've met the requirements described in the [root README](../../README.md). Then follow the steps below. - -### Build your package ### - - mvn package shade:shade - -### Test your application locally ### - -Use [SAM Local](https://github.com/awslabs/aws-sam-local) to run your Lambda function locally: - - sam local invoke "HelloWorldFunction" -e event.json - -### Package artifacts ### - -Run the following command, replacing `BUCKET-NAME` with the name of your bucket: - - sam package --template-file template.yaml --s3-bucket BUCKET-NAME --output-template-file packaged-template.yaml - -This creates a new template file, packaged-template.yaml, that you will use to deploy your serverless application. - -### Deploy to AWS CloudFormation ### - -Run the following command, replacing `MY-NEW-STACK` with a name for your CloudFormation stack. - - sam deploy --template-file packaged-template.yaml --stack-name MY-NEW-STACK --capabilities CAPABILITY_IAM - -This uploads your template to an S3 bucket and deploys the specified resources using AWS CloudFormation. diff --git a/samples/hello-world/java/event.json b/samples/hello-world/java/event.json deleted file mode 100644 index a5fb7093c9..0000000000 --- a/samples/hello-world/java/event.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "key1": "value1", - "key2": "value2", - "key3": "value3" -} diff --git a/samples/hello-world/java/pom.xml b/samples/hello-world/java/pom.xml deleted file mode 100644 index e67064ff8a..0000000000 --- a/samples/hello-world/java/pom.xml +++ /dev/null @@ -1,39 +0,0 @@ - - 4.0.0 - - com.amazonaws.examples - HelloWorld - jar - 1.0 - AWS SAM Local Hello World Example - - - - com.amazonaws - aws-lambda-java-core - 1.1.0 - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - false - - - - package - - shade - - - - - - - diff --git a/samples/hello-world/java/src/main/java/com/amazonaws/HelloWorld.java b/samples/hello-world/java/src/main/java/com/amazonaws/HelloWorld.java deleted file mode 100644 index c895e0aeea..0000000000 --- a/samples/hello-world/java/src/main/java/com/amazonaws/HelloWorld.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.amazonaws.examples; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; - -public class HelloWorld implements RequestHandler { - public Response handleRequest(Request request, Context context) { - System.out.println("value1 = " + request.key1); - System.out.println("value2 = " + request.key2); - System.out.println("value3 = " + request.key3); - - return new Response("Hello World"); - } -} diff --git a/samples/hello-world/java/src/main/java/com/amazonaws/examples/Request.java b/samples/hello-world/java/src/main/java/com/amazonaws/examples/Request.java deleted file mode 100644 index 03b6d4818f..0000000000 --- a/samples/hello-world/java/src/main/java/com/amazonaws/examples/Request.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.amazonaws.examples; - -public class Request { - String key1; - String key2; - String key3; - - public String getKey1() { - return key1; - } - - public void setKey1(String key1) { - this.key1 = key1; - } - - public String getKey2() { - return key2; - } - - public void setKey2(String key2) { - this.key2 = key2; - } - - public String getKey3() { - return key3; - } - - public void setKey3(String key3) { - this.key3 = key3; - } - - public Request(String key1, String key2, String key3) { - this.key1 = key1; - this.key2 = key2; - this.key3 = key3; - } - - public Request() {} -} diff --git a/samples/hello-world/java/src/main/java/com/amazonaws/examples/Response.java b/samples/hello-world/java/src/main/java/com/amazonaws/examples/Response.java deleted file mode 100644 index 0dc8ce9204..0000000000 --- a/samples/hello-world/java/src/main/java/com/amazonaws/examples/Response.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.amazonaws.examples; - -public class Response { - String message; - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Response(String message) { - this.message = message; - } - - public Response() {} -} diff --git a/samples/hello-world/java/template.yaml b/samples/hello-world/java/template.yaml deleted file mode 100644 index 21bad96424..0000000000 --- a/samples/hello-world/java/template.yaml +++ /dev/null @@ -1,10 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A hello world application. -Resources: - HelloWorldFunction: - Type: AWS::Serverless::Function - Properties: - Handler: com.amazonaws.examples.HelloWorld - Runtime: java8 - CodeUri: ./target/HelloWorld-1.0.jar diff --git a/samples/hello-world/node/README.md b/samples/hello-world/node/README.md deleted file mode 100644 index 4cfec21d19..0000000000 --- a/samples/hello-world/node/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# AWS SAM Hello World Example # - -A simple AWS SAM template that specifies a single Lambda function. - -## Usage ## - -To create and deploy the SAM Hello World example, first ensure that you've met the requirements described in the [root README](../../README.md). Then follow the steps below. - -### Test your application locally ### - -Use [SAM Local](https://github.com/awslabs/aws-sam-local) to run your Lambda function locally: - - sam local invoke "HelloWorld" -e event.json - -### Package artifacts ### - -Run the following command, replacing `BUCKET-NAME` with the name of your bucket: - - sam package --template-file template.yaml --s3-bucket BUCKET-NAME --output-template-file packaged-template.yaml - -This creates a new template file, packaged-template.yaml, that you will use to deploy your serverless application. - -### Deploy to AWS CloudFormation ### - -Run the following command, replacing `MY-NEW-STACK` with a name for your CloudFormation stack. - - sam deploy --template-file packaged-template.yaml --stack-name MY-NEW-STACK --capabilities CAPABILITY_IAM - -This uploads your template to an S3 bucket and deploys the specified resources using AWS CloudFormation. diff --git a/samples/hello-world/node/event.json b/samples/hello-world/node/event.json deleted file mode 100644 index 442e32a789..0000000000 --- a/samples/hello-world/node/event.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "Bob" -} diff --git a/samples/hello-world/node/index.js b/samples/hello-world/node/index.js deleted file mode 100644 index 1c88103667..0000000000 --- a/samples/hello-world/node/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -// A simple hello world Lambda function -exports.handler = (event, context, callback) => { - - console.log('LOG: Name is ' + event.name); - callback(null, "Hello " + event.name); - -} diff --git a/samples/hello-world/node/template.yaml b/samples/hello-world/node/template.yaml deleted file mode 100644 index b70e5a1929..0000000000 --- a/samples/hello-world/node/template.yaml +++ /dev/null @@ -1,11 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: A simple Hello World Serverless project -Resources: - HelloWorld: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: index.handler - CodeUri: . diff --git a/samples/hello-world/python/README.md b/samples/hello-world/python/README.md deleted file mode 100644 index 491a2ef099..0000000000 --- a/samples/hello-world/python/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# AWS SAM Hello World Example # - -A simple AWS SAM template that specifies a single Lambda function. - -## Usage ## - -To create and deploy the SAM Hello World example, first ensure that you've met the requirements described in the [root README](../../README.md). Then follow the steps below. - -### Test your application locally ### - -Use [SAM Local](https://github.com/awslabs/aws-sam-local) to run your Lambda function locally: - - sam local invoke "HelloWorldFunction" -e event.json - -### Package artifacts ### - -Run the following command, replacing `BUCKET-NAME` with the name of your bucket: - - sam package --template-file template.yaml --s3-bucket BUCKET-NAME --output-template-file packaged-template.yaml - -This creates a new template file, packaged-template.yaml, that you will use to deploy your serverless application. - -### Deploy to AWS CloudFormation ### - -Run the following command, replacing `MY-NEW-STACK` with a name for your CloudFormation stack. - - sam deploy --template-file packaged-template.yaml --stack-name MY-NEW-STACK --capabilities CAPABILITY_IAM - -This uploads your template to an S3 bucket and deploys the specified resources using AWS CloudFormation. diff --git a/samples/hello-world/python/event.json b/samples/hello-world/python/event.json deleted file mode 100644 index a5fb7093c9..0000000000 --- a/samples/hello-world/python/event.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "key1": "value1", - "key2": "value2", - "key3": "value3" -} diff --git a/samples/hello-world/python/main.py b/samples/hello-world/python/main.py deleted file mode 100644 index d0ec46f048..0000000000 --- a/samples/hello-world/python/main.py +++ /dev/null @@ -1,8 +0,0 @@ -print('Loading function') - -def handler(event, context): - print("value1 = " + event['key1']) - print("value2 = " + event['key2']) - print("value3 = " + event['key3']) - - return "Hello world" diff --git a/samples/hello-world/python/template.yaml b/samples/hello-world/python/template.yaml deleted file mode 100644 index 4a17740077..0000000000 --- a/samples/hello-world/python/template.yaml +++ /dev/null @@ -1,10 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A hello world application. -Resources: - HelloWorldFunction: - Type: AWS::Serverless::Function - Properties: - Handler: main.handler - Runtime: python3.6 - CodeUri: . diff --git a/samples/java/.gitignore b/samples/java/.gitignore deleted file mode 100644 index e420ee4ba0..0000000000 --- a/samples/java/.gitignore +++ /dev/null @@ -1 +0,0 @@ -target/* diff --git a/samples/java/README.md b/samples/java/README.md deleted file mode 100644 index e2cfb82be8..0000000000 --- a/samples/java/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Welcome to the AWS CodeStar sample web service -============================================== - -This sample code helps get you started with a simple Java web service using -AWS Lambda and Amazon API Gateway. - -What's Here ------------ - -This sample includes: - -* README.md - this file -* buildspec.yml - this file is used by AWS CodeBuild to build the web - service -* pom.xml - this file is the Maven Project Object Model for the web service -* src/ - this directory contains your Java service source files -* template.yml - this file contains the Serverless Application Model (SAM) used - by AWS Cloudformation to deploy your application to AWS Lambda and Amazon API - Gateway. - - -What Do I Do Next? ------------------- - -If you have checked out a local copy of your AWS CodeCommit repository you can -start making changes to the sample code. We suggest making a small change to -index.py first, so you can see how changes pushed to your project's repository -in AWS CodeCommit are automatically picked up by your project pipeline and -deployed to AWS Lambda and Amazon API Gateway. (You can watch the pipeline -progress on your AWS CodeStar project dashboard.) Once you've seen how that -works, start developing your own code, and have fun! - -Learn more about Serverless Application Model (SAM) and how it works here: -https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md - -AWS Lambda Developer Guide: -http://docs.aws.amazon.com/lambda/latest/dg/deploying-lambda-apps.html - -Learn more about AWS CodeStar by reading the user guide, and post questions and -comments about AWS CodeStar on our forum. - -AWS CodeStar User Guide: -http://docs.aws.amazon.com/codestar/latest/userguide/welcome.html - -AWS CodeStar Forum: https://forums.aws.amazon.com/forum.jspa?forumID=248 diff --git a/samples/java/buildspec.yml b/samples/java/buildspec.yml deleted file mode 100644 index 1b8a006adb..0000000000 --- a/samples/java/buildspec.yml +++ /dev/null @@ -1,15 +0,0 @@ -version: 0.2 - -phases: - build: - commands: - - echo Entering build phase... - - echo Build started on `date` - - mvn package shade:shade - - mv target/HelloWorld-1.0.jar . - - unzip HelloWorld-1.0.jar - - rm -rf target src buildspec.yml pom.xml HelloWorld-1.0.jar - - aws cloudformation package --template template.yml --s3-bucket $S3_BUCKET --output-template template-export.json -artifacts: - files: - - template-export.json \ No newline at end of file diff --git a/samples/java/pom.xml b/samples/java/pom.xml deleted file mode 100644 index c78dfa7bfa..0000000000 --- a/samples/java/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - 4.0.0 - com.aws.codestar.projecttemplates - HelloWorld - 1.0 - jar - A sample Java Spring web service created with AWS CodeStar. - - org.springframework.boot - spring-boot-starter-parent - 1.4.3.RELEASE - - - 1.8 - 1.8 - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-tomcat - provided - - - com.amazonaws - aws-lambda-java-core - 1.1.0 - - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - false - - - - package - - shade - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - - diff --git a/samples/java/src/main/java/com/aws/codestar/projecttemplates/Application.java b/samples/java/src/main/java/com/aws/codestar/projecttemplates/Application.java deleted file mode 100644 index b6702649bd..0000000000 --- a/samples/java/src/main/java/com/aws/codestar/projecttemplates/Application.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.aws.codestar.projecttemplates; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -/** Simple class to start up the application. - * - * @SpringBootApplication adds: - * @Configuration - * @EnableAutoConfiguration - * @ComponentScan - */ -@SpringBootApplication -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/samples/java/src/main/java/com/aws/codestar/projecttemplates/handler/HelloWorldHandler.java b/samples/java/src/main/java/com/aws/codestar/projecttemplates/handler/HelloWorldHandler.java deleted file mode 100644 index d437d09328..0000000000 --- a/samples/java/src/main/java/com/aws/codestar/projecttemplates/handler/HelloWorldHandler.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.aws.codestar.projecttemplates.handler; - -import com.amazonaws.services.lambda.runtime.Context; -import com.amazonaws.services.lambda.runtime.RequestHandler; - -import java.util.HashMap; -import java.util.Map; - -import com.aws.codestar.projecttemplates.GatewayResponse; - -/** - * Handler for requests to Lambda function. - */ -public class HelloWorldHandler implements RequestHandler { - - public Object handleRequest(final Object input, final Context context) { - Map headers = new HashMap<>(); - headers.put("Content-Type", "application/json"); - headers.put("X-Custom-Header", "application/json"); - System.err.println("This is a test log message 1"); - System.err.println("This is a test log message 2"); - return new GatewayResponse("{ \"Output\": \"Hello World!\"}", headers, 200); - } -} diff --git a/samples/java/template.yml b/samples/java/template.yml deleted file mode 100644 index fc39258588..0000000000 --- a/samples/java/template.yml +++ /dev/null @@ -1,42 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: -- AWS::Serverless-2016-10-31 -- AWS::CodeStar - -Parameters: - ProjectId: - Type: String - Description: AWS CodeStar projectID used to associate new resources to team members - -Resources: - GetHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler - CodeUri: ./target/HelloWorld-1.0.jar - Runtime: java8 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - GetEvent: - Type: Api - Properties: - Path: /java - Method: get - - PostHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler - CodeUri: ./target/HelloWorld-1.0.jar - Runtime: java8 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - PostEvent: - Type: Api - Properties: - Path: / - Method: post diff --git a/samples/python-with-packages/.gitignore b/samples/python-with-packages/.gitignore deleted file mode 100644 index e5aeba8201..0000000000 --- a/samples/python-with-packages/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.py[co] -*.egg-info - -/bundle.zip -/packaged.yml - -/var -/.venv diff --git a/samples/python-with-packages/Makefile b/samples/python-with-packages/Makefile deleted file mode 100644 index 3feeb20e44..0000000000 --- a/samples/python-with-packages/Makefile +++ /dev/null @@ -1,67 +0,0 @@ -SHELL := /bin/bash -PY_VERSION := 3.6 - -export PYTHONUNBUFFERED := 1 - -AWS_PROFILE ?= sandbox -BUCKET ?= <> -S3_PREFIX ?= sources -STACK_NAME ?= stack-cloudschedule - -BASE := $(shell /bin/pwd) -VENV_DIR := $(BASE)/.venv -export PATH := var:$(PATH):$(VENV_DIR)/bin - -PYTHON := $(shell /usr/bin/which python$(PY_VERSION)) -VIRTUALENV := $(PYTHON) -m venv -ZIP_FILE := $(BASE)/bundle.zip - -.DEFAULT_GOAL := build -.PHONY: build clean release describe deploy package bundle bundle.local - - -build: - $(VIRTUALENV) "$(VENV_DIR)" - mkdir -p "$(VENV_DIR)/lib64/python$(PY_VERSION)/site-packages" - touch "$(VENV_DIR)/lib64/python$(PY_VERSION)/site-packages/file" - "$(VENV_DIR)/bin/pip$(PY_VERSION)" \ - --isolated \ - --disable-pip-version-check \ - install --no-binary :all: -Ur requirements.txt - find "$(VENV_DIR)" -name "*.pyc" -exec rm -f {} \; - -bundle.local: - zip -r -9 "$(ZIP_FILE)" example - cd "$(VENV_DIR)/lib/python$(PY_VERSION)/site-packages" \ - && zip -r9 "$(ZIP_FILE)" * - cd "$(VENV_DIR)/lib64/python$(PY_VERSION)/site-packages" \ - && zip -r9 "$(ZIP_FILE)" * - -bundle: - docker run -v $$PWD:/var/task -it lambci/lambda:build-python3.6 /bin/bash -c 'make clean build bundle.local' - -package: - sam package \ - --template-file template.yml \ - --s3-bucket $(BUCKET) \ - --s3-prefix $(S3_PREFIX) \ - --output-template-file packaged.yml - -deploy: - sam deploy \ - --template-file packaged.yml \ - --stack-name $(STACK_NAME) \ - --capabilities CAPABILITY_IAM - -# call this in case of errors -describe: - aws cloudformation describe-stack-events --stack-name $(STACK_NAME) - -release: - @make bundle - @make package - @make deploy - -clean: - rm -rf "$(VENV_DIR)" "$(BASE)/var" "$(BASE)/__pycache__" "$(ZIP_FILE)" - diff --git a/samples/python-with-packages/README.md b/samples/python-with-packages/README.md deleted file mode 100644 index e2b97667b3..0000000000 --- a/samples/python-with-packages/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# Full Example for a Python Lambda with external Dependencies - -## Development - -### Prerequisites - -- Install [Docker](https://github.com/awslabs/aws-sam-local#prerequisites) -- Install [AWS SAM local](https://github.com/awslabs/aws-sam-local) from - [here](https://github.com/awslabs/aws-sam-local/releases) - -### Run - -As we defined `EnvDownHandler` in [`template.yml`](template.yml), our -`invoke` call looks like this - -```bash -$ echo '{ "resources": ["arn:aws:events:eu-west-1:482174156240:rule/10MinuteTickRule"] }' | sam local invoke EnvDownHandler -2017/09/06 11:06:39 Successfully parsed template.yml -2017/09/06 11:06:39 Connected to Docker 1.30 -2017/09/06 11:06:39 Fetching lambci/lambda:python3.6 image for python3.6 runtime... -python3.6: Pulling from lambci/lambda -Digest: sha256:b0245d6aaae7648b4c488ffa3113e20d67b77ecc15392589162f67e7fa8e1bb7 -Status: Image is up to date for lambci/lambda:python3.6 -2017/09/06 11:06:41 Reading invoke payload from stdin (you can also pass it from file with --event) -2017/09/06 11:06:41 Invoking schedule.lambda_sandbox_down_handler (python3.6) -START RequestId: 09c35258-f743-4906-bbc5-35f12a542fb9 Version: $LATEST -hello from handler -END RequestId: 09c35258-f743-4906-bbc5-35f12a542fb9 -REPORT RequestId: 09c35258-f743-4906-bbc5-35f12a542fb9 Duration: 31 ms Billed Duration: 0 ms Memory Size: 0 MB Max Memory Used: 19 MB - -"foo" -``` - -We can see what kind of payload we'll receive via - -```bash -$ sam local generate-event schedule -{ - "account": "123456789012", - "region": "us-east-1", - "detail": {}, - "detail-type": "Scheduled Event", - "source": "aws.events", - "time": "1970-01-01T00:00:00Z", - "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", - "resources": [ - "arn:aws:events:us-east-1:123456789012:rule/my-schedule" - ] -} -``` - -### Build - -To be able to package third-party dependencies as we know it via virtualenv, we need to interact -with docker directly [5]. - -To just build the current status, run - -```bash -make bundle -``` - -If you want to inspect the image, perform an interactive shell - -```bash -docker run -v $PWD:/var/task -it lambci/lambda:build-python3.6 /bin/bash -``` - -### Deploy - -#### TL;DR - -For a complete release action, just call - -```bash -make release -``` - - -#### More Detailed - -For deployment we follow [the SAM documentation](https://github.com/awslabs/aws-sam-local#package-and-deploy-to-lambda) - -To include our AWS credentials and to make things easy, there are two `make` targets - -```bash -make package -make deploy -``` - -- `make package` takes the `template.yml`, uploads our `build.zip` and creates a new template (`packaged.yml`) - with the matching S3 reference in `CodeUri`. - -- `make deploy` will wire the uploaded zip file on S3 to a fully functional lambda. Ours can be listed - [here](https://eu-west-1.console.aws.amazon.com/lambda/home?region=eu-west-1#/functions) - - -### Using the virtualenv in a different Architecture - -There is no reason not to call - -```bash -make clean build -``` -locally. Just ensure that you always use `clean` to avoid confusion inside of the virtualenv. - - -## Background - -1. A general blueprint how to start with cloudwatch events and lambda handlers exists [from Amazon](https://aws.amazon.com/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/). This does -not include SAM Local or external sources; still it provides a good overview. - -1. A python package with dependencies requires us to [build a `virtualenv` on -a `amd64` kernel]( -http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python). - -1. Howto integrate third party libs into lambda via SAM Local [seems unclear](https://github.com/awslabs/aws-sam-local/issues/53) - -1. About [Packaging Lambda Functions](https://github.com/awslabs/serverless-application-model/blob/master/HOWTO.md#packing-artifacts) - -1. [Replications](https://github.com/lambci/docker-lambda) of the live AWS Lambda environment - -1. [About packaging `virtualenv` projects for AWS Lambda](http://www.perrygeo.com/running-python-with-compiled-code-on-aws-lambda.html) - -1. Create a Deployment Package [on AWS](http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-deployment-pkg.html#with-s3-example-deployment-pkg-python) -1. Create a Deployment Package [for Lambda](http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html#deployment-pkg-for-virtualenv) - -1. [About Lambda Roles](http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example-create-iam-role.html) - -1. [Example Policies for EC2 handling](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ExamplePolicies_EC2.html) \ No newline at end of file diff --git a/samples/python-with-packages/VERSION b/samples/python-with-packages/VERSION deleted file mode 100644 index 8acdd82b76..0000000000 --- a/samples/python-with-packages/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.0.1 diff --git a/samples/python-with-packages/example/__init__.py b/samples/python-with-packages/example/__init__.py deleted file mode 100644 index 3d76c97dbf..0000000000 --- a/samples/python-with-packages/example/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -# https://www.python.org/dev/peps/pep-0382/ -__import__('pkg_resources').declare_namespace(__name__) \ No newline at end of file diff --git a/samples/python-with-packages/example/schedule.py b/samples/python-with-packages/example/schedule.py deleted file mode 100644 index bca0296365..0000000000 --- a/samples/python-with-packages/example/schedule.py +++ /dev/null @@ -1,9 +0,0 @@ -import logging - -logging.basicConfig(level=logging.INFO) -log = logging.getLogger(__name__) -log.setLevel(logging.INFO) - -def lambda_sandbox_down_handler(event: dict, context): - log.info('running DOWN handler with event: %s and context: %s', event, context) - diff --git a/samples/python-with-packages/requirements.txt b/samples/python-with-packages/requirements.txt deleted file mode 100644 index 6d803117dc..0000000000 --- a/samples/python-with-packages/requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ -# we're only loading one example dep here -requests==2.18.4 -. \ No newline at end of file diff --git a/samples/python-with-packages/setup.cfg b/samples/python-with-packages/setup.cfg deleted file mode 100644 index 6302b3a02b..0000000000 --- a/samples/python-with-packages/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[install] -prefix= \ No newline at end of file diff --git a/samples/python-with-packages/setup.py b/samples/python-with-packages/setup.py deleted file mode 100644 index 12af7d738f..0000000000 --- a/samples/python-with-packages/setup.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -import os -from setuptools import setup, find_packages - -here = os.path.abspath(os.path.dirname(__file__)) -VERSION = open(os.path.join(here, 'VERSION')).read().strip() - -required_eggs = [ - 'requests>=2.18.4', - 'boto3>=1.4.7', -] - -setup( - name='example.cloudschedule', - version=VERSION, - description="", - author="zerotired", - author_email='andi@doppelpop.de', - url='', - packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]), - # http://pythonhosted.org/distribute/setuptools.html#namespace-packages - namespace_packages=['example'], - # TODO amb - # include_package_data=True, - package_data={'example': ['static/*.*', 'templates/*.*']}, - install_requires=required_eggs, - extras_require=dict( - test=required_eggs + [ - 'pytest>=3.2', - ], - develop=required_eggs + [ - 'ipdb>=0.10.2', - ]), - zip_safe=False, - entry_points={ - 'console_scripts': [ - 'index=example.schedule:lambda_sandbox_down_handler' - ], - }, - dependency_links=[ - ], -) diff --git a/samples/python-with-packages/template.yml b/samples/python-with-packages/template.yml deleted file mode 100644 index e2509fc51f..0000000000 --- a/samples/python-with-packages/template.yml +++ /dev/null @@ -1,15 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Example Lambda -Resources: - EnvDownHandler: - Type: AWS::Serverless::Function - Properties: - # as soon as we rely on third-party depedencies (pip packages to `virtualenv`), we are - # forced to create a zip-file, containing all relevant data - CodeUri: bundle.zip - Handler: example.schedule.lambda_sandbox_down_handler - Runtime: python3.6 - Environment: - Variables: - AWS_ENVIRONMENT: sandbox diff --git a/samples/s3-event-source/index.js b/samples/s3-event-source/index.js deleted file mode 100644 index ecc245a5c0..0000000000 --- a/samples/s3-event-source/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -exports.handler = (event, context, callback) => { - - for (let record of event.Records) { - console.log("Got an S3 event:"); - console.log(" - Bucket: " + record.s3.bucket.arn); - console.log(" - Key: " + record.s3.object.key); - } - - callback(null, "") - -} \ No newline at end of file diff --git a/samples/s3-event-source/template.yaml b/samples/s3-event-source/template.yaml deleted file mode 100644 index d591bc021a..0000000000 --- a/samples/s3-event-source/template.yaml +++ /dev/null @@ -1,21 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: | - A sample Serverless project triggered from S3 CreateObject events - -Resources: - ExampleFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: index.handler - Events: - S3CreateObject: - Type: S3 - Properties: - Bucket: !Ref MyPhotoBucket - Events: s3:ObjectCreated:* - - MyPhotoBucket: - Type: AWS::S3::Bucket diff --git a/samples/using-aws-sdk/.gitignore b/samples/using-aws-sdk/.gitignore deleted file mode 100644 index 00cbbdf53f..0000000000 --- a/samples/using-aws-sdk/.gitignore +++ /dev/null @@ -1,59 +0,0 @@ -# Logs -logs -*.log -npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# Bower dependency directory (https://bower.io/) -bower_components - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# Typescript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - diff --git a/samples/using-aws-sdk/index.js b/samples/using-aws-sdk/index.js deleted file mode 100644 index fa4562900e..0000000000 --- a/samples/using-aws-sdk/index.js +++ /dev/null @@ -1,29 +0,0 @@ -'use strict'; - -// Make sure to run 'npm install' before running this function. -// This will fetch the AWS SDK to ./node_modules. - -// Create a new AWS SDK object -const AWS = require('aws-sdk'); - -// Create S3 service object -const s3 = new AWS.S3({apiVersion: '2006-03-01'}); - -exports.handler = (event, context, callback) => { - - s3.listBuckets((err, data) => { - - if(err){ - console.log("Error listing S3 buckets: " + err); - callback(err, null); - return; - } - - for (let bucket of data.Buckets){ - console.log("s3://" + bucket.Name) - callback(null, "ok") - } - - }) - -} \ No newline at end of file diff --git a/samples/using-aws-sdk/package-lock.json b/samples/using-aws-sdk/package-lock.json deleted file mode 100644 index 57bb91f39c..0000000000 --- a/samples/using-aws-sdk/package-lock.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "name": "using-aws-sdk", - "version": "1.0.0", - "lockfileVersion": 1, - "requires": true, - "dependencies": { - "aws-sdk": { - "version": "2.94.0", - "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.94.0.tgz", - "integrity": "sha1-cEPePvjCTLarS/I18I2H2EFz4XQ=", - "requires": { - "buffer": "4.9.1", - "crypto-browserify": "1.0.9", - "events": "1.1.1", - "jmespath": "0.15.0", - "querystring": "0.2.0", - "sax": "1.2.1", - "url": "0.10.3", - "uuid": "3.0.1", - "xml2js": "0.4.17", - "xmlbuilder": "4.2.1" - } - }, - "base64-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.2.1.tgz", - "integrity": "sha512-dwVUVIXsBZXwTuwnXI9RK8sBmgq09NDHzyR9SAph9eqk76gKK2JSQmZARC2zRC81JC2QTtxD0ARU5qTS25gIGw==" - }, - "buffer": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", - "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", - "requires": { - "base64-js": "1.2.1", - "ieee754": "1.1.8", - "isarray": "1.0.0" - } - }, - "crypto-browserify": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/crypto-browserify/-/crypto-browserify-1.0.9.tgz", - "integrity": "sha1-zFRJaF37hesRyYKKzHy4erW7/MA=" - }, - "events": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", - "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=" - }, - "ieee754": { - "version": "1.1.8", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", - "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=" - }, - "isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=" - }, - "jmespath": { - "version": "0.15.0", - "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", - "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=" - }, - "lodash": { - "version": "4.17.4", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.4.tgz", - "integrity": "sha1-eCA6TRwyiuHYbcpkYONptX9AVa4=" - }, - "punycode": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", - "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=" - }, - "querystring": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", - "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=" - }, - "sax": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", - "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=" - }, - "url": { - "version": "0.10.3", - "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", - "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", - "requires": { - "punycode": "1.3.2", - "querystring": "0.2.0" - } - }, - "uuid": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.0.1.tgz", - "integrity": "sha1-ZUS7ot/ajBzxfmKaOjBeK7H+5sE=" - }, - "xml2js": { - "version": "0.4.17", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.17.tgz", - "integrity": "sha1-F76T6q4/O3eTWceVtBlwWogX6Gg=", - "requires": { - "sax": "1.2.1", - "xmlbuilder": "4.2.1" - } - }, - "xmlbuilder": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-4.2.1.tgz", - "integrity": "sha1-qlijBBoGb5DqoWwvU4n/GfP0YaU=", - "requires": { - "lodash": "4.17.4" - } - } - } -} diff --git a/samples/using-aws-sdk/package.json b/samples/using-aws-sdk/package.json deleted file mode 100644 index 7c5217a0b1..0000000000 --- a/samples/using-aws-sdk/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "using-aws-sdk", - "version": "1.0.0", - "description": "An example Serverless project that uses the AWS SDK to list S3 buckets", - "main": "index.js", - "dependencies": { - "aws-sdk": "^2.94.0" - }, - "devDependencies": {}, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "Paul Maddox ", - "license": "Apache-2.0" -} diff --git a/samples/using-aws-sdk/template.yaml b/samples/using-aws-sdk/template.yaml deleted file mode 100644 index 5a3dd70199..0000000000 --- a/samples/using-aws-sdk/template.yaml +++ /dev/null @@ -1,14 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: | - An example Serverless project that uses the AWS SDK to list S3 buckets - -Resources: - # Place your project resources here (AWS Lambda functions, API Gateway) etc - - ExampleFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: index.handler diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000000..11e9ec40ee --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +description-file = README.rst \ No newline at end of file diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000..270d07b268 --- /dev/null +++ b/setup.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python + +import io +import re +import os +from setuptools import setup, find_packages + + +def read(*filenames, **kwargs): + encoding = kwargs.get('encoding', 'utf-8') + sep = kwargs.get('sep', os.linesep) + buf = [] + for filename in filenames: + with io.open(filename, encoding=encoding) as f: + buf.append(f.read()) + return sep.join(buf) + + +def read_requirements(req='base.txt'): + content = read(os.path.join('requirements', req)) + return [line for line in content.split(os.linesep) + if not line.strip().startswith('#')] + + +def read_version(): + content = read(os.path.join( + os.path.dirname(__file__), 'samcli', '__init__.py')) + return re.search(r"__version__ = '([^']+)'", content).group(1) + + +cmd_name = "sam" +if os.getenv("SAM_CLI_DEV"): + # We are installing in a dev environment + cmd_name = "samdev" + +setup( + name='aws-sam-cli', + version=read_version(), + description='AWS SAM CLI is a CLI tool for local development and testing of Serverless applications', + long_description=read('README.rst'), + author='Amazon Web Services', + author_email='aws-sam-developers@amazon.com', + url='https://github.com/awslabs/aws-sam-cli', + license=read('LICENSE'), + packages=find_packages(exclude=('tests', 'docs')), + keywords="AWS SAM CLI", + # Support Python2.7 and higher, but not 3.x + python_requires='~=2.7', + entry_points={ + 'console_scripts': [ + '{}=samcli.cli.main:cli'.format(cmd_name) + ] + }, + install_requires=read_requirements('base.txt'), + extras_require={ + 'dev': read_requirements('dev.txt') + }, + include_package_data=True, + classifiers=[ + 'Development Status :: 4 - Beta', + 'Environment :: Console', + 'Environment :: Other Environment', + 'Intended Audience :: Developers', + 'Intended Audience :: Information Technology', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2.7', + 'Topic :: Internet', + 'Topic :: Software Development :: Build Tools', + 'Topic :: Utilities', + ] +) diff --git a/start.go b/start.go deleted file mode 100644 index 2ee99baabc..0000000000 --- a/start.go +++ /dev/null @@ -1,160 +0,0 @@ -package main - -import ( - "fmt" - "io" - "log" - "net/http" - "os" - "path/filepath" - - "github.com/awslabs/goformation/intrinsics" - "github.com/fatih/color" - - "github.com/awslabs/aws-sam-local/router" - "github.com/awslabs/goformation" - "github.com/codegangsta/cli" -) - -// messages color -var errMsg = color.New(color.FgRed).Add(color.Bold) -var warnMsg = color.New(color.FgYellow).Add(color.Bold) -var successMsg = color.New(color.FgGreen).Add(color.Bold) - -func start(c *cli.Context) { - - // Setup the logger - stderr := io.Writer(os.Stderr) - logarg := c.String("log-file") - - if len(logarg) > 0 { - if logFile, err := os.Create(logarg); err == nil { - stderr = io.Writer(logFile) - log.SetOutput(stderr) - } else { - log.Fatalf("Failed to open log file %s: %s\n", c.String("log"), err) - } - } - - filename := getTemplateFilename(c.String("template")) - template, err := goformation.OpenWithOptions(filename, &intrinsics.ProcessorOptions{ - ParameterOverrides: parseParameters(c.String("parameter-values")), - }) - if err != nil { - log.Fatalf("Failed to parse template: %s\n", err) - } - - // Check connectivity to docker - dockerVersion, err := getDockerVersion() - if err != nil { - log.Printf("Running AWS SAM projects locally requires Docker. Have you got it installed?\n") - log.Printf("%s\n", err) - os.Exit(1) - } - log.Printf("Connected to Docker %s", dockerVersion) - - // Get the working directory for the project based on - // the template directory. Also, give an opportunity for - // this to be overriden by the --docker-volume-basedir flag. - cwd := filepath.Dir(filename) - if c.String("docker-volume-basedir") != "" { - cwd = c.String("docker-volume-basedir") - } - - // Create a new router - mux := router.NewServerlessRouter(c.Bool("prefix-routing")) - - templateApis := template.GetAllAWSServerlessApiResources() - - for _, api := range templateApis { - err := mux.AddAPI(&api) - if err != nil { - errMsg.Printf("%s\n\n", err.Error()) - os.Exit(1) - } - } - - functions := template.GetAllAWSServerlessFunctionResources() - - for name, function := range functions { - - cwd := filepath.Dir(filename) - if c.String("docker-volume-basedir") != "" { - cwd = c.String("docker-volume-basedir") - } - - // Initiate a new Lambda runtime - runt, err := NewRuntime(NewRuntimeOpt{ - Cwd: cwd, - LogicalID: name, - Function: function, - Logger: stderr, - EnvOverrideFile: c.String("env-vars"), - DebugPort: c.String("debug-port"), - SkipPullImage: c.Bool("skip-pull-image"), - DockerNetwork: c.String("docker-network"), - }) - - // Check there wasn't a problem initiating the Lambda runtime - if err != nil { - if err == ErrRuntimeNotSupported { - warnMsg.Printf("Ignoring %s (%s) due to unsupported runtime (%s)\n", name, function.Handler, function.Runtime) - continue - } else { - warnMsg.Printf("Ignoring %s (%s) due to %s runtime init error: %s\n", name, function.Handler, function.Runtime, err) - continue - } - } - - // Add this AWS::Serverless::Function to the HTTP router - if err := mux.AddFunction(&function, runt.InvokeHTTP(c.String("profile"))); err != nil { - if err == router.ErrNoEventsFound { - warnMsg.Printf("Ignoring %s (%s) as no API event sources are defined\n", name, function.Handler) - } - } - } - - // Check we actually mounted some functions on our HTTP router - if len(mux.Mounts()) < 1 { - if len(functions) < 1 { - errMsg.Fprintf(stderr, "ERROR: No Serverless functions were found in your SAM template.\n") - os.Exit(1) - } - errMsg.Fprintf(stderr, "ERROR: None of the Serverless functions in your SAM template were able to be mounted. See above for errors.\n") - os.Exit(1) - } - - fmt.Fprintf(stderr, "\n") - - for _, mount := range mux.Mounts() { - if mount.Function == nil || len(mount.Function.Handler) == 0 { - msg := warnMsg.Sprint(fmt.Sprintf("WARNING: Could not find function for %s to %s resource", mount.Methods(), mount.Path)) - fmt.Fprintf(os.Stderr, "%s\n", msg) - continue - } - - msg := successMsg.Sprintf("Mounting %s (%s) at http://%s:%s%s %s", mount.Function.Handler, mount.Function.Runtime, c.String("host"), c.String("port"), mount.Path, mount.Methods()) - fmt.Fprintf(os.Stderr, "%s\n", msg) - } - - // Mount static files - if c.String("static-dir") != "" { - static := filepath.Join(cwd, c.String("static-dir")) - - if _, err := os.Stat(static); err == nil { - fmt.Fprintf(os.Stderr, "Mounting static files from %s at /\n", static) - mux.AddStaticDir(static) - } - } - - fmt.Fprintf(stderr, "\n") - fmt.Fprintf(stderr, "You can now browse to the above endpoints to invoke your functions.\n") - fmt.Fprintf(stderr, "You do not need to restart/reload SAM CLI while working on your functions,\n") - fmt.Fprintf(stderr, "changes will be reflected instantly/automatically. You only need to restart\n") - fmt.Fprintf(stderr, "SAM CLI if you update your AWS SAM template.\n") - fmt.Fprintf(stderr, "\n") - - // Start the HTTP listener - log.Fatal(http.ListenAndServe(c.String("host")+":"+c.String("port"), mux.Router())) - -} diff --git a/test/environment-overrides.json b/test/environment-overrides.json deleted file mode 100644 index a4670777db..0000000000 --- a/test/environment-overrides.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "IoTFunction": { - "TABLE_NAME": "OVERRIDE_TABLE" - } -} \ No newline at end of file diff --git a/test/templates/api-backend.yaml b/test/templates/api-backend.yaml deleted file mode 100644 index 649aef9a3e..0000000000 --- a/test/templates/api-backend.yaml +++ /dev/null @@ -1,53 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Simple CRUD webservice. State is stored in a SimpleTable (DynamoDB) resource. -Resources: - GetFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.get - Runtime: nodejs - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBReadOnlyAccess - Environment: - Variables: - TABLE_NAME: !Ref Table1 - Events: - GetResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: get - PutFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.put - Runtime: nodejs4.3 - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBFullAccess - Environment: - Variables: - TABLE_NAME: !Ref Table2 - Events: - PutResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: put - - DeleteFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.delete - Runtime: nodejs4.3 - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBFullAccess - Environment: - Variables: - TABLE_NAME: !Ref Table3 - Events: - DeleteResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: delete \ No newline at end of file diff --git a/test/templates/api-missing-method.yaml b/test/templates/api-missing-method.yaml deleted file mode 100644 index 314aaf6559..0000000000 --- a/test/templates/api-missing-method.yaml +++ /dev/null @@ -1,48 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Simple API Endpoint configured using Swagger specified inline and backed by a Lambda function -Resources: - MyApi: - Type: AWS::Serverless::Api - Properties: - StageName: prod - DefinitionBody: - swagger: "2.0" - info: - title: - Ref: AWS::StackName - paths: - "/get": - get: - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: - Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations - responses: {} - "/badget": - get: - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: - Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations - responses: {} - - - - - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs6.10 - CodeUri: func/ - Events: - GetApi: - Type: Api - Properties: - Path: /get - Method: GET - RestApiId: - Ref: MyApi \ No newline at end of file diff --git a/test/templates/api-swagger-intrinsic.yaml b/test/templates/api-swagger-intrinsic.yaml deleted file mode 100644 index 429cb977e8..0000000000 --- a/test/templates/api-swagger-intrinsic.yaml +++ /dev/null @@ -1,1038 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Swagger demo for Integration Requests - -Parameters: - - NotificationEmail: - Type: String - Description: Email address to subscribe to SNS topic and receive notifications from Notifier Workflow - - SlackToken: - Type: String - Description: Legacy Slack Token (xoxp-ywz) to send messages on channel - Default: None - -Resources: - - - SnsNotifierServiceRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowLambdaServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - "lambda.amazonaws.com" - Policies: - - - PolicyName: "PublishSnsTopic" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "sns:Publish" - Resource: - - !Ref NotifierSNSTopic - - "*" # can't restrict on SMS number yet, so * - - - EmailNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: email_sns.lambda_handler - Runtime: python2.7 - CodeUri: ../code/email/ - Role: !GetAtt SnsNotifierServiceRole.Arn - Environment: - Variables: - NOTIFIER_TOPIC: !Ref NotifierSNSTopic - - - SmsNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: sms_sns.lambda_handler - Runtime: python2.7 - CodeUri: ../code/sms/ - Role: !GetAtt SnsNotifierServiceRole.Arn - Environment: - Variables: - NOTIFIER_TOPIC: !Ref NotifierSNSTopic - - # No need for extra permissions other than Basic Execution - # SAM takes care of creating basic IAM Role if none is provided - SlackNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: slack.lambda_handler - Runtime: python2.7 - CodeUri: ../code/slack.zip # Slack contains 3rd party libraries - Environment: - Variables: - SLACK_TOKEN: !Ref SlackToken - # IAM Role API Gateway will assume in order to call StepFunctions StartExecution API - ApiGatewayStepFunctionsRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowApiGatewayServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - "apigateway.amazonaws.com" - Policies: - - - PolicyName: "CallStepFunctions" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "states:StartExecution" - Resource: - - !Ref StepFunctionStateMachine - - AnotherRandomAPI: - Type: AWS::Serverless::Api - Properties: - StageName: prod - DefinitionBody: - swagger: "2.0" - info: - description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" - version: 1.0.0 - title: Swagger Petstore YAML - termsOfService: "http://swagger.io/terms/" - contact: - email: "apiteam@swagger.io" - license: - name: Apache 2.0 - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - basePath: /v2 - tags: - - name: pet - description: Everything about your Pets - externalDocs: - description: Find out more - url: "http://swagger.io" - - name: store - description: Operations about user - - name: user - description: Access to Petstore orders - externalDocs: - description: Find out more about our store - url: "http://swagger.io" - schemes: - - http - paths: - /pet: - post: - tags: - - pet - summary: Add a new pet to the store - x-swagger-router-controller: SampleController - description: "" - operationId: addPet - consumes: - - application/json - - application/xml - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Pet object that needs to be added to the store - required: false - schema: - $ref: "#/definitions/Pet" - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - "write:pets" - - "read:pets" - put: - tags: - - pet - summary: Update an existing pet - description: "" - operationId: updatePet - consumes: - - application/json - - application/xml - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Pet object that needs to be added to the store - required: false - schema: - $ref: "#/definitions/Pet" - responses: - "400": - description: Invalid ID supplied - "404": - description: Pet not found - "405": - description: Validation exception - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByStatus: - get: - tags: - - pet - summary: Finds Pets by status - description: Multiple status values can be provided with comma seperated strings - operationId: findPetsByStatus - consumes: - - application/xml - - application/json - - multipart/form-data - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: status - in: query - description: Status values that need to be considered for filter - required: false - type: array - items: - type: string - collectionFormat: multi - default: available - enum: - - available - - pending - - sold - - name: testlong - in: query - description: Status values that need to be considered for filter - required: false - type: array - items: - type: long - collectionFormat: multi - default: available - enum: - - 1234567890123456 - - 345 - - 678 - responses: - "200": - description: successful operation - schema: - type: array - items: - $ref: "#/definitions/Pet" - "400": - description: Invalid status value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByTags: - get: - tags: - - pet - summary: Finds Pets by tags - description: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." - operationId: findPetsByTags - produces: - - application/xml - - application/json - parameters: - - name: tags - in: query - description: Tags to filter by - required: false - type: array - items: - type: string - collectionFormat: multi - responses: - "200": - description: successful operation - schema: - type: array - items: - $ref: "#/definitions/Pet" - "400": - description: Invalid tag value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - "/pet/{petId}": - get: - tags: - - pet - summary: Find pet by ID - description: Returns a single pet - operationId: getPetById - consumes: - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: petId - in: path - description: ID of pet to return - required: true - type: integer - format: int64 - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Pet" - "400": - description: Invalid ID supplied - "404": - description: Pet not found - security: - - api_key: [] - - petstore_auth: - - "write:pets" - - "read:pets" - post: - tags: - - pet - summary: Updates a pet in the store with form data - description: "" - operationId: updatePetWithForm - consumes: - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: petId - in: path - description: ID of pet that needs to be updated - required: true - type: string - - name: name - in: formData - description: Updated name of the pet - required: false - type: string - - name: status - in: formData - description: Updated status of the pet - required: false - type: string - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - "write:pets" - - "read:pets" - delete: - tags: - - pet - summary: Deletes a pet - description: "" - operationId: deletePet - consumes: - - multipart/form-data - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: api_key - in: header - description: "" - required: false - type: string - - name: petId - in: path - description: Pet id to delete - required: true - type: integer - format: int64 - responses: - "400": - description: Invalid pet value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - "/pet/{petId}/uploadImage": - post: - tags: - - pet - summary: uploads an image - x-swagger-router-controller: SampleController - description: "" - operationId: uploadFile - consumes: - - multipart/form-data - produces: - - application/json - parameters: - - name: petId - in: path - description: ID of pet to update - required: true - type: integer - format: int64 - - name: additionalMetadata - in: formData - description: Additional data to pass to server - required: false - type: string - - name: file - in: formData - description: file to upload - required: false - type: file - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/ApiResponse" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /store/inventory: - get: - tags: - - store - summary: Returns pet inventories by status - description: Returns a map of status codes to quantities - operationId: getInventory - produces: - - application/json - parameters: [] - responses: - "200": - description: successful operation - schema: - type: object - additionalProperties: - type: integer - format: int32 - security: - - api_key: [] - /store/order: - post: - tags: - - store - summary: Place an order for a pet - description: "" - operationId: placeOrder - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: order placed for purchasing the pet - required: false - schema: - $ref: "#/definitions/Order" - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Order" - "400": - description: Invalid Order - "/store/order/{orderId}": - get: - tags: - - store - summary: Find purchase order by ID - description: "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - operationId: getOrderById - produces: - - application/xml - - application/json - parameters: - - name: orderId - in: path - description: ID of pet that needs to be fetched - required: true - type: string - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Order" - "400": - description: Invalid ID supplied - "404": - description: Order not found - delete: - tags: - - store - summary: Delete purchase order by ID - description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - operationId: deleteOrder - produces: - - application/xml - - application/json - parameters: - - name: orderId - in: path - description: ID of the order that needs to be deleted - required: true - type: string - responses: - "400": - description: Invalid ID supplied - "404": - description: Order not found - /user: - post: - tags: - - user - summary: Create user - description: This can only be done by the logged in user. - operationId: createUser - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Created user object - required: false - schema: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/createWithArray: - post: - tags: - - user - summary: Creates list of users with given input array - description: "" - operationId: createUsersWithArrayInput - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: List of user object - required: false - schema: - type: array - items: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/createWithList: - post: - tags: - - user - summary: Creates list of users with given input array - description: "" - operationId: createUsersWithListInput - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: List of user object - required: false - schema: - type: array - items: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/login: - get: - tags: - - user - summary: Logs user into the system - description: "" - operationId: loginUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: query - description: The user name for login - required: false - type: string - - name: password - in: query - description: The password for login in clear text - required: false - type: string - responses: - "200": - description: successful operation - schema: - type: string - headers: - X-Rate-Limit: - type: integer - format: int32 - description: calls per hour allowed by the user - X-Expires-After: - type: string - format: date-time - description: date in UTC when toekn expires - "400": - description: Invalid username/password supplied - x-amazon-apigateway-integration: - uri: - Fn::GetAtt: [ "SmsNotifierServiceFunction", "Arn" ] - httpMethod: POST - /user/logout: - get: - tags: - - user - summary: Logs out current logged in user session - description: "" - operationId: logoutUser - produces: - - application/xml - - application/json - parameters: [] - responses: - default: - description: successful operation - x-amazon-apigateway-integration: - uri: - Fn::Sub: - - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${FunctionName}/invocations" - - {"FunctionName": !Ref EmailNotifierServiceFunction } - httpMethod: POST - "/user/{username}": - get: - tags: - - user - summary: Get user by user name - description: "" - operationId: getUserByName - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: "The name that needs to be fetched. Use user1 for testing. " - required: true - type: string - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/User" - "400": - description: Invalid username supplied - "404": - description: User not found - put: - tags: - - user - summary: Updated user - description: This can only be done by the logged in user. - operationId: updateUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: name that need to be deleted - required: true - type: string - - in: body - name: body - description: Updated user object - required: false - schema: - $ref: "#/definitions/User" - responses: - "400": - description: Invalid user supplied - "404": - description: User not found - delete: - tags: - - user - summary: Delete user - description: This can only be done by the logged in user. - operationId: deleteUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: The name that needs to be deleted - required: true - type: string - responses: - "400": - description: Invalid username supplied - "404": - description: User not found - securityDefinitions: - petstore_auth: - type: oauth2 - authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" - flow: implicit - scopes: - "write:pets": modify pets in your account - "read:pets": read your pets - api_key: - type: apiKey - name: api_key - in: header - definitions: - Order: - properties: - id: - type: integer - format: int64 - petId: - type: integer - format: int64 - quantity: - type: integer - format: int32 - shipDate: - type: string - format: date-time - status: - type: string - description: Order Status - enum: - - placed - - approved - - delivered - complete: - type: boolean - xml: - name: Order - Category: - properties: - id: - type: integer - format: int64 - name: - type: string - xml: - name: Category - User: - properties: - id: - type: integer - format: int64 - username: - type: string - firstName: - type: string - lastName: - type: string - email: - type: string - password: - type: string - phone: - type: string - userStatus: - type: integer - format: int32 - description: User Status - xml: - name: User - Tag: - properties: - id: - type: integer - format: int64 - name: - type: string - xml: - name: Tag - Pet: - required: - - name - - photoUrls - properties: - id: - type: integer - format: int64 - category: - $ref: "#/definitions/Category" - name: - type: string - example: doggie - photoUrls: - type: array - xml: - name: photoUrl - wrapped: true - items: - type: string - tags: - type: array - xml: - name: tag - wrapped: true - items: - $ref: "#/definitions/Tag" - status: - type: string - description: pet status in the store - enum: - - available - - pending - - sold - xml: - name: Pet - ApiResponse: - properties: - code: - type: integer - format: int32 - type: - type: string - message: - type: string - xml: - name: "##default" - externalDocs: - description: Find out more about Swagger - url: "http://swagger.io" - StepFunctionsAPI: - Type: AWS::Serverless::Api - Properties: - StageName: dev - DefinitionBody: - swagger: "2.0" - basePath: /prod - info: - title: AwsSamExample - schemes: - - https - paths: - /: - x-amazon-apigateway-any-method: - security: - - test-authorizer: [] - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - responses: - default: - statusCode: 200 - # NOTE: Replace <> and <> fields - uri: arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations - - passthroughBehavior: when_no_match - httpMethod: POST - type: aws_proxy - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - headers: - Access-Control-Allow-Origin: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Headers: - type: string - x-amazon-apigateway-integration: - type: aws - uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:012345678901:function:HelloWorld/invocations - httpMethod: POST - credentials: arn:aws:iam::012345678901:role/apigateway-invoke-lambda-exec-role - requestTemplates: - application/json: '#set ($root=$input.path(''$'')) { "stage": "$root.name", "user-id": - "$root.key" }' - application/xml: "#set ($root=$input.path('$')) $root.name " - requestParameters: - integration.request.path.stage: method.request.querystring.version - integration.request.querystring.provider: method.request.querystring.vendor - cacheNamespace: cache namespace - cacheKeyParameters: [] - responses: - '302': - statusCode: '302' - responseParameters: - method.response.header.Location: integration.response.body.redirect.url - 2\d{2}: - statusCode: '200' - responseParameters: - method.response.header.requestId: integration.response.header.cid - responseTemplates: - application/json: '#set ($root=$input.path(''$'')) { "stage": "$root.name", - "user-id": "$root.key" }' - application/xml: "#set ($root=$input.path('$')) $root.name " - default: - statusCode: '400' - responseParameters: - method.response.header.test-method-response-header: "'static value'" - x-amazon-apigateway-integration: - uri: !Sub - - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${EmailNotifierServiceFunction}${Test}/invocations" - - { "Test": "ABCD", "OtherTest": !Ref something } - httpMethod: POST - StepFunctionsServiceRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowStepFunctionsServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - !Sub "states.${AWS::Region}.amazonaws.com" - Policies: - - - PolicyName: "CallLambdaFunctions" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "lambda:InvokeFunction" - Resource: - - !Sub "${SlackNotifierServiceFunction.Arn}" - - !Sub "${EmailNotifierServiceFunction.Arn}" - - !Sub "${SmsNotifierServiceFunction.Arn}" - - StepFunctionStateMachine: - Type: "AWS::StepFunctions::StateMachine" - Properties: - DefinitionString: !Sub | - { - "Comment": "Demo for API GW->SFN", - "StartAt": "NotifierState", - "States": { - "NotifierState": { - "Type" : "Choice", - "Choices": [ - { - "Variable": "$.notifier", - "StringEquals": "Email", - "Next": "EmailNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Sms", - "Next": "SmsNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Slack", - "Next": "SlackNotifier" - }, - { - "Variable": "$.notify", - "StringEquals": "Twilio", - "Next": "NotImplementedYet" - } - ], - "Default": "IgnoreNotification" - }, - "IgnoreNotification": { - "Type": "Pass", - "Next": "SayHi" - }, - "NotImplementedYet": { - "Type": "Fail", - "Cause": "Feature not implemented yet!" - }, - "EmailNotifier": { - "Type": "Task", - "Resource": "${EmailNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SlackNotifier": { - "Type": "Task", - "Resource": "${SlackNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SmsNotifier": { - "Type": "Task", - "Resource": "${SmsNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SayHi": { - "Type": "Pass", - "Result": "Hi!", - "End": true - } - } - } - RoleArn: !GetAtt StepFunctionsServiceRole.Arn - NotifierSNSTopic: - Type: AWS::SNS::Topic - Properties: - Subscription: - - Endpoint: !Ref NotificationEmail - Protocol: email -Outputs: - NotifyUrl: - Description: Notify Workflow URL - Value: !Sub "https://${StepFunctionsAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/notify" - - StepFunctionsStateMachine: - Description: Step Functions State Machine ARN - Value: !Ref StepFunctionStateMachine \ No newline at end of file diff --git a/test/templates/api-swagger-plain.yaml b/test/templates/api-swagger-plain.yaml deleted file mode 100644 index cc7f499ce4..0000000000 --- a/test/templates/api-swagger-plain.yaml +++ /dev/null @@ -1,1111 +0,0 @@ -AWSTemplateFormatVersion: "2010-09-09" -Description: "Swagger demo for Integration Requests" -Outputs: - NotifyUrl: - Description: "Notify Workflow URL" - Value: "https://${StepFunctionsAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/notify" - StepFunctionsStateMachine: - Description: "Step Functions State Machine ARN" - Value: StepFunctionStateMachine -Parameters: - NotificationEmail: - Description: "Email address to subscribe to SNS topic and receive notifications from Notifier Workflow" - Type: String - SlackToken: - Default: None - Description: "Legacy Slack Token (xoxp-ywz) to send messages on channel" - Type: String -Resources: - AnotherRandomAPI: - Properties: - DefinitionBody: - basePath: /v2 - definitions: - ApiResponse: - properties: - code: - format: int32 - type: integer - message: - type: string - type: - type: string - xml: - name: "##default" - Category: - properties: - id: - format: int64 - type: integer - name: - type: string - xml: - name: Category - Order: - properties: - complete: - type: boolean - id: - format: int64 - type: integer - petId: - format: int64 - type: integer - quantity: - format: int32 - type: integer - shipDate: - format: date-time - type: string - status: - description: "Order Status" - enum: - - placed - - approved - - delivered - type: string - xml: - name: Order - Pet: - properties: - category: - $ref: "#/definitions/Category" - id: - format: int64 - type: integer - name: - example: doggie - type: string - photoUrls: - items: - type: string - type: array - xml: - name: photoUrl - wrapped: true - status: - description: "pet status in the store" - enum: - - available - - pending - - sold - type: string - tags: - items: - $ref: "#/definitions/Tag" - type: array - xml: - name: tag - wrapped: true - required: - - name - - photoUrls - xml: - name: Pet - Tag: - properties: - id: - format: int64 - type: integer - name: - type: string - xml: - name: Tag - User: - properties: - email: - type: string - firstName: - type: string - id: - format: int64 - type: integer - lastName: - type: string - password: - type: string - phone: - type: string - userStatus: - description: "User Status" - format: int32 - type: integer - username: - type: string - xml: - name: User - externalDocs: - description: "Find out more about Swagger" - url: "http://swagger.io" - info: - contact: - email: apiteam@swagger.io - description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" - license: - name: "Apache 2.0" - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - termsOfService: "http://swagger.io/terms/" - title: "Swagger Petstore YAML" - version: "1.0.0" - paths: - /pet: - post: - consumes: - - application/json - - application/xml - description: "" - operationId: addPet - parameters: - - - description: "Pet object that needs to be added to the store" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Pet" - produces: - - application/xml - - application/json - responses: - "405": - description: "Invalid input" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Add a new pet to the store" - tags: - - pet - x-swagger-router-controller: SampleController - put: - consumes: - - application/json - - application/xml - description: "" - operationId: updatePet - parameters: - - - description: "Pet object that needs to be added to the store" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Pet" - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid ID supplied" - "404": - description: "Pet not found" - "405": - description: "Validation exception" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Update an existing pet" - tags: - - pet - /pet/findByStatus: - get: - consumes: - - application/xml - - application/json - - multipart/form-data - - application/x-www-form-urlencoded - description: "Multiple status values can be provided with comma seperated strings" - operationId: findPetsByStatus - parameters: - - - collectionFormat: multi - default: available - description: "Status values that need to be considered for filter" - enum: - - available - - pending - - sold - in: query - items: - type: string - name: status - required: false - type: array - - - collectionFormat: multi - default: available - description: "Status values that need to be considered for filter" - enum: - - 1234567890123456 - - 345 - - 678 - in: query - items: - type: long - name: testlong - required: false - type: array - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - items: - $ref: "#/definitions/Pet" - type: array - "400": - description: "Invalid status value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Finds Pets by status" - tags: - - pet - /pet/findByTags: - get: - description: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." - operationId: findPetsByTags - parameters: - - - collectionFormat: multi - description: "Tags to filter by" - in: query - items: - type: string - name: tags - required: false - type: array - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - items: - $ref: "#/definitions/Pet" - type: array - "400": - description: "Invalid tag value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Finds Pets by tags" - tags: - - pet - ? "/pet/{petId}" - : - delete: - consumes: - - multipart/form-data - - application/x-www-form-urlencoded - description: "" - operationId: deletePet - parameters: - - - description: "" - in: header - name: api_key - required: false - type: string - - - description: "Pet id to delete" - format: int64 - in: path - name: petId - required: true - type: integer - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid pet value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Deletes a pet" - tags: - - pet - get: - consumes: - - application/x-www-form-urlencoded - description: "Returns a single pet" - operationId: getPetById - parameters: - - - description: "ID of pet to return" - format: int64 - in: path - name: petId - required: true - type: integer - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Pet" - "400": - description: "Invalid ID supplied" - "404": - description: "Pet not found" - security: - - - api_key: [] - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Find pet by ID" - tags: - - pet - post: - consumes: - - application/x-www-form-urlencoded - description: "" - operationId: updatePetWithForm - parameters: - - - description: "ID of pet that needs to be updated" - in: path - name: petId - required: true - type: string - - - description: "Updated name of the pet" - in: formData - name: name - required: false - type: string - - - description: "Updated status of the pet" - in: formData - name: status - required: false - type: string - produces: - - application/xml - - application/json - responses: - "405": - description: "Invalid input" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Updates a pet in the store with form data" - tags: - - pet - ? "/pet/{petId}/uploadImage" - : - post: - consumes: - - multipart/form-data - description: "" - operationId: uploadFile - parameters: - - - description: "ID of pet to update" - format: int64 - in: path - name: petId - required: true - type: integer - - - description: "Additional data to pass to server" - in: formData - name: additionalMetadata - required: false - type: string - - - description: "file to upload" - in: formData - name: file - required: false - type: file - produces: - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/ApiResponse" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "uploads an image" - tags: - - pet - x-swagger-router-controller: SampleController - /store/inventory: - get: - description: "Returns a map of status codes to quantities" - operationId: getInventory - parameters: [] - produces: - - application/json - responses: - "200": - description: "successful operation" - schema: - additionalProperties: - format: int32 - type: integer - type: object - security: - - - api_key: [] - summary: "Returns pet inventories by status" - tags: - - store - /store/order: - post: - description: "" - operationId: placeOrder - parameters: - - - description: "order placed for purchasing the pet" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Order" - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Order" - "400": - description: "Invalid Order" - summary: "Place an order for a pet" - tags: - - store - ? "/store/order/{orderId}" - : - delete: - description: "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" - operationId: deleteOrder - parameters: - - - description: "ID of the order that needs to be deleted" - in: path - name: orderId - required: true - type: string - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid ID supplied" - "404": - description: "Order not found" - summary: "Delete purchase order by ID" - tags: - - store - get: - description: "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - operationId: getOrderById - parameters: - - - description: "ID of pet that needs to be fetched" - in: path - name: orderId - required: true - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Order" - "400": - description: "Invalid ID supplied" - "404": - description: "Order not found" - summary: "Find purchase order by ID" - tags: - - store - /user: - post: - description: "This can only be done by the logged in user." - operationId: createUser - parameters: - - - description: "Created user object" - in: body - name: body - required: false - schema: - $ref: "#/definitions/User" - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Create user" - tags: - - user - /user/createWithArray: - post: - description: "" - operationId: createUsersWithArrayInput - parameters: - - - description: "List of user object" - in: body - name: body - required: false - schema: - items: - $ref: "#/definitions/User" - type: array - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Creates list of users with given input array" - tags: - - user - /user/createWithList: - post: - description: "" - operationId: createUsersWithListInput - parameters: - - - description: "List of user object" - in: body - name: body - required: false - schema: - items: - $ref: "#/definitions/User" - type: array - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Creates list of users with given input array" - tags: - - user - /user/login: - get: - description: "" - operationId: loginUser - parameters: - - - description: "The user name for login" - in: query - name: username - required: false - type: string - - - description: "The password for login in clear text" - in: query - name: password - required: false - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - headers: - X-Expires-After: - description: "date in UTC when toekn expires" - format: date-time - type: string - X-Rate-Limit: - description: "calls per hour allowed by the user" - format: int32 - type: integer - schema: - type: string - "400": - description: "Invalid username/password supplied" - summary: "Logs user into the system" - tags: - - user - /user/logout: - get: - description: "" - operationId: logoutUser - parameters: [] - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Logs out current logged in user session" - tags: - - user - ? "/user/{username}" - : - delete: - description: "This can only be done by the logged in user." - operationId: deleteUser - parameters: - - - description: "The name that needs to be deleted" - in: path - name: username - required: true - type: string - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid username supplied" - "404": - description: "User not found" - summary: "Delete user" - tags: - - user - get: - description: "" - operationId: getUserByName - parameters: - - - description: "The name that needs to be fetched. Use user1 for testing. " - in: path - name: username - required: true - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/User" - "400": - description: "Invalid username supplied" - "404": - description: "User not found" - summary: "Get user by user name" - tags: - - user - put: - description: "This can only be done by the logged in user." - operationId: updateUser - parameters: - - - description: "name that need to be deleted" - in: path - name: username - required: true - type: string - - - description: "Updated user object" - in: body - name: body - required: false - schema: - $ref: "#/definitions/User" - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid user supplied" - "404": - description: "User not found" - summary: "Updated user" - tags: - - user - schemes: - - http - securityDefinitions: - api_key: - in: header - name: api_key - type: apiKey - petstore_auth: - authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" - flow: implicit - scopes: - ? "read:pets" - : "read your pets" - ? "write:pets" - : "modify pets in your account" - type: oauth2 - swagger: "2.0" - tags: - - - description: "Everything about your Pets" - externalDocs: - description: "Find out more" - url: "http://swagger.io" - name: pet - - - description: "Operations about user" - name: store - - - description: "Access to Petstore orders" - externalDocs: - description: "Find out more about our store" - url: "http://swagger.io" - name: user - StageName: prod - Type: "AWS::Serverless::Api" - ApiGatewayStepFunctionsRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - apigateway.amazonaws.com - Sid: AllowApiGatewayServiceToAssumeRole - Version: "2012-10-17" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "states:StartExecution" - Effect: Allow - Resource: - - StepFunctionStateMachine - Version: "2012-10-17" - PolicyName: CallStepFunctions - Type: "AWS::IAM::Role" - EmailNotifierServiceFunction: - Properties: - CodeUri: ../code/email/ - Environment: - Variables: - NOTIFIER_TOPIC: NotifierSNSTopic - Handler: email_sns.lambda_handler - Role: SnsNotifierServiceRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - NotifierSNSTopic: - Properties: - Subscription: - - - Endpoint: NotificationEmail - Protocol: email - Type: "AWS::SNS::Topic" - SlackNotifierServiceFunction: - Properties: - CodeUri: ../code/slack.zip - Environment: - Variables: - SLACK_TOKEN: SlackToken - Handler: slack.lambda_handler - Runtime: python2.7 - Type: "AWS::Serverless::Function" - SmsNotifierServiceFunction: - Properties: - CodeUri: ../code/sms/ - Environment: - Variables: - NOTIFIER_TOPIC: NotifierSNSTopic - Handler: sms_sns.lambda_handler - Role: SnsNotifierServiceRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - SnsNotifierServiceRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - lambda.amazonaws.com - Sid: AllowLambdaServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "sns:Publish" - Effect: Allow - Resource: - - NotifierSNSTopic - - "*" - Version: "2012-10-17" - PolicyName: PublishSnsTopic - Type: "AWS::IAM::Role" - StepFunctionStateMachine: - Properties: - DefinitionString: | - { - "Comment": "Demo for API GW->SFN", - "StartAt": "NotifierState", - "States": { - "NotifierState": { - "Type" : "Choice", - "Choices": [ - { - "Variable": "$.notifier", - "StringEquals": "Email", - "Next": "EmailNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Sms", - "Next": "SmsNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Slack", - "Next": "SlackNotifier" - }, - { - "Variable": "$.notify", - "StringEquals": "Twilio", - "Next": "NotImplementedYet" - } - ], - "Default": "IgnoreNotification" - }, - "IgnoreNotification": { - "Type": "Pass", - "Next": "SayHi" - }, - "NotImplementedYet": { - "Type": "Fail", - "Cause": "Feature not implemented yet!" - }, - "EmailNotifier": { - "Type": "Task", - "Resource": "${EmailNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SlackNotifier": { - "Type": "Task", - "Resource": "${SlackNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SmsNotifier": { - "Type": "Task", - "Resource": "${SmsNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SayHi": { - "Type": "Pass", - "Result": "Hi!", - "End": true - } - } - } - RoleArn: StepFunctionsServiceRole.Arn - Type: "AWS::StepFunctions::StateMachine" - StepFunctionsAPI: - Properties: - DefinitionBody: - basePath: /prod - definitions: - Empty: - title: "Empty Schema" - type: object - info: - title: AwsSamExample - paths: - /: - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: "200 response" - headers: - Access-Control-Allow-Headers: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Origin: - type: string - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - cacheKeyParameters: [] - cacheNamespace: "cache namespace" - credentials: "arn:aws:iam::012345678901:role/apigateway-invoke-lambda-exec-role" - httpMethod: POST - requestParameters: - integration.request.path.stage: method.request.querystring.version - integration.request.querystring.provider: method.request.querystring.vendor - requestTemplates: - application/json: "#set ($root=$input.path('$')) { \"stage\": \"$root.name\", \"user-id\": \"$root.key\" }" - application/xml: "#set ($root=$input.path('$')) $root.name " - responses: - "2\\d{2}": - responseParameters: - method.response.header.requestId: integration.response.header.cid - responseTemplates: - application/json: "#set ($root=$input.path('$')) { \"stage\": \"$root.name\", \"user-id\": \"$root.key\" }" - application/xml: "#set ($root=$input.path('$')) $root.name " - statusCode: "200" - "302": - responseParameters: - method.response.header.Location: integration.response.body.redirect.url - statusCode: "302" - default: - responseParameters: - method.response.header.test-method-response-header: "'static value'" - statusCode: "400" - type: aws - uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:012345678901:function:HelloWorld/invocations" - x-amazon-apigateway-any-method: - produces: - - application/json - responses: - 200: - description: "200 response" - schema: - $ref: "#/definitions/Empty" - security: - - - test-authorizer: [] - x-amazon-apigateway-integration: - httpMethod: POST - passthroughBehavior: when_no_match - responses: - default: - statusCode: 200 - type: aws_proxy - uri: EmailNotifierServiceFunction.Arn - "/{proxy+}": - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: "200 response" - headers: - Access-Control-Allow-Headers: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Origin: - type: string - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - passthroughBehavior: when_no_match - requestTemplates: - application/json: "{\"statusCode\": 200}" - responses: - default: - responseParameters: - method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" - method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'" - method.response.header.Access-Control-Allow-Origin: "'*'" - statusCode: 200 - type: mock - x-amazon-apigateway-any-method: - parameters: - - - in: path - name: proxy - required: true - type: string - produces: - - application/json - responses: {} - x-amazon-apigateway-auth: - type: aws_iam - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: "arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations" - schemes: - - https - securityDefinitions: - test-authorizer: - in: header - name: Authorization - type: apiKey - x-amazon-apigateway-authorizer: - authorizerCredentials: "arn:aws:iam::account-id:role" - authorizerResultTtlInSeconds: 60 - authorizerUri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:account-id:function:function-name/invocations" - identityValidationExpression: "^x-[a-z]+" - type: token - x-amazon-apigateway-authtype: oauth2 - swagger: "2.0" - StageName: dev - Type: "AWS::Serverless::Api" - StepFunctionsServiceRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - "states.${AWS::Region}.amazonaws.com" - Sid: AllowStepFunctionsServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "lambda:InvokeFunction" - Effect: Allow - Resource: - - "${SlackNotifierServiceFunction.Arn}" - - "${EmailNotifierServiceFunction.Arn}" - - "${SmsNotifierServiceFunction.Arn}" - Version: "2012-10-17" - PolicyName: CallLambdaFunctions - Type: "AWS::IAM::Role" -Transform: "AWS::Serverless-2016-10-31" diff --git a/test/templates/aws-common-string-or-s3-location.yaml b/test/templates/aws-common-string-or-s3-location.yaml deleted file mode 100644 index f11107a9fd..0000000000 --- a/test/templates/aws-common-string-or-s3-location.yaml +++ /dev/null @@ -1,25 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: SAM template for testing CodeUri property parsing -Resources: - - CodeUriWithS3LocationSpecifiedAsString: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs - CodeUri: s3://testbucket/testkey.zip - - CodeUriWithS3LocationSpecifiedAsObject: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs - CodeUri: - Bucket: testbucket - Key: testkey.zip - Version: 5 - - CodeUriWithString: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs - CodeUri: ./testfolder diff --git a/test/templates/codestar/java.yml b/test/templates/codestar/java.yml deleted file mode 100644 index 98d1966c8e..0000000000 --- a/test/templates/codestar/java.yml +++ /dev/null @@ -1,41 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: -- AWS::Serverless-2016-10-31 -- AWS::CodeStar - -Parameters: - ProjectId: - Type: String - Description: AWS CodeStar projectID used to associate new resources to team members - -Resources: - GetHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler - CodeUri: target/ - Runtime: java8 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - GetEvent: - Type: Api - Properties: - Path: / - Method: get - - PostHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler - Runtime: java8 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - PostEvent: - Type: Api - Properties: - Path: / - Method: post diff --git a/test/templates/codestar/nodejs.yml b/test/templates/codestar/nodejs.yml deleted file mode 100644 index f28f69f5d6..0000000000 --- a/test/templates/codestar/nodejs.yml +++ /dev/null @@ -1,25 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: -- AWS::Serverless-2016-10-31 -- AWS::CodeStar - -Parameters: - ProjectId: - Type: String - Description: AWS CodeStar projectID used to associate new resources to team members - -Resources: - GetHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: index.get - Runtime: nodejs4.3 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - GetEvent: - Type: Api - Properties: - Path: / - Method: get \ No newline at end of file diff --git a/test/templates/codestar/python.yml b/test/templates/codestar/python.yml deleted file mode 100644 index 97ae2a910d..0000000000 --- a/test/templates/codestar/python.yml +++ /dev/null @@ -1,30 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: -- AWS::Serverless-2016-10-31 -- AWS::CodeStar - -Parameters: - ProjectId: - Type: String - Description: CodeStar projectId used to associate new resources to team members - -Resources: - HelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: python2.7 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - GetEvent: - Type: Api - Properties: - Path: / - Method: get - PostEvent: - Type: Api - Properties: - Path: / - Method: post diff --git a/test/templates/function-2016-10-31.yaml b/test/templates/function-2016-10-31.yaml deleted file mode 100644 index 376ff804c0..0000000000 --- a/test/templates/function-2016-10-31.yaml +++ /dev/null @@ -1,29 +0,0 @@ -Transform: AWS::Serverless-2016-10-31 -Resources: - Function20161031: - Type: AWS::Serverless::Function - Properties: - Handler: file.method - Runtime: nodejs - CodeUri: s3://bucket/path/key - FunctionName: functionname - Description: description - MemorySize: 128 - Timeout: 30 - Role: aws::arn::123456789012::some/role - Policies: - - AmazonDynamoDBFullAccess - Environment: - Variables: - NAME: VALUE - VpcConfig: - SecurityGroupIds: - - String - SubnetIds: - - String - Events: - TestApi: - Type: Api - Properties: - Path: /testing - Method: any \ No newline at end of file diff --git a/test/templates/function-environment-variables.yaml b/test/templates/function-environment-variables.yaml deleted file mode 100644 index ea1682cd5e..0000000000 --- a/test/templates/function-environment-variables.yaml +++ /dev/null @@ -1,104 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 - -Description: | - Use this section to describe your Serverless project - -Parameters: - # Optional: Use parameters to pass in runtime configuration (such as a database connection string) - # See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html - - ExampleParameter: - Description: This is just an example parameter, used to show how to pass in environment variables to Lambda - Type: String - Default: SomeValue - -Resources: - # Place your project resources here (AWS Lambda functions, API Gateway) etc - - EnvironmentVariableTestFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: filename.method - Environment: - Variables: - STRING_ENV_VAR: test123 - Events: - GetRequest: - Type: Api - Properties: - Path: / - Method: get - - NoValueEnvironmentVariableTestFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: filename.method - Environment: - Variables: - EMPTY_ENV_VAR: "" - Events: - GetRequest: - Type: Api - Properties: - Path: / - Method: get - - SubEnvironmentVariableTestFunction: - Type: AWS::Serverless::Function - Properties: - FunctionName: sub - Runtime: nodejs6.10 - Handler: filename.method - Environment: - Variables: - SUB_ENV_VAR: !Sub Hello - Events: - GetRequest: - Type: Api - Properties: - Path: / - Method: get - - NonExistSubEnvironmentVariableTestFunction: - Type: AWS::Serverless::Function - Properties: - FunctionName: sub - Runtime: nodejs6.10 - Handler: filename.method - Environment: - Variables: - SUB_REF_ENV_VAR: !Sub Hello-${ThisReferenceDoesntExist} - Events: - GetRequest: - Type: Api - Properties: - Path: / - Method: get - - IntrinsicEnvironmentVariableTestFunction: - Type: AWS::Serverless::Function - Properties: - Runtime: nodejs6.10 - Handler: filename.method - Environment: - Variables: - REF_ENV_VAR: !Ref ExampleParameter - Events: - GetRequest: - Type: Api - Properties: - Path: / - Method: get - -Outputs: - # Optional: The optional Outputs section declares output values that you can import into other stacks - # (to create cross-stack references), return in response (to describe stack calls), or view on the - # AWS CloudFormation console. - # See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html - - ExampleOutput: - Description: This is an example output, used to show how to return the ARN of the created Lambda function - Value: !Ref ExampleFunction diff --git a/test/templates/open-api/pet-store-proxy.json b/test/templates/open-api/pet-store-proxy.json deleted file mode 100644 index c0300506d5..0000000000 --- a/test/templates/open-api/pet-store-proxy.json +++ /dev/null @@ -1,234 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "Swagger API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "petstore.swagger.io", - "basePath": "/api", - "schemes": [ - "http" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/NewPet" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - } - }, - "/pets/{proxy+}": { - "x-amazon-apigateway-any-method": { - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:AnyMethod/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - } - } - }, - "definitions": { - "Pet": { - "type": "object", - "allOf": [ - { - "$ref": "#/definitions/NewPet" - }, - { - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "NewPet": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "type": "object", - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/test/templates/open-api/pet-store-simple.json b/test/templates/open-api/pet-store-simple.json deleted file mode 100644 index 65106f5e58..0000000000 --- a/test/templates/open-api/pet-store-simple.json +++ /dev/null @@ -1,266 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "version": "1.0.0", - "title": "Swagger Petstore", - "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "name": "Swagger API Team" - }, - "license": { - "name": "MIT" - } - }, - "host": "petstore.swagger.io", - "basePath": "/api", - "schemes": [ - "http" - ], - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "paths": { - "/pets": { - "get": { - "description": "Returns all pets from the system that the user has access to", - "operationId": "findPets", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "tags", - "in": "query", - "description": "tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "csv" - }, - { - "name": "limit", - "in": "query", - "description": "maximum number of results to return", - "required": false, - "type": "integer", - "format": "int32" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - }, - "post": { - "description": "Creates a new pet in the store. Duplicates are allowed", - "operationId": "addPet", - "produces": [ - "application/json" - ], - "parameters": [ - { - "name": "pet", - "in": "body", - "description": "Pet to add to the store", - "required": true, - "schema": { - "$ref": "#/definitions/NewPet" - } - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - } - }, - "/pets/{id}": { - "get": { - "description": "Returns a user based on a single ID, if the user does not have access to the pet", - "operationId": "findPetById", - "produces": [ - "application/json", - "application/xml", - "text/xml", - "text/html" - ], - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to fetch", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "200": { - "description": "pet response", - "schema": { - "$ref": "#/definitions/Pet" - } - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - }, - "delete": { - "description": "deletes a single pet based on the ID supplied", - "operationId": "deletePet", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "ID of pet to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "204": { - "description": "pet deleted" - }, - "default": { - "description": "unexpected error", - "schema": { - "$ref": "#/definitions/ErrorModel" - } - } - }, - "x-amazon-apigateway-integration": { - "responses": { - "default": { - "statusCode": "200" - } - }, - "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:Calc/invocations", - "passthroughBehavior": "when_no_match", - "httpMethod": "POST", - "type": "aws_proxy" - } - } - } - }, - "definitions": { - "Pet": { - "type": "object", - "allOf": [ - { - "$ref": "#/definitions/NewPet" - }, - { - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - } - } - } - ] - }, - "NewPet": { - "type": "object", - "required": [ - "name" - ], - "properties": { - "name": { - "type": "string" - }, - "tag": { - "type": "string" - } - } - }, - "ErrorModel": { - "type": "object", - "required": [ - "code", - "message" - ], - "properties": { - "code": { - "type": "integer", - "format": "int32" - }, - "message": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/test/templates/open-api/simple-yaml.yaml b/test/templates/open-api/simple-yaml.yaml deleted file mode 100644 index b8f4eabaf5..0000000000 --- a/test/templates/open-api/simple-yaml.yaml +++ /dev/null @@ -1,14 +0,0 @@ ---- -swagger: 2.0 - -info: - title: example - version: 0.1.0 - -paths: - /: - post: - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations diff --git a/test/templates/output_section.yaml b/test/templates/output_section.yaml deleted file mode 100644 index 91cb5cf105..0000000000 --- a/test/templates/output_section.yaml +++ /dev/null @@ -1,14 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Simple CRUD webservice. State is stored in a SimpleTable (DynamoDB) resource. -Resources: - MyApi: - Type: AWS::Serverless::Api - Properties: - DefinitionUri: s3://bucket/key - StageName: prod - -Outputs: - ApiUrl: - Description: URL of API endpoint - Value: !Join ['', ['https://', !Ref "MyApi", '.execute-api.', !Ref 'AWS::Region', '.amazonaws.com/Prod']] \ No newline at end of file diff --git a/test/templates/sam-official-samples/alexa_skill/index.js b/test/templates/sam-official-samples/alexa_skill/index.js deleted file mode 100644 index 2b0de8b136..0000000000 --- a/test/templates/sam-official-samples/alexa_skill/index.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; -console.log('Loading hello world function'); - -exports.handler = function(event, context) { - var name = "World"; - var responseCode = 200; - console.log("request: " + JSON.stringify(event)); - if (event.queryStringParameters !== null && event.queryStringParameters !== undefined) { - if (event.queryStringParameters.name !== undefined && event.queryStringParameters.name !== null && event.queryStringParameters.name !== "") { - console.log("Received name: " + event.queryStringParameters.name); - name = event.queryStringParameters.name; - } - - if (event.queryStringParameters.httpStatus !== undefined && event.queryStringParameters.httpStatus !== null && event.queryStringParameters.httpStatus !== "") { - console.log("Received http status: " + event.queryStringParameters.httpStatus); - responseCode = event.queryStringParameters.httpStatus; - } - } - - var responseBody = { - message: "Hello " + name + "!", - input: event - }; - var response = { - statusCode: responseCode, - headers: { - "x-custom-header" : "my custom header value" - }, - body: JSON.stringify(responseBody) - }; - console.log("response: " + JSON.stringify(response)) - context.succeed(response); -}; diff --git a/test/templates/sam-official-samples/alexa_skill/template.yaml b/test/templates/sam-official-samples/alexa_skill/template.yaml deleted file mode 100644 index 80ad8c0a11..0000000000 --- a/test/templates/sam-official-samples/alexa_skill/template.yaml +++ /dev/null @@ -1,15 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Alexa Skill https://developer.amazon.com/alexa-skills-kit -Resources: - AlexaSkillFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: s3:///alexa_skill.zip - Handler: index.handler - Runtime: nodejs4.3 - Events: - AlexaSkillEvent: - Type: AlexaSkill - Properties: - Whatever: whatever diff --git a/test/templates/sam-official-samples/api-swagger-intrinsic.yaml b/test/templates/sam-official-samples/api-swagger-intrinsic.yaml deleted file mode 100644 index 429cb977e8..0000000000 --- a/test/templates/sam-official-samples/api-swagger-intrinsic.yaml +++ /dev/null @@ -1,1038 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Swagger demo for Integration Requests - -Parameters: - - NotificationEmail: - Type: String - Description: Email address to subscribe to SNS topic and receive notifications from Notifier Workflow - - SlackToken: - Type: String - Description: Legacy Slack Token (xoxp-ywz) to send messages on channel - Default: None - -Resources: - - - SnsNotifierServiceRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowLambdaServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - "lambda.amazonaws.com" - Policies: - - - PolicyName: "PublishSnsTopic" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "sns:Publish" - Resource: - - !Ref NotifierSNSTopic - - "*" # can't restrict on SMS number yet, so * - - - EmailNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: email_sns.lambda_handler - Runtime: python2.7 - CodeUri: ../code/email/ - Role: !GetAtt SnsNotifierServiceRole.Arn - Environment: - Variables: - NOTIFIER_TOPIC: !Ref NotifierSNSTopic - - - SmsNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: sms_sns.lambda_handler - Runtime: python2.7 - CodeUri: ../code/sms/ - Role: !GetAtt SnsNotifierServiceRole.Arn - Environment: - Variables: - NOTIFIER_TOPIC: !Ref NotifierSNSTopic - - # No need for extra permissions other than Basic Execution - # SAM takes care of creating basic IAM Role if none is provided - SlackNotifierServiceFunction: - Type: 'AWS::Serverless::Function' - Properties: - Handler: slack.lambda_handler - Runtime: python2.7 - CodeUri: ../code/slack.zip # Slack contains 3rd party libraries - Environment: - Variables: - SLACK_TOKEN: !Ref SlackToken - # IAM Role API Gateway will assume in order to call StepFunctions StartExecution API - ApiGatewayStepFunctionsRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowApiGatewayServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - "apigateway.amazonaws.com" - Policies: - - - PolicyName: "CallStepFunctions" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "states:StartExecution" - Resource: - - !Ref StepFunctionStateMachine - - AnotherRandomAPI: - Type: AWS::Serverless::Api - Properties: - StageName: prod - DefinitionBody: - swagger: "2.0" - info: - description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" - version: 1.0.0 - title: Swagger Petstore YAML - termsOfService: "http://swagger.io/terms/" - contact: - email: "apiteam@swagger.io" - license: - name: Apache 2.0 - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - basePath: /v2 - tags: - - name: pet - description: Everything about your Pets - externalDocs: - description: Find out more - url: "http://swagger.io" - - name: store - description: Operations about user - - name: user - description: Access to Petstore orders - externalDocs: - description: Find out more about our store - url: "http://swagger.io" - schemes: - - http - paths: - /pet: - post: - tags: - - pet - summary: Add a new pet to the store - x-swagger-router-controller: SampleController - description: "" - operationId: addPet - consumes: - - application/json - - application/xml - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Pet object that needs to be added to the store - required: false - schema: - $ref: "#/definitions/Pet" - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - "write:pets" - - "read:pets" - put: - tags: - - pet - summary: Update an existing pet - description: "" - operationId: updatePet - consumes: - - application/json - - application/xml - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Pet object that needs to be added to the store - required: false - schema: - $ref: "#/definitions/Pet" - responses: - "400": - description: Invalid ID supplied - "404": - description: Pet not found - "405": - description: Validation exception - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByStatus: - get: - tags: - - pet - summary: Finds Pets by status - description: Multiple status values can be provided with comma seperated strings - operationId: findPetsByStatus - consumes: - - application/xml - - application/json - - multipart/form-data - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: status - in: query - description: Status values that need to be considered for filter - required: false - type: array - items: - type: string - collectionFormat: multi - default: available - enum: - - available - - pending - - sold - - name: testlong - in: query - description: Status values that need to be considered for filter - required: false - type: array - items: - type: long - collectionFormat: multi - default: available - enum: - - 1234567890123456 - - 345 - - 678 - responses: - "200": - description: successful operation - schema: - type: array - items: - $ref: "#/definitions/Pet" - "400": - description: Invalid status value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /pet/findByTags: - get: - tags: - - pet - summary: Finds Pets by tags - description: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." - operationId: findPetsByTags - produces: - - application/xml - - application/json - parameters: - - name: tags - in: query - description: Tags to filter by - required: false - type: array - items: - type: string - collectionFormat: multi - responses: - "200": - description: successful operation - schema: - type: array - items: - $ref: "#/definitions/Pet" - "400": - description: Invalid tag value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - "/pet/{petId}": - get: - tags: - - pet - summary: Find pet by ID - description: Returns a single pet - operationId: getPetById - consumes: - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: petId - in: path - description: ID of pet to return - required: true - type: integer - format: int64 - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Pet" - "400": - description: Invalid ID supplied - "404": - description: Pet not found - security: - - api_key: [] - - petstore_auth: - - "write:pets" - - "read:pets" - post: - tags: - - pet - summary: Updates a pet in the store with form data - description: "" - operationId: updatePetWithForm - consumes: - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: petId - in: path - description: ID of pet that needs to be updated - required: true - type: string - - name: name - in: formData - description: Updated name of the pet - required: false - type: string - - name: status - in: formData - description: Updated status of the pet - required: false - type: string - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - "write:pets" - - "read:pets" - delete: - tags: - - pet - summary: Deletes a pet - description: "" - operationId: deletePet - consumes: - - multipart/form-data - - application/x-www-form-urlencoded - produces: - - application/xml - - application/json - parameters: - - name: api_key - in: header - description: "" - required: false - type: string - - name: petId - in: path - description: Pet id to delete - required: true - type: integer - format: int64 - responses: - "400": - description: Invalid pet value - security: - - petstore_auth: - - "write:pets" - - "read:pets" - "/pet/{petId}/uploadImage": - post: - tags: - - pet - summary: uploads an image - x-swagger-router-controller: SampleController - description: "" - operationId: uploadFile - consumes: - - multipart/form-data - produces: - - application/json - parameters: - - name: petId - in: path - description: ID of pet to update - required: true - type: integer - format: int64 - - name: additionalMetadata - in: formData - description: Additional data to pass to server - required: false - type: string - - name: file - in: formData - description: file to upload - required: false - type: file - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/ApiResponse" - security: - - petstore_auth: - - "write:pets" - - "read:pets" - /store/inventory: - get: - tags: - - store - summary: Returns pet inventories by status - description: Returns a map of status codes to quantities - operationId: getInventory - produces: - - application/json - parameters: [] - responses: - "200": - description: successful operation - schema: - type: object - additionalProperties: - type: integer - format: int32 - security: - - api_key: [] - /store/order: - post: - tags: - - store - summary: Place an order for a pet - description: "" - operationId: placeOrder - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: order placed for purchasing the pet - required: false - schema: - $ref: "#/definitions/Order" - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Order" - "400": - description: Invalid Order - "/store/order/{orderId}": - get: - tags: - - store - summary: Find purchase order by ID - description: "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - operationId: getOrderById - produces: - - application/xml - - application/json - parameters: - - name: orderId - in: path - description: ID of pet that needs to be fetched - required: true - type: string - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/Order" - "400": - description: Invalid ID supplied - "404": - description: Order not found - delete: - tags: - - store - summary: Delete purchase order by ID - description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - operationId: deleteOrder - produces: - - application/xml - - application/json - parameters: - - name: orderId - in: path - description: ID of the order that needs to be deleted - required: true - type: string - responses: - "400": - description: Invalid ID supplied - "404": - description: Order not found - /user: - post: - tags: - - user - summary: Create user - description: This can only be done by the logged in user. - operationId: createUser - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: Created user object - required: false - schema: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/createWithArray: - post: - tags: - - user - summary: Creates list of users with given input array - description: "" - operationId: createUsersWithArrayInput - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: List of user object - required: false - schema: - type: array - items: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/createWithList: - post: - tags: - - user - summary: Creates list of users with given input array - description: "" - operationId: createUsersWithListInput - produces: - - application/xml - - application/json - parameters: - - in: body - name: body - description: List of user object - required: false - schema: - type: array - items: - $ref: "#/definitions/User" - responses: - default: - description: successful operation - /user/login: - get: - tags: - - user - summary: Logs user into the system - description: "" - operationId: loginUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: query - description: The user name for login - required: false - type: string - - name: password - in: query - description: The password for login in clear text - required: false - type: string - responses: - "200": - description: successful operation - schema: - type: string - headers: - X-Rate-Limit: - type: integer - format: int32 - description: calls per hour allowed by the user - X-Expires-After: - type: string - format: date-time - description: date in UTC when toekn expires - "400": - description: Invalid username/password supplied - x-amazon-apigateway-integration: - uri: - Fn::GetAtt: [ "SmsNotifierServiceFunction", "Arn" ] - httpMethod: POST - /user/logout: - get: - tags: - - user - summary: Logs out current logged in user session - description: "" - operationId: logoutUser - produces: - - application/xml - - application/json - parameters: [] - responses: - default: - description: successful operation - x-amazon-apigateway-integration: - uri: - Fn::Sub: - - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${FunctionName}/invocations" - - {"FunctionName": !Ref EmailNotifierServiceFunction } - httpMethod: POST - "/user/{username}": - get: - tags: - - user - summary: Get user by user name - description: "" - operationId: getUserByName - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: "The name that needs to be fetched. Use user1 for testing. " - required: true - type: string - responses: - "200": - description: successful operation - schema: - $ref: "#/definitions/User" - "400": - description: Invalid username supplied - "404": - description: User not found - put: - tags: - - user - summary: Updated user - description: This can only be done by the logged in user. - operationId: updateUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: name that need to be deleted - required: true - type: string - - in: body - name: body - description: Updated user object - required: false - schema: - $ref: "#/definitions/User" - responses: - "400": - description: Invalid user supplied - "404": - description: User not found - delete: - tags: - - user - summary: Delete user - description: This can only be done by the logged in user. - operationId: deleteUser - produces: - - application/xml - - application/json - parameters: - - name: username - in: path - description: The name that needs to be deleted - required: true - type: string - responses: - "400": - description: Invalid username supplied - "404": - description: User not found - securityDefinitions: - petstore_auth: - type: oauth2 - authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" - flow: implicit - scopes: - "write:pets": modify pets in your account - "read:pets": read your pets - api_key: - type: apiKey - name: api_key - in: header - definitions: - Order: - properties: - id: - type: integer - format: int64 - petId: - type: integer - format: int64 - quantity: - type: integer - format: int32 - shipDate: - type: string - format: date-time - status: - type: string - description: Order Status - enum: - - placed - - approved - - delivered - complete: - type: boolean - xml: - name: Order - Category: - properties: - id: - type: integer - format: int64 - name: - type: string - xml: - name: Category - User: - properties: - id: - type: integer - format: int64 - username: - type: string - firstName: - type: string - lastName: - type: string - email: - type: string - password: - type: string - phone: - type: string - userStatus: - type: integer - format: int32 - description: User Status - xml: - name: User - Tag: - properties: - id: - type: integer - format: int64 - name: - type: string - xml: - name: Tag - Pet: - required: - - name - - photoUrls - properties: - id: - type: integer - format: int64 - category: - $ref: "#/definitions/Category" - name: - type: string - example: doggie - photoUrls: - type: array - xml: - name: photoUrl - wrapped: true - items: - type: string - tags: - type: array - xml: - name: tag - wrapped: true - items: - $ref: "#/definitions/Tag" - status: - type: string - description: pet status in the store - enum: - - available - - pending - - sold - xml: - name: Pet - ApiResponse: - properties: - code: - type: integer - format: int32 - type: - type: string - message: - type: string - xml: - name: "##default" - externalDocs: - description: Find out more about Swagger - url: "http://swagger.io" - StepFunctionsAPI: - Type: AWS::Serverless::Api - Properties: - StageName: dev - DefinitionBody: - swagger: "2.0" - basePath: /prod - info: - title: AwsSamExample - schemes: - - https - paths: - /: - x-amazon-apigateway-any-method: - security: - - test-authorizer: [] - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - responses: - default: - statusCode: 200 - # NOTE: Replace <> and <> fields - uri: arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations - - passthroughBehavior: when_no_match - httpMethod: POST - type: aws_proxy - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - headers: - Access-Control-Allow-Origin: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Headers: - type: string - x-amazon-apigateway-integration: - type: aws - uri: arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:012345678901:function:HelloWorld/invocations - httpMethod: POST - credentials: arn:aws:iam::012345678901:role/apigateway-invoke-lambda-exec-role - requestTemplates: - application/json: '#set ($root=$input.path(''$'')) { "stage": "$root.name", "user-id": - "$root.key" }' - application/xml: "#set ($root=$input.path('$')) $root.name " - requestParameters: - integration.request.path.stage: method.request.querystring.version - integration.request.querystring.provider: method.request.querystring.vendor - cacheNamespace: cache namespace - cacheKeyParameters: [] - responses: - '302': - statusCode: '302' - responseParameters: - method.response.header.Location: integration.response.body.redirect.url - 2\d{2}: - statusCode: '200' - responseParameters: - method.response.header.requestId: integration.response.header.cid - responseTemplates: - application/json: '#set ($root=$input.path(''$'')) { "stage": "$root.name", - "user-id": "$root.key" }' - application/xml: "#set ($root=$input.path('$')) $root.name " - default: - statusCode: '400' - responseParameters: - method.response.header.test-method-response-header: "'static value'" - x-amazon-apigateway-integration: - uri: !Sub - - "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${EmailNotifierServiceFunction}${Test}/invocations" - - { "Test": "ABCD", "OtherTest": !Ref something } - httpMethod: POST - StepFunctionsServiceRole: - Type: "AWS::IAM::Role" - Properties: - Path: "/" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess" - AssumeRolePolicyDocument: - Version: "2012-10-17" - Statement: - - - Sid: "AllowStepFunctionsServiceToAssumeRole" - Effect: "Allow" - Action: - - "sts:AssumeRole" - Principal: - Service: - - !Sub "states.${AWS::Region}.amazonaws.com" - Policies: - - - PolicyName: "CallLambdaFunctions" - PolicyDocument: - Version: '2012-10-17' - Statement: - - - Effect: "Allow" - Action: - - "lambda:InvokeFunction" - Resource: - - !Sub "${SlackNotifierServiceFunction.Arn}" - - !Sub "${EmailNotifierServiceFunction.Arn}" - - !Sub "${SmsNotifierServiceFunction.Arn}" - - StepFunctionStateMachine: - Type: "AWS::StepFunctions::StateMachine" - Properties: - DefinitionString: !Sub | - { - "Comment": "Demo for API GW->SFN", - "StartAt": "NotifierState", - "States": { - "NotifierState": { - "Type" : "Choice", - "Choices": [ - { - "Variable": "$.notifier", - "StringEquals": "Email", - "Next": "EmailNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Sms", - "Next": "SmsNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Slack", - "Next": "SlackNotifier" - }, - { - "Variable": "$.notify", - "StringEquals": "Twilio", - "Next": "NotImplementedYet" - } - ], - "Default": "IgnoreNotification" - }, - "IgnoreNotification": { - "Type": "Pass", - "Next": "SayHi" - }, - "NotImplementedYet": { - "Type": "Fail", - "Cause": "Feature not implemented yet!" - }, - "EmailNotifier": { - "Type": "Task", - "Resource": "${EmailNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SlackNotifier": { - "Type": "Task", - "Resource": "${SlackNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SmsNotifier": { - "Type": "Task", - "Resource": "${SmsNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SayHi": { - "Type": "Pass", - "Result": "Hi!", - "End": true - } - } - } - RoleArn: !GetAtt StepFunctionsServiceRole.Arn - NotifierSNSTopic: - Type: AWS::SNS::Topic - Properties: - Subscription: - - Endpoint: !Ref NotificationEmail - Protocol: email -Outputs: - NotifyUrl: - Description: Notify Workflow URL - Value: !Sub "https://${StepFunctionsAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/notify" - - StepFunctionsStateMachine: - Description: Step Functions State Machine ARN - Value: !Ref StepFunctionStateMachine \ No newline at end of file diff --git a/test/templates/sam-official-samples/api-swagger-plain.yaml b/test/templates/sam-official-samples/api-swagger-plain.yaml deleted file mode 100644 index cc7f499ce4..0000000000 --- a/test/templates/sam-official-samples/api-swagger-plain.yaml +++ /dev/null @@ -1,1111 +0,0 @@ -AWSTemplateFormatVersion: "2010-09-09" -Description: "Swagger demo for Integration Requests" -Outputs: - NotifyUrl: - Description: "Notify Workflow URL" - Value: "https://${StepFunctionsAPI}.execute-api.${AWS::Region}.amazonaws.com/dev/notify" - StepFunctionsStateMachine: - Description: "Step Functions State Machine ARN" - Value: StepFunctionStateMachine -Parameters: - NotificationEmail: - Description: "Email address to subscribe to SNS topic and receive notifications from Notifier Workflow" - Type: String - SlackToken: - Default: None - Description: "Legacy Slack Token (xoxp-ywz) to send messages on channel" - Type: String -Resources: - AnotherRandomAPI: - Properties: - DefinitionBody: - basePath: /v2 - definitions: - ApiResponse: - properties: - code: - format: int32 - type: integer - message: - type: string - type: - type: string - xml: - name: "##default" - Category: - properties: - id: - format: int64 - type: integer - name: - type: string - xml: - name: Category - Order: - properties: - complete: - type: boolean - id: - format: int64 - type: integer - petId: - format: int64 - type: integer - quantity: - format: int32 - type: integer - shipDate: - format: date-time - type: string - status: - description: "Order Status" - enum: - - placed - - approved - - delivered - type: string - xml: - name: Order - Pet: - properties: - category: - $ref: "#/definitions/Category" - id: - format: int64 - type: integer - name: - example: doggie - type: string - photoUrls: - items: - type: string - type: array - xml: - name: photoUrl - wrapped: true - status: - description: "pet status in the store" - enum: - - available - - pending - - sold - type: string - tags: - items: - $ref: "#/definitions/Tag" - type: array - xml: - name: tag - wrapped: true - required: - - name - - photoUrls - xml: - name: Pet - Tag: - properties: - id: - format: int64 - type: integer - name: - type: string - xml: - name: Tag - User: - properties: - email: - type: string - firstName: - type: string - id: - format: int64 - type: integer - lastName: - type: string - password: - type: string - phone: - type: string - userStatus: - description: "User Status" - format: int32 - type: integer - username: - type: string - xml: - name: User - externalDocs: - description: "Find out more about Swagger" - url: "http://swagger.io" - info: - contact: - email: apiteam@swagger.io - description: "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters" - license: - name: "Apache 2.0" - url: "http://www.apache.org/licenses/LICENSE-2.0.html" - termsOfService: "http://swagger.io/terms/" - title: "Swagger Petstore YAML" - version: "1.0.0" - paths: - /pet: - post: - consumes: - - application/json - - application/xml - description: "" - operationId: addPet - parameters: - - - description: "Pet object that needs to be added to the store" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Pet" - produces: - - application/xml - - application/json - responses: - "405": - description: "Invalid input" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Add a new pet to the store" - tags: - - pet - x-swagger-router-controller: SampleController - put: - consumes: - - application/json - - application/xml - description: "" - operationId: updatePet - parameters: - - - description: "Pet object that needs to be added to the store" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Pet" - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid ID supplied" - "404": - description: "Pet not found" - "405": - description: "Validation exception" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Update an existing pet" - tags: - - pet - /pet/findByStatus: - get: - consumes: - - application/xml - - application/json - - multipart/form-data - - application/x-www-form-urlencoded - description: "Multiple status values can be provided with comma seperated strings" - operationId: findPetsByStatus - parameters: - - - collectionFormat: multi - default: available - description: "Status values that need to be considered for filter" - enum: - - available - - pending - - sold - in: query - items: - type: string - name: status - required: false - type: array - - - collectionFormat: multi - default: available - description: "Status values that need to be considered for filter" - enum: - - 1234567890123456 - - 345 - - 678 - in: query - items: - type: long - name: testlong - required: false - type: array - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - items: - $ref: "#/definitions/Pet" - type: array - "400": - description: "Invalid status value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Finds Pets by status" - tags: - - pet - /pet/findByTags: - get: - description: "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing." - operationId: findPetsByTags - parameters: - - - collectionFormat: multi - description: "Tags to filter by" - in: query - items: - type: string - name: tags - required: false - type: array - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - items: - $ref: "#/definitions/Pet" - type: array - "400": - description: "Invalid tag value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Finds Pets by tags" - tags: - - pet - ? "/pet/{petId}" - : - delete: - consumes: - - multipart/form-data - - application/x-www-form-urlencoded - description: "" - operationId: deletePet - parameters: - - - description: "" - in: header - name: api_key - required: false - type: string - - - description: "Pet id to delete" - format: int64 - in: path - name: petId - required: true - type: integer - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid pet value" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Deletes a pet" - tags: - - pet - get: - consumes: - - application/x-www-form-urlencoded - description: "Returns a single pet" - operationId: getPetById - parameters: - - - description: "ID of pet to return" - format: int64 - in: path - name: petId - required: true - type: integer - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Pet" - "400": - description: "Invalid ID supplied" - "404": - description: "Pet not found" - security: - - - api_key: [] - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Find pet by ID" - tags: - - pet - post: - consumes: - - application/x-www-form-urlencoded - description: "" - operationId: updatePetWithForm - parameters: - - - description: "ID of pet that needs to be updated" - in: path - name: petId - required: true - type: string - - - description: "Updated name of the pet" - in: formData - name: name - required: false - type: string - - - description: "Updated status of the pet" - in: formData - name: status - required: false - type: string - produces: - - application/xml - - application/json - responses: - "405": - description: "Invalid input" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "Updates a pet in the store with form data" - tags: - - pet - ? "/pet/{petId}/uploadImage" - : - post: - consumes: - - multipart/form-data - description: "" - operationId: uploadFile - parameters: - - - description: "ID of pet to update" - format: int64 - in: path - name: petId - required: true - type: integer - - - description: "Additional data to pass to server" - in: formData - name: additionalMetadata - required: false - type: string - - - description: "file to upload" - in: formData - name: file - required: false - type: file - produces: - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/ApiResponse" - security: - - - petstore_auth: - - "write:pets" - - "read:pets" - summary: "uploads an image" - tags: - - pet - x-swagger-router-controller: SampleController - /store/inventory: - get: - description: "Returns a map of status codes to quantities" - operationId: getInventory - parameters: [] - produces: - - application/json - responses: - "200": - description: "successful operation" - schema: - additionalProperties: - format: int32 - type: integer - type: object - security: - - - api_key: [] - summary: "Returns pet inventories by status" - tags: - - store - /store/order: - post: - description: "" - operationId: placeOrder - parameters: - - - description: "order placed for purchasing the pet" - in: body - name: body - required: false - schema: - $ref: "#/definitions/Order" - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Order" - "400": - description: "Invalid Order" - summary: "Place an order for a pet" - tags: - - store - ? "/store/order/{orderId}" - : - delete: - description: "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors" - operationId: deleteOrder - parameters: - - - description: "ID of the order that needs to be deleted" - in: path - name: orderId - required: true - type: string - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid ID supplied" - "404": - description: "Order not found" - summary: "Delete purchase order by ID" - tags: - - store - get: - description: "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions" - operationId: getOrderById - parameters: - - - description: "ID of pet that needs to be fetched" - in: path - name: orderId - required: true - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/Order" - "400": - description: "Invalid ID supplied" - "404": - description: "Order not found" - summary: "Find purchase order by ID" - tags: - - store - /user: - post: - description: "This can only be done by the logged in user." - operationId: createUser - parameters: - - - description: "Created user object" - in: body - name: body - required: false - schema: - $ref: "#/definitions/User" - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Create user" - tags: - - user - /user/createWithArray: - post: - description: "" - operationId: createUsersWithArrayInput - parameters: - - - description: "List of user object" - in: body - name: body - required: false - schema: - items: - $ref: "#/definitions/User" - type: array - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Creates list of users with given input array" - tags: - - user - /user/createWithList: - post: - description: "" - operationId: createUsersWithListInput - parameters: - - - description: "List of user object" - in: body - name: body - required: false - schema: - items: - $ref: "#/definitions/User" - type: array - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Creates list of users with given input array" - tags: - - user - /user/login: - get: - description: "" - operationId: loginUser - parameters: - - - description: "The user name for login" - in: query - name: username - required: false - type: string - - - description: "The password for login in clear text" - in: query - name: password - required: false - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - headers: - X-Expires-After: - description: "date in UTC when toekn expires" - format: date-time - type: string - X-Rate-Limit: - description: "calls per hour allowed by the user" - format: int32 - type: integer - schema: - type: string - "400": - description: "Invalid username/password supplied" - summary: "Logs user into the system" - tags: - - user - /user/logout: - get: - description: "" - operationId: logoutUser - parameters: [] - produces: - - application/xml - - application/json - responses: - default: - description: "successful operation" - summary: "Logs out current logged in user session" - tags: - - user - ? "/user/{username}" - : - delete: - description: "This can only be done by the logged in user." - operationId: deleteUser - parameters: - - - description: "The name that needs to be deleted" - in: path - name: username - required: true - type: string - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid username supplied" - "404": - description: "User not found" - summary: "Delete user" - tags: - - user - get: - description: "" - operationId: getUserByName - parameters: - - - description: "The name that needs to be fetched. Use user1 for testing. " - in: path - name: username - required: true - type: string - produces: - - application/xml - - application/json - responses: - "200": - description: "successful operation" - schema: - $ref: "#/definitions/User" - "400": - description: "Invalid username supplied" - "404": - description: "User not found" - summary: "Get user by user name" - tags: - - user - put: - description: "This can only be done by the logged in user." - operationId: updateUser - parameters: - - - description: "name that need to be deleted" - in: path - name: username - required: true - type: string - - - description: "Updated user object" - in: body - name: body - required: false - schema: - $ref: "#/definitions/User" - produces: - - application/xml - - application/json - responses: - "400": - description: "Invalid user supplied" - "404": - description: "User not found" - summary: "Updated user" - tags: - - user - schemes: - - http - securityDefinitions: - api_key: - in: header - name: api_key - type: apiKey - petstore_auth: - authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" - flow: implicit - scopes: - ? "read:pets" - : "read your pets" - ? "write:pets" - : "modify pets in your account" - type: oauth2 - swagger: "2.0" - tags: - - - description: "Everything about your Pets" - externalDocs: - description: "Find out more" - url: "http://swagger.io" - name: pet - - - description: "Operations about user" - name: store - - - description: "Access to Petstore orders" - externalDocs: - description: "Find out more about our store" - url: "http://swagger.io" - name: user - StageName: prod - Type: "AWS::Serverless::Api" - ApiGatewayStepFunctionsRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - apigateway.amazonaws.com - Sid: AllowApiGatewayServiceToAssumeRole - Version: "2012-10-17" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "states:StartExecution" - Effect: Allow - Resource: - - StepFunctionStateMachine - Version: "2012-10-17" - PolicyName: CallStepFunctions - Type: "AWS::IAM::Role" - EmailNotifierServiceFunction: - Properties: - CodeUri: ../code/email/ - Environment: - Variables: - NOTIFIER_TOPIC: NotifierSNSTopic - Handler: email_sns.lambda_handler - Role: SnsNotifierServiceRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - NotifierSNSTopic: - Properties: - Subscription: - - - Endpoint: NotificationEmail - Protocol: email - Type: "AWS::SNS::Topic" - SlackNotifierServiceFunction: - Properties: - CodeUri: ../code/slack.zip - Environment: - Variables: - SLACK_TOKEN: SlackToken - Handler: slack.lambda_handler - Runtime: python2.7 - Type: "AWS::Serverless::Function" - SmsNotifierServiceFunction: - Properties: - CodeUri: ../code/sms/ - Environment: - Variables: - NOTIFIER_TOPIC: NotifierSNSTopic - Handler: sms_sns.lambda_handler - Role: SnsNotifierServiceRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - SnsNotifierServiceRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - lambda.amazonaws.com - Sid: AllowLambdaServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "sns:Publish" - Effect: Allow - Resource: - - NotifierSNSTopic - - "*" - Version: "2012-10-17" - PolicyName: PublishSnsTopic - Type: "AWS::IAM::Role" - StepFunctionStateMachine: - Properties: - DefinitionString: | - { - "Comment": "Demo for API GW->SFN", - "StartAt": "NotifierState", - "States": { - "NotifierState": { - "Type" : "Choice", - "Choices": [ - { - "Variable": "$.notifier", - "StringEquals": "Email", - "Next": "EmailNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Sms", - "Next": "SmsNotifier" - }, - { - "Variable": "$.notifier", - "StringEquals": "Slack", - "Next": "SlackNotifier" - }, - { - "Variable": "$.notify", - "StringEquals": "Twilio", - "Next": "NotImplementedYet" - } - ], - "Default": "IgnoreNotification" - }, - "IgnoreNotification": { - "Type": "Pass", - "Next": "SayHi" - }, - "NotImplementedYet": { - "Type": "Fail", - "Cause": "Feature not implemented yet!" - }, - "EmailNotifier": { - "Type": "Task", - "Resource": "${EmailNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SlackNotifier": { - "Type": "Task", - "Resource": "${SlackNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SmsNotifier": { - "Type": "Task", - "Resource": "${SmsNotifierServiceFunction.Arn}", - "Next": "SayHi" - }, - "SayHi": { - "Type": "Pass", - "Result": "Hi!", - "End": true - } - } - } - RoleArn: StepFunctionsServiceRole.Arn - Type: "AWS::StepFunctions::StateMachine" - StepFunctionsAPI: - Properties: - DefinitionBody: - basePath: /prod - definitions: - Empty: - title: "Empty Schema" - type: object - info: - title: AwsSamExample - paths: - /: - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: "200 response" - headers: - Access-Control-Allow-Headers: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Origin: - type: string - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - cacheKeyParameters: [] - cacheNamespace: "cache namespace" - credentials: "arn:aws:iam::012345678901:role/apigateway-invoke-lambda-exec-role" - httpMethod: POST - requestParameters: - integration.request.path.stage: method.request.querystring.version - integration.request.querystring.provider: method.request.querystring.vendor - requestTemplates: - application/json: "#set ($root=$input.path('$')) { \"stage\": \"$root.name\", \"user-id\": \"$root.key\" }" - application/xml: "#set ($root=$input.path('$')) $root.name " - responses: - "2\\d{2}": - responseParameters: - method.response.header.requestId: integration.response.header.cid - responseTemplates: - application/json: "#set ($root=$input.path('$')) { \"stage\": \"$root.name\", \"user-id\": \"$root.key\" }" - application/xml: "#set ($root=$input.path('$')) $root.name " - statusCode: "200" - "302": - responseParameters: - method.response.header.Location: integration.response.body.redirect.url - statusCode: "302" - default: - responseParameters: - method.response.header.test-method-response-header: "'static value'" - statusCode: "400" - type: aws - uri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:012345678901:function:HelloWorld/invocations" - x-amazon-apigateway-any-method: - produces: - - application/json - responses: - 200: - description: "200 response" - schema: - $ref: "#/definitions/Empty" - security: - - - test-authorizer: [] - x-amazon-apigateway-integration: - httpMethod: POST - passthroughBehavior: when_no_match - responses: - default: - statusCode: 200 - type: aws_proxy - uri: EmailNotifierServiceFunction.Arn - "/{proxy+}": - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: "200 response" - headers: - Access-Control-Allow-Headers: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Origin: - type: string - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - passthroughBehavior: when_no_match - requestTemplates: - application/json: "{\"statusCode\": 200}" - responses: - default: - responseParameters: - method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" - method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'" - method.response.header.Access-Control-Allow-Origin: "'*'" - statusCode: 200 - type: mock - x-amazon-apigateway-any-method: - parameters: - - - in: path - name: proxy - required: true - type: string - produces: - - application/json - responses: {} - x-amazon-apigateway-auth: - type: aws_iam - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: "arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations" - schemes: - - https - securityDefinitions: - test-authorizer: - in: header - name: Authorization - type: apiKey - x-amazon-apigateway-authorizer: - authorizerCredentials: "arn:aws:iam::account-id:role" - authorizerResultTtlInSeconds: 60 - authorizerUri: "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:account-id:function:function-name/invocations" - identityValidationExpression: "^x-[a-z]+" - type: token - x-amazon-apigateway-authtype: oauth2 - swagger: "2.0" - StageName: dev - Type: "AWS::Serverless::Api" - StepFunctionsServiceRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - "states.${AWS::Region}.amazonaws.com" - Sid: AllowStepFunctionsServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/AWSStepFunctionsFullAccess" - Path: / - Policies: - - - PolicyDocument: - Statement: - - - Action: - - "lambda:InvokeFunction" - Effect: Allow - Resource: - - "${SlackNotifierServiceFunction.Arn}" - - "${EmailNotifierServiceFunction.Arn}" - - "${SmsNotifierServiceFunction.Arn}" - Version: "2012-10-17" - PolicyName: CallLambdaFunctions - Type: "AWS::IAM::Role" -Transform: "AWS::Serverless-2016-10-31" diff --git a/test/templates/sam-official-samples/api_backend/index.js b/test/templates/sam-official-samples/api_backend/index.js deleted file mode 100644 index 5420b07b56..0000000000 --- a/test/templates/sam-official-samples/api_backend/index.js +++ /dev/null @@ -1,87 +0,0 @@ -'use strict'; - - -const AWS = require('aws-sdk'); -const dynamo = new AWS.DynamoDB.DocumentClient(); - -const tableName = process.env.TABLE_NAME; - -const createResponse = (statusCode, body) => { - - return { - statusCode: statusCode, - body: body - } -}; - -exports.get = (event, context, callback) => { - - let params = { - TableName: tableName, - Key: { - id: event.pathParameters.resourceId - } - }; - - let dbGet = (params) => { return dynamo.get(params).promise() }; - - dbGet(params).then( (data) => { - if (!data.Item) { - callback(null, createResponse(404, "ITEM NOT FOUND")); - return; - } - console.log(`RETRIEVED ITEM SUCCESSFULLY WITH doc = ${data.Item.doc}`); - callback(null, createResponse(200, data.Item.doc)); - }).catch( (err) => { - console.log(`GET ITEM FAILED FOR doc = ${data.Item.doc}, WITH ERROR: ${err}`); - callback(null, createResponse(500, err)); - }); -}; - -exports.put = (event, context, callback) => { - - let item = { - id: event.pathParameters.resourceId, - doc: event.body - }; - - let params = { - TableName: tableName, - Item: item - }; - - let dbPut = (params) => { return dynamo.put(params).promise() }; - - dbPut(params).then( (data) => { - console.log(`PUT ITEM SUCCEEDED WITH doc = ${item.doc}`); - callback(null, createResponse(200, null)); - }).catch( (err) => { - console.log(`PUT ITEM FAILED FOR doc = ${item.doc}, WITH ERROR: ${err}`); - callback(null, createResponse(500, err)); - }); -}; - -exports.delete = (event, context, callback) => { - - let params = { - TableName: tableName, - Key: { - id: event.pathParameters.resourceId - }, - ReturnValues: 'ALL_OLD' - }; - - let dbDelete = (params) => { return dynamo.delete(params).promise() }; - - dbDelete(params).then( (data) => { - if (!data.Attributes) { - callback(null, createResponse(404, "ITEM NOT FOUND FOR DELETION")); - return; - } - console.log(`DELETED ITEM SUCCESSFULLY WITH id = ${event.pathParameters.resourceId}`); - callback(null, createResponse(200, null)); - }).catch( (err) => { - console.log(`DELETE ITEM FAILED FOR id = ${event.pathParameters.resourceId}, WITH ERROR: ${err}`); - callback(null, createResponse(500, err)); - }); -}; diff --git a/test/templates/sam-official-samples/api_backend/template.yaml b/test/templates/sam-official-samples/api_backend/template.yaml deleted file mode 100644 index 5b2710a255..0000000000 --- a/test/templates/sam-official-samples/api_backend/template.yaml +++ /dev/null @@ -1,54 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Simple CRUD webservice. State is stored in a SimpleTable (DynamoDB) resource. -Resources: - GetFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.get - Runtime: nodejs4.3 - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBReadOnlyAccess - Environment: - Variables: - TABLE_NAME: !Ref Table - Events: - GetResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: get - - PutFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.put - Runtime: nodejs4.3 - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBFullAccess - Environment: - Variables: - TABLE_NAME: !Ref Table - Events: - PutResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: put - - DeleteFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.delete - Runtime: nodejs4.3 - CodeUri: s3:///api_backend.zip - Policies: AmazonDynamoDBFullAccess - Environment: - Variables: - TABLE_NAME: !Ref Table - Events: - DeleteResource: - Type: Api - Properties: - Path: /resource/{resourceId} - Method: delete \ No newline at end of file diff --git a/test/templates/sam-official-samples/api_swagger_cors/index.js b/test/templates/sam-official-samples/api_swagger_cors/index.js deleted file mode 100644 index 03d56b3116..0000000000 --- a/test/templates/sam-official-samples/api_swagger_cors/index.js +++ /dev/null @@ -1,8 +0,0 @@ -exports.handler = function(event, context, callback) { - - callback(null, { - statusCode: '200', - body: "Hello world" - }); - -} diff --git a/test/templates/sam-official-samples/api_swagger_cors/swagger.yaml b/test/templates/sam-official-samples/api_swagger_cors/swagger.yaml deleted file mode 100644 index 70546630a9..0000000000 --- a/test/templates/sam-official-samples/api_swagger_cors/swagger.yaml +++ /dev/null @@ -1,105 +0,0 @@ ---- -swagger: 2.0 -basePath: /prod -info: - title: AwsSamExample -schemes: -- https -paths: - /: - x-amazon-apigateway-any-method: - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - x-amazon-apigateway-integration: - responses: - default: - statusCode: 200 - # NOTE: Replace <> and <> fields - uri: arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations - - passthroughBehavior: when_no_match - httpMethod: POST - type: aws_proxy - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - headers: - Access-Control-Allow-Origin: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Headers: - type: string - x-amazon-apigateway-integration: - responses: - default: - statusCode: 200 - responseParameters: - method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'" - method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" - method.response.header.Access-Control-Allow-Origin: "'*'" - passthroughBehavior: when_no_match - requestTemplates: - application/json: "{\"statusCode\": 200}" - type: mock - /{proxy+}: - x-amazon-apigateway-any-method: - x-amazon-apigateway-auth: - type: aws_iam - produces: - - application/json - parameters: - - name: proxy - in: path - required: true - type: string - responses: {} - x-amazon-apigateway-integration: - uri: arn:aws:apigateway:<>:lambda:path/2015-03-31/functions/arn:aws:lambda:<>:<>:function:${stageVariables.LambdaFunctionName}/invocations - httpMethod: POST - type: aws_proxy - options: - consumes: - - application/json - produces: - - application/json - responses: - 200: - description: 200 response - schema: - $ref: "#/definitions/Empty" - headers: - Access-Control-Allow-Origin: - type: string - Access-Control-Allow-Methods: - type: string - Access-Control-Allow-Headers: - type: string - x-amazon-apigateway-integration: - responses: - default: - statusCode: 200 - responseParameters: - method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'" - method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'" - method.response.header.Access-Control-Allow-Origin: "'*'" - passthroughBehavior: when_no_match - requestTemplates: - application/json: "{\"statusCode\": 200}" - type: mock -definitions: - Empty: - type: object - title: Empty Schema diff --git a/test/templates/sam-official-samples/api_swagger_cors/template.yaml b/test/templates/sam-official-samples/api_swagger_cors/template.yaml deleted file mode 100644 index d7e8450561..0000000000 --- a/test/templates/sam-official-samples/api_swagger_cors/template.yaml +++ /dev/null @@ -1,46 +0,0 @@ ---- -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: AWS SAM template with API defined in an external Swagger file along with Lambda integrations and CORS configurations -Resources: - ApiGatewayApi: - Type: AWS::Serverless::Api - Properties: - DefinitionUri: s3:///swagger.yaml - StageName: Prod - Variables: - # NOTE: Before using this template, replace the <> and <> fields - # in Lambda integration URI in the swagger file to region and accountId - # you are deploying to - LambdaFunctionName: !Ref LambdaFunction - - LambdaFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: s3:///api_swagger_cors.zip - Handler: index.handler - Runtime: nodejs4.3 - Events: - ProxyApiRoot: - Type: Api - Properties: - RestApiId: !Ref ApiGatewayApi - Path: / - Method: ANY - ProxyApiGreedy: - Type: Api - Properties: - RestApiId: !Ref ApiGatewayApi - Path: /{proxy+} - Method: ANY - -Outputs: - ApiUrl: - Description: URL of your API endpoint - Value: !Join - - '' - - - https:// - - !Ref ApiGatewayApi - - '.execute-api.' - - !Ref 'AWS::Region' - - '.amazonaws.com/Prod' diff --git a/test/templates/sam-official-samples/codestar-node4.3.yaml b/test/templates/sam-official-samples/codestar-node4.3.yaml deleted file mode 100644 index f28f69f5d6..0000000000 --- a/test/templates/sam-official-samples/codestar-node4.3.yaml +++ /dev/null @@ -1,25 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: -- AWS::Serverless-2016-10-31 -- AWS::CodeStar - -Parameters: - ProjectId: - Type: String - Description: AWS CodeStar projectID used to associate new resources to team members - -Resources: - GetHelloWorld: - Type: AWS::Serverless::Function - Properties: - Handler: index.get - Runtime: nodejs4.3 - Role: - Fn::ImportValue: - !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']] - Events: - GetEvent: - Type: Api - Properties: - Path: / - Method: get \ No newline at end of file diff --git a/test/templates/sam-official-samples/encryption_proxy/README.MD b/test/templates/sam-official-samples/encryption_proxy/README.MD deleted file mode 100644 index f439e69bd6..0000000000 --- a/test/templates/sam-official-samples/encryption_proxy/README.MD +++ /dev/null @@ -1,48 +0,0 @@ -### Encryption/Decryption Proxy - -This template creates the following resources: - -* 2 Lambda functions (Encryption, Decryption) - - SAM takes care of creating 2 stages API Gateway {Stage,Prod} that sits on top -* IAM Role for each function -* KMS Key and KMS Decrypt/Encrypt permissions for each IAM Role separately - - KMS Key ID is then passed to Encryption Lambda via Env vars - - -#### Encrypt Action - -* Consumes up to 4KB of data (string, json blob, etc.) -* Returns encrypted data via JSON blob as follows - -```javascript -{ - "data": "base64_encrypted_blob" -} -``` - -**Encrypting data via cURL** - -```bash -encryptURL=$(aws cloudformation describe-stacks --stack-name encryption-proxy --query 'Stacks[].Outputs[?OutputKey==`EncryptURL`].OutputValue' --output text) - -curl -H 'Content-Type: application/json' -X POST -d 'Here it is my super secret data...' ${encryptURL} -``` - -#### Decrypt Action - -* Consumes JSON blob received out of Encryption Action -* Returns decrypted data via JSON blob as follows - -```javascript -{ - "data": "decrypted_data" -} -``` - -**Decrypting data via cURL** - -```bash -decryptURL=$(aws cloudformation describe-stacks --stack-name encryption-proxy --query 'Stacks[].Outputs[?OutputKey==`DecryptURL`].OutputValue' --output text) - -curl -H 'Content-Type: application/json' -X POST -d '{ "data": "AQECAHjgf/RDFTAO0+ief3VXaJRnnKbyaaEsVhkmYxTcbiNhcgAAAHIwcAYJKoZIhvcNAQcGoGMw\nYQIBADBcBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDBX7iv8CwG1gr2Hc4wIBEIAvS1cXraMW\n3PU96z4AACGj7Wuo007HwWjtK/quSi3FKyYFvkJ10YhDOEvzxOD7Ntw=\n" }' ${decryptURL} -``` diff --git a/test/templates/sam-official-samples/encryption_proxy/decryption.py b/test/templates/sam-official-samples/encryption_proxy/decryption.py deleted file mode 100644 index ac04a86fa5..0000000000 --- a/test/templates/sam-official-samples/encryption_proxy/decryption.py +++ /dev/null @@ -1,49 +0,0 @@ -import boto3 -import json -import base64 - -kms = boto3.client('kms') -bad_request = { - 'statusCode': 400, - 'headers': { - 'Content-Type': 'application/json' - }, - 'body': json.dumps({'error': 'Invalid argument'}) -} - - -def decrypt(message): - '''decrypt leverages KMS decrypt and base64-encode decrypted blob - - More info on KMS decrypt API: - https://docs.aws.amazon.com/kms/latest/APIReference/API_decrypt.html - ''' - try: - ret = kms.decrypt( - CiphertextBlob=base64.decodestring(message)) - decrypted_data = ret.get('Plaintext') - except Exception as e: - # returns http 500 back to user and log error details in Cloudwatch Logs - raise Exception("Unable to decrypt data: ", e) - - return decrypted_data - - -def post(event, context): - - try: - payload = json.loads(event['body']) - message = payload['data'] - except (KeyError, TypeError, ValueError): - return bad_request - - decrypted_message = decrypt(message) - response = {'data': decrypted_message} - - return { - 'statusCode': 200, - 'headers': { - 'Content-Type': 'application/json' - }, - 'body': json.dumps(response) - } diff --git a/test/templates/sam-official-samples/encryption_proxy/encryption.py b/test/templates/sam-official-samples/encryption_proxy/encryption.py deleted file mode 100644 index 72598f3c47..0000000000 --- a/test/templates/sam-official-samples/encryption_proxy/encryption.py +++ /dev/null @@ -1,53 +0,0 @@ -import boto3 -import json -import base64 -import os - -kms = boto3.client('kms') -bad_request = { - 'statusCode': 400, - 'headers': { - 'Content-Type': 'application/json' - }, - 'body': json.dumps({'error': 'Invalid argument'}) -} - - -def encrypt(key, message): - '''encrypt leverages KMS encrypt and base64-encode encrypted blob - - More info on KMS encrypt API: - https://docs.aws.amazon.com/kms/latest/APIReference/API_encrypt.html - ''' - try: - ret = kms.encrypt(KeyId=key, Plaintext=message) - encrypted_data = base64.encodestring(ret.get('CiphertextBlob')) - except Exception as e: - # returns http 500 back to user and log error details in Cloudwatch Logs - raise Exception("Unable to encrypt data: ", e) - - return encrypted_data - - -def post(event, context): - - try: - key_id = os.environ['keyId'] - message = event['body'] - if message is None: - raise ValueError - except KeyError: - raise Exception("KMS Key ID not found.") - except ValueError: - return bad_request - - encrypted_message = encrypt(key_id, message) - response = {'data': encrypted_message} - - return { - 'statusCode': 200, - 'headers': { - 'Content-Type': 'application/json' - }, - 'body': json.dumps(response) - } diff --git a/test/templates/sam-official-samples/encryption_proxy/template.yaml b/test/templates/sam-official-samples/encryption_proxy/template.yaml deleted file mode 100644 index dc7bd9c05c..0000000000 --- a/test/templates/sam-official-samples/encryption_proxy/template.yaml +++ /dev/null @@ -1,129 +0,0 @@ -AWSTemplateFormatVersion: "2010-09-09" -Description: | - This SAM example creates the following resources: - - Encryption Proxy: Comprised of Encryption and Decryption Lambda functions + IAM Roles - KMS Key: KMS Key and encrypt/decrypt permission for each IAM Role separately - - Last Modified: 22nd November 2016 Author: Heitor Lessa -Outputs: - DecryptFunction: - Description: "Decryption Lambda Function ARN" - Value: DecryptionFunction.Arn - DecryptURL: - Description: "Decrypt endpoint URL for Stage environment" - Value: "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Stage/decrypt" - EncryptFunction: - Description: "Encryption Lambda Function ARN" - Value: EncryptionFunction.Arn - EncryptURL: - Description: "Encrypt endpoint URL for Stage environment" - Value: "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Stage/encrypt" -Resources: - EncryptionDecryptionKey: - Properties: - Description: "Encryption and Decryption key for Lambda" - KeyPolicy: - Id: LambdaEncDec - Statement: - - - Action: - - "kms:Create*" - - "kms:Describe*" - - "kms:Enable*" - - "kms:List*" - - "kms:Put*" - - "kms:Update*" - - "kms:Revoke*" - - "kms:Disable*" - - "kms:Get*" - - "kms:Delete*" - - "kms:ScheduleKeyDeletion" - - "kms:CancelKeyDeletion" - Effect: Allow - Principal: - AWS: "AWS::AccountId" - Resource: "*" - Sid: "Allow administration of the key" - - - Action: - - "kms:Encrypt" - Effect: Allow - Principal: - AWS: EncryptionServiceIAMRole.Arn - Resource: "*" - Sid: "Allow Encryption Service to use this key" - - - Action: - - "kms:Decrypt" - Effect: Allow - Principal: - AWS: DecryptionServiceIAMRole.Arn - Resource: "*" - Sid: "Allow Decryption Service to use this key" - Version: "2012-10-17" - Type: "AWS::KMS::Key" - EncryptionServiceIAMRole: - DecryptionFunction: - Properties: - CodeUri: "s3:///encryption_proxy.zip" - Events: - decryptAction: - Properties: - Method: post - Path: /decrypt - Type: Api - Handler: decryption.post - Role: DecryptionServiceIAMRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - DecryptionServiceIAMRole: - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - lambda.amazonaws.com - Sid: AllowLambdaServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - Path: / - Type: "AWS::IAM::Role" - EncryptionFunction: - Properties: - CodeUri: "s3:///encryption_proxy.zip" - Environment: - Variables: - keyId: EncryptionDecryptionKey - Events: - encryptAction: - Properties: - Method: post - Path: /encrypt - Type: Api - Handler: encryption.post - Role: EncryptionServiceIAMRole.Arn - Runtime: python2.7 - Type: "AWS::Serverless::Function" - Properties: - AssumeRolePolicyDocument: - Statement: - - - Action: - - "sts:AssumeRole" - Effect: Allow - Principal: - Service: - - lambda.amazonaws.com - Sid: AllowLambdaServiceToAssumeRole - Version: "2012-10-17" - ManagedPolicyArns: - - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" - Path: / - Type: "AWS::IAM::Role" -Transform: "AWS::Serverless-2016-10-31" diff --git a/test/templates/sam-official-samples/function.yaml b/test/templates/sam-official-samples/function.yaml deleted file mode 100644 index 0b89c7a52e..0000000000 --- a/test/templates/sam-official-samples/function.yaml +++ /dev/null @@ -1,29 +0,0 @@ -Transform: AWS::Serverless-2016-10-31 -Resources: - TestFunction: - Type: AWS::Serverless::Function - Properties: - Handler: file.method - Runtime: nodejs - CodeUri: s3://bucket/path/key - FunctionName: functionname - Description: description - MemorySize: 128 - Timeout: 30 - Role: aws::arn::123456789012::some/role - Policies: - - AmazonDynamoDBFullAccess - Environment: - Variables: - NAME: VALUE - VpcConfig: - SecurityGroupIds: - - String - SubnetIds: - - String - Events: - TestApi: - Type: Api - Properties: - Path: /testing - Method: any \ No newline at end of file diff --git a/test/templates/sam-official-samples/hello_world/index.js b/test/templates/sam-official-samples/hello_world/index.js deleted file mode 100644 index 300dd0e6d0..0000000000 --- a/test/templates/sam-official-samples/hello_world/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; -console.log('Loading function'); - -exports.handler = (event, context, callback) => { - callback(null, 'Hello World!'); -}; \ No newline at end of file diff --git a/test/templates/sam-official-samples/hello_world/template.yaml b/test/templates/sam-official-samples/hello_world/template.yaml deleted file mode 100644 index d0f01b66f5..0000000000 --- a/test/templates/sam-official-samples/hello_world/template.yaml +++ /dev/null @@ -1,17 +0,0 @@ -AWSTemplateFormatVersion : '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A hello world application. -Parameters: - Bucket: - Type: String - CodeZipKey: - Type: String -Resources: - HelloWorldFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: - Bucket: !Bucket - Key: !CodeZipKey diff --git a/test/templates/sam-official-samples/inline_swagger/index.js b/test/templates/sam-official-samples/inline_swagger/index.js deleted file mode 100644 index 7f7a6018dd..0000000000 --- a/test/templates/sam-official-samples/inline_swagger/index.js +++ /dev/null @@ -1,6 +0,0 @@ -exports.handler = function(event, context, callback) { - callback(null, { - "statusCode": 200, - "body": "hello world" - }); -} diff --git a/test/templates/sam-official-samples/inline_swagger/template.yaml b/test/templates/sam-official-samples/inline_swagger/template.yaml deleted file mode 100644 index b9dc3018c4..0000000000 --- a/test/templates/sam-official-samples/inline_swagger/template.yaml +++ /dev/null @@ -1,41 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Simple API Endpoint configured using Swagger specified inline and backed by a Lambda function -Resources: - MyApi: - Type: AWS::Serverless::Api - Properties: - StageName: prod - DefinitionBody: - swagger: 2.0 - info: - title: - Ref: AWS::StackName - paths: - "/get": - get: - x-amazon-apigateway-integration: - httpMethod: POST - type: aws_proxy - uri: - Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations - responses: {} - swagger: '2.0' - - - - MyLambdaFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: s3:///inline_swagger.zip - Events: - GetApi: - Type: Api - Properties: - Path: /get - Method: GET - RestApiId: - Ref: MyApi - diff --git a/test/templates/sam-official-samples/iot_backend/index.js b/test/templates/sam-official-samples/iot_backend/index.js deleted file mode 100644 index b18f84d411..0000000000 --- a/test/templates/sam-official-samples/iot_backend/index.js +++ /dev/null @@ -1,30 +0,0 @@ -console.log('Loading function'); - -var AWS = require('aws-sdk'); -var dynamo = new AWS.DynamoDB.DocumentClient(); -var table = process.env.TABLE_NAME; - -exports.handler = function(event, context, callback) { - //console.log('Received event:', JSON.stringify(event, null, 2)); - - var params = { - TableName:table, - Item:{ - "id": event.id, - "thing": event.thing - } - }; - - console.log("Adding a new IoT device..."); - dynamo.put(params, function(err, data) { - if (err) { - console.error("Unable to add device. Error JSON:", JSON.stringify(err, null, 2)); - callback(err); - } else { - console.log("Added device:", JSON.stringify(data, null, 2)); - callback(null,'DynamoDB updated'); - } - }); - - -} diff --git a/test/templates/sam-official-samples/iot_backend/template.yaml b/test/templates/sam-official-samples/iot_backend/template.yaml deleted file mode 100644 index 8486c72a79..0000000000 --- a/test/templates/sam-official-samples/iot_backend/template.yaml +++ /dev/null @@ -1,29 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: IoT -> Lambda -> DynamoDB -Resources: - IoTFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: s3:///iot_backend.zip - Policies: AmazonDynamoDBFullAccess - Environment: - Variables: - TABLE_NAME: - Ref: Table - Events: - IoT: - Type: IoTRule - Properties: - AwsIotSqlVersion: 2016-03-23 - Sql: "SELECT * FROM 'iot2ddb'" - Table: - Type: AWS::Serverless::SimpleTable - Properties: - PrimaryKey: - Name: id - Type: String - - diff --git a/test/templates/sam-official-samples/s3_processor/index.js b/test/templates/sam-official-samples/s3_processor/index.js deleted file mode 100644 index ad412345b2..0000000000 --- a/test/templates/sam-official-samples/s3_processor/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; -console.log('Loading function'); - -let aws = require('aws-sdk'); -let s3 = new aws.S3({ apiVersion: '2006-03-01' }); - -exports.handler = (event, context, callback) => { - // Get the object from the event and show its content type - const bucket = event.Records[0].s3.bucket.name; - const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); - const params = { - Bucket: bucket, - Key: key - }; - s3.getObject(params, (err, data) => { - if (err) { - console.log(err); - const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; - console.log(message); - callback(message); - } else { - console.log('CONTENT TYPE:', data.ContentType); - callback(null, data.ContentType); - } - }); -}; \ No newline at end of file diff --git a/test/templates/sam-official-samples/s3_processor/template.yaml b/test/templates/sam-official-samples/s3_processor/template.yaml deleted file mode 100644 index 5ff7aa2c29..0000000000 --- a/test/templates/sam-official-samples/s3_processor/template.yaml +++ /dev/null @@ -1,22 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A function is triggered off an upload to a bucket. It logs the content type of the uploaded object. -Resources: - ProcessorFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: s3:///s3_processor.zip - Policies: AmazonS3ReadOnlyAccess - Events: - PhotoUpload: - Type: S3 - Properties: - Bucket: !Ref Bucket - Events: s3:ObjectCreated:* - - Bucket: - Type: AWS::S3::Bucket - Properties: - BucketName: Test \ No newline at end of file diff --git a/test/templates/sam-official-samples/schedule/index.js b/test/templates/sam-official-samples/schedule/index.js deleted file mode 100644 index d77afb94bb..0000000000 --- a/test/templates/sam-official-samples/schedule/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; -console.log('Loading function'); - -exports.handler = (event, context, callback) => { - console.log("Invocation with event =", event); - callback(null, 'Everything is ok!'); -}; \ No newline at end of file diff --git a/test/templates/sam-official-samples/schedule/template.yaml b/test/templates/sam-official-samples/schedule/template.yaml deleted file mode 100644 index 4bd022e8c9..0000000000 --- a/test/templates/sam-official-samples/schedule/template.yaml +++ /dev/null @@ -1,15 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A function triggered on a timer. -Resources: - ScheduledFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: s3:///schedule.zip - Events: - Timer: - Type: Schedule - Properties: - Schedule: rate(5 minutes) \ No newline at end of file diff --git a/test/templates/sam-official-samples/stream_processor/index.js b/test/templates/sam-official-samples/stream_processor/index.js deleted file mode 100644 index ea051babc8..0000000000 --- a/test/templates/sam-official-samples/stream_processor/index.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; -console.log('Loading function'); - -exports.handler = (event, context, callback) => { - event.Records.forEach((record) => { - // Kinesis data is base64 encoded so decode here - const payload = new Buffer(record.kinesis.data, 'base64').toString('ascii'); - console.log('Decoded payload:', payload); - }); - callback(null, `Successfully processed ${event.Records.length} records.`); -}; \ No newline at end of file diff --git a/test/templates/sam-official-samples/stream_processor/template.yaml b/test/templates/sam-official-samples/stream_processor/template.yaml deleted file mode 100644 index 48de30be6b..0000000000 --- a/test/templates/sam-official-samples/stream_processor/template.yaml +++ /dev/null @@ -1,21 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: A function that processes data from a Kinesis stream. -Resources: - StreamProcessor: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - CodeUri: s3:///stream_processor.zip - Events: - Stream: - Type: Kinesis - Properties: - Stream: !GetAtt Stream.Arn - StartingPosition: TRIM_HORIZON - - Stream: - Type: AWS::Kinesis::Stream - Properties: - ShardCount: 1 diff --git a/test/templates/sam-official-samples/templates/basic.yaml b/test/templates/sam-official-samples/templates/basic.yaml deleted file mode 100644 index eb8dc991ab..0000000000 --- a/test/templates/sam-official-samples/templates/basic.yaml +++ /dev/null @@ -1,13 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Alexa Skill https://developer.amazon.com/alexa-skills-kit -Resources: - AlexaSkillFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: s3:///alexa_skill.zip - Handler: index.handler - Runtime: nodejs4.3 - Events: - AlexaSkillEvent: - Type: AlexaSkill \ No newline at end of file diff --git a/test/templates/sam-official-samples/templates/intrinsic.yaml b/test/templates/sam-official-samples/templates/intrinsic.yaml deleted file mode 100644 index caf18af6d6..0000000000 --- a/test/templates/sam-official-samples/templates/intrinsic.yaml +++ /dev/null @@ -1,29 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Alexa Skill https://developer.amazon.com/alexa-skills-kit -Resources: - AlexaSkillFunction: - Type: AWS::Serverless::Function - Properties: - CodeUri: s3:///alexa_skill.zip - Handler: index.handler - Runtime: !Ref InlineParameter - Environment: - Variables: - BASE_64_SIMPLE: !Base64 "123456" - # TODO More Base64 - # TODO Conditionals - # TODO FindInMap - GET_ATT: - "Fn::GetAtt": [ "SomeResource", "AndParameter" ] - # TODO ImportValue - # TODO Join - # TODO Select - # TODO Split - SUB_SIMPLE: !Sub "Building with ${AWS::Region} parameters and ${SomeCustom} ones" - SUB_FULL: - "Fn::Sub": - - "Some full text with ${AWS::Region} parameters and ${CustomParams}" - - { "CustomParams": "${SomeOtherResource}" } - - diff --git a/test/templates/sam-official-samples/templates/wrong.yaml b/test/templates/sam-official-samples/templates/wrong.yaml deleted file mode 100644 index de8ae7dcc5..0000000000 --- a/test/templates/sam-official-samples/templates/wrong.yaml +++ /dev/null @@ -1,12 +0,0 @@ -AWSTemplateFormatVersion: '2010-09-09' -Transform: AWS::Serverless-2016-10-31 -Description: Alexa Skill https://developer.amazon.com/alexa-skills-kit -Resources: - AlexaSkillFunction: - Type: AWS::Serverless::Function - Properties: - Handler: index.handler - Runtime: nodejs4.3 - Events: - AlexaSkillEvent: - Type: AlexaSkill \ No newline at end of file diff --git a/test/templates/validation-errors/no-resources-section.yaml b/test/templates/validation-errors/no-resources-section.yaml deleted file mode 100644 index ee4bec3f97..0000000000 --- a/test/templates/validation-errors/no-resources-section.yaml +++ /dev/null @@ -1,2 +0,0 @@ -AWSTemplateFormatVersion: 2010-09-09 -Transform: AWS::Serverless-2016-10-31 \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/__init__.py b/tests/functional/commands/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/local/__init__.py b/tests/functional/commands/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/local/lib/__init__.py b/tests/functional/commands/local/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/local/lib/test_local_api_service.py b/tests/functional/commands/local/lib/test_local_api_service.py new file mode 100644 index 0000000000..bb1c5c4b9b --- /dev/null +++ b/tests/functional/commands/local/lib/test_local_api_service.py @@ -0,0 +1,128 @@ +""" +Function test for Local API service +""" + +import os +import shutil +import random +import threading +import requests +import time +import logging + +from samcli.commands.local.lib import provider +from samcli.commands.local.lib.local_lambda import LocalLambdaRunner +from samcli.local.lambdafn.runtime import LambdaRuntime +from samcli.local.docker.manager import ContainerManager +from samcli.commands.local.lib.local_api_service import LocalApiService + +from tests.functional.function_code import nodejs_lambda, API_GATEWAY_ECHO_EVENT +from unittest import TestCase +from mock import Mock, patch + +logging.basicConfig(level=logging.INFO) + + +class TestFunctionalLocalLambda(TestCase): + + def setUp(self): + self.host = "0.0.0.0" + self.port = random.randint(30000, 40000) # get a random port + self.url = "http://{}:{}".format(self.host, self.port) + + self.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + self.cwd = os.path.dirname(self.code_abs_path) + self.code_uri = os.path.relpath(self.code_abs_path, self.cwd) # Get relative path with respect to CWD + + # Setup a static file in the directory + self.static_dir = "mystaticdir" + self.static_file_name = "myfile.txt" + self.static_file_content = "This is a static file" + self._setup_static_file(os.path.join(self.cwd, self.static_dir), # Create static directory with in cwd + self.static_file_name, + self.static_file_content) + + # Create one Lambda function + self.function_name = "name" + self.function = provider.Function(name=self.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=self.code_uri, + environment={}, + rolearn=None) + self.mock_function_provider = Mock() + self.mock_function_provider.get.return_value = self.function + + # Setup two APIs pointing to the same function + apis = [ + provider.Api(path="/get", method="GET", function_name=self.function_name, cors="cors"), + provider.Api(path="/post", method="POST", function_name=self.function_name, cors="cors"), + ] + self.api_provider_mock = Mock() + self.api_provider_mock.get_all.return_value = apis + + # Now wire up the Lambda invoker and pass it through the context + self.lambda_invoke_context_mock = Mock() + manager = ContainerManager() + local_runtime = LambdaRuntime(manager) + lambda_runner = LocalLambdaRunner(local_runtime, self.mock_function_provider, self.cwd, env_vars_values=None, + debug_args=None, debug_port=None, aws_profile=None) + self.lambda_invoke_context_mock.local_lambda_runner = lambda_runner + self.lambda_invoke_context_mock.get_cwd.return_value = self.cwd + + def tearDown(self): + shutil.rmtree(self.code_abs_path) + + @patch("samcli.commands.local.lib.local_api_service.SamApiProvider") + def test_must_start_service_and_serve_endpoints(self, SamApiProviderMock): + SamApiProviderMock.return_value = self.api_provider_mock + + local_service = LocalApiService(self.lambda_invoke_context_mock, + self.port, + self.host, + None) # No static directory + + self._start_service_thread(local_service) + + response = requests.get(self.url + '/get') + self.assertEquals(response.status_code, 200) + + response = requests.post(self.url + '/post', {}) + self.assertEquals(response.status_code, 200) + + response = requests.get(self.url + '/post') + self.assertEquals(response.status_code, 403) # "HTTP GET /post" must not exist + + @patch("samcli.commands.local.lib.local_api_service.SamApiProvider") + def test_must_serve_static_files(self, SamApiProviderMock): + SamApiProviderMock.return_value = self.api_provider_mock + + local_service = LocalApiService(self.lambda_invoke_context_mock, + self.port, + self.host, + self.static_dir) # Mount the static directory + + self._start_service_thread(local_service) + + # NOTE: The URL does not contain the static_dir because this directory is mounted directly at / + response = requests.get("{}/{}".format(self.url, self.static_file_name)) + + self.assertEquals(response.status_code, 200) + self.assertEquals(self.static_file_content, response.text) + + @staticmethod + def _start_service_thread(service): + t = threading.Thread(name='thread', target=service.start, args=()) + t.setDaemon(True) + t.start() + time.sleep(1) # Wait for the Web server to spin up + + @staticmethod + def _setup_static_file(directory, filename, contents): + + if not os.path.isdir(directory): + os.mkdir(directory) + + with open(os.path.join(directory, filename), "w") as fp: + fp.write(contents) + diff --git a/tests/functional/commands/local/lib/test_local_lambda.py b/tests/functional/commands/local/lib/test_local_lambda.py new file mode 100644 index 0000000000..10f87a1efc --- /dev/null +++ b/tests/functional/commands/local/lib/test_local_lambda.py @@ -0,0 +1,92 @@ +""" +Function test for Local Lambda runner +""" + +import os +import io +import json +import shutil +import logging + +from samcli.commands.local.lib import provider +from samcli.commands.local.lib.local_lambda import LocalLambdaRunner +from samcli.local.lambdafn.runtime import LambdaRuntime +from samcli.local.docker.manager import ContainerManager + +from tests.functional.function_code import nodejs_lambda, GET_ENV_VAR +from unittest import TestCase +from mock import Mock + +logging.basicConfig(level=logging.INFO) + + +class TestFunctionalLocalLambda(TestCase): + + def setUp(self): + self.code_abs_path = nodejs_lambda(GET_ENV_VAR) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + self.cwd = os.path.dirname(self.code_abs_path) + self.code_uri = os.path.relpath(self.code_abs_path, self.cwd) # Get relative path with respect to CWD + + self.function_name = "name" + self.variables = { + "var1": "defaultvalue1", + "var2": "defaultvalue2" + } + + self.env_var_overrides = { + self.function_name: { + "var1": "override_value1" + } + } + + # Override "var2" through the Shell environment + os.environ["var2"] = "shell_env_value2" + + self.function = provider.Function(name=self.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=self.code_uri, + environment={"Variables": self.variables}, + rolearn=None) + + self.mock_function_provider = Mock() + self.mock_function_provider.get.return_value = self.function + + def tearDown(self): + + del os.environ["var2"] + shutil.rmtree(self.code_abs_path) + + def test_must_invoke(self): + input_event = '"some data"' + expected_env_vars = { + "var1": "override_value1", + "var2": "shell_env_value2" + } + + manager = ContainerManager() + local_runtime = LambdaRuntime(manager) + runner = LocalLambdaRunner(local_runtime, self.mock_function_provider, self.cwd, self.env_var_overrides, + debug_args=None, debug_port=None, aws_profile=None) + + # Append the real AWS credentials to the expected values. + creds = runner.get_aws_creds() + # default value for creds is not configured by the test. But coming from a downstream class + expected_env_vars["AWS_SECRET_ACCESS_KEY"] = creds.get("secret", "defaultsecret") + expected_env_vars["AWS_ACCESS_KEY_ID"] = creds.get("key", "defaultkey") + expected_env_vars["AWS_REGION"] = creds.get("region", "us-east-1") + + stdout_stream = io.BytesIO() + stderr_stream = io.BytesIO() + runner.invoke(self.function_name, input_event, stdout=stdout_stream, stderr=stderr_stream) + + # stderr is where the Lambda container runtime logs are available. It usually contains requestId, start time + # etc. So it is non-zero in size + self.assertGreater(len(stderr_stream.getvalue().strip()), 0, "stderr stream must contain data") + + # This should contain all the environment variables passed to the function + actual_output = json.loads(stdout_stream.getvalue().strip()) + + for key, value in expected_env_vars.items(): + self.assertTrue(key in actual_output, "Key '{}' must be in function output".format(key)) + self.assertEquals(actual_output.get(key), value) diff --git a/tests/functional/commands/validate/__init__.py b/tests/functional/commands/validate/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/validate/lib/__init__.py b/tests/functional/commands/validate/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/commands/validate/lib/test_sam_template_validator.py b/tests/functional/commands/validate/lib/test_sam_template_validator.py new file mode 100644 index 0000000000..64e0505f7f --- /dev/null +++ b/tests/functional/commands/validate/lib/test_sam_template_validator.py @@ -0,0 +1,150 @@ +from unittest import TestCase +from mock import Mock + +from samcli.commands.validate.lib.sam_template_validator import SamTemplateValidator +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + + +class TestValidate(TestCase): + + def test_valid_template(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "CodeUri": "s3://fake-bucket/lambda-code.zip", + "Runtime": "nodejs6.10", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"PolicyName": "FakePolicy"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + # Should not throw an exception + validator.is_valid() + + def test_invalid_template(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "CodeUri": "s3://lambda-code.zip", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"PolicyName": "FakePolicy"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + with self.assertRaises(InvalidSamDocumentException): + validator.is_valid() + + def test_valid_template_with_local_code_for_function(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "CodeUri": "./", + "Runtime": "nodejs6.10", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"PolicyName": "FakePolicy"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + # Should not throw an exception + validator.is_valid() + + def test_valid_template_with_local_code_for_api(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionUri": "./" + } + } + } + } + + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"PolicyName": "FakePolicy"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + # Should not throw an exception + validator.is_valid() + + + def test_valid_template_with_s3_object_passed(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionUri": { + "Bucket": "mybucket-name", + "Key": "swagger", + "Version": 121212 + } + } + }, + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "CodeUri": { + "Bucket": "mybucket-name", + "Key": "code.zip", + "Version": 121212 + }, + "Runtime": "nodejs6.10", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"PolicyName": "FakePolicy"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + # Should not throw an exception + validator.is_valid() + + # validate the CodeUri was not changed + self.assertEquals(validator.sam_template.get("Resources").get("ServerlessApi").get("Properties").get("DefinitionUri"), {"Bucket": "mybucket-name", "Key": "swagger", "Version": 121212}) + self.assertEquals(validator.sam_template.get("Resources").get("ServerlessFunction").get("Properties").get("CodeUri"), {"Bucket": "mybucket-name", "Key": "code.zip", "Version": 121212}) \ No newline at end of file diff --git a/tests/functional/function_code.py b/tests/functional/function_code.py new file mode 100644 index 0000000000..1a88c6b269 --- /dev/null +++ b/tests/functional/function_code.py @@ -0,0 +1,142 @@ +""" +Helper class for tests to generate code folders with different types of Lambda functions +""" + +import tempfile +import os +import shutil + +from contextlib import contextmanager + +# Echoes the input back as result +ECHO_CODE = """ +exports.handler = function(event, context, callback){ + + console.log("Hello World"); + callback(null, event) +} +""" + +# Sleeps for input number of seconds before returning +SLEEP_CODE = """ +exports.handler = function(event, context, callback) { + // Duration for the sleep comes in the event + + duration = event * 1000 // milliseconds + setTimeout(function() { callback(null, event) }, duration) +} +""" + +# Returns all the environment variables as an output +GET_ENV_VAR = """ +exports.handler = function(event, context, callback) { + callback(null, process.env) +} +""" + +CONSOLE_LOG_LAMBDA = """ +exports.handler = function(event, context, callback) { + console.log("Hello World") + callback(null, null) +} +""" + +HELLO_FROM_LAMBDA = """ +exports.handler = function(event, context) { + context.done(null, 'Hello from Lambda'); +}; +""" + +API_GATEWAY_ECHO_EVENT = """ +exports.handler = function(event, context, callback){ + + response = {"statusCode":200,"headers":{},"body":JSON.stringify(event),"isBase64Encoded":false} + context.done(null, response); +} +""" + +API_GATEWAY_BAD_PROXY_RESPONSE = """ +exports.handler = function(event, context, callback){ + + response = "Non Proxy Response" + context.done(null, response); +} +""" + +API_GATEWAY_ECHO_BASE64_EVENT = """ +exports.base54request = function(event, context, callback){ + + response = {"statusCode":200,"headers":{"Content-Type":"image/gif"},"body":event["body"],"isBase64Encoded":event["isBase64Encoded"]} + context.done(null, response); +} + +exports.echoimagehandler = function(event, context, callback) { + + gifImageBase64 = "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==" + + callback(null, { + statusCode: 200, + body: gifImageBase64, + + // API Gateway will automatically convert the base64 encoded response to binary if the Accept header in + // request matches the Content-Type of response. Unfortunately, if you use this in an HTML Image tag + // , then browsers don't send a specific Accept header. Therefore API Gateway + // will return the base64 text response. If serving image in HTML tag is your primary usecase, + // then you can use */* as value for BinaryMediaType which will make API Gateway treat every response + // as binary type, and hence decode base64 always. + isBase64Encoded: true, + headers: { + "Content-Type": "image/gif" + } + }); +} +""" + + +def nodejs_lambda(code): + """ + In a temporary directory, create "index.js" file with the passed in code and return directory path. + This is a contextmanager. So it can be used inside `with` statements to automatically cleanup + temp folder upon exit + + :param string code: Code to be written to the index.js file + :return string: directory path + + """ + directory = tempfile.mkdtemp() + filename = os.path.join(directory, "index.js") + + with open(filename, "w+") as fp: + fp.write(code) + fp.flush() + + # The directory that Python returns might have symlinks. The Docker File sharing settings will not resolve + # symlinks. Hence get the real path before passing to Docker. + return os.path.realpath(directory) + +@contextmanager +def make_zip(directory, extension="zip"): + """ + Zip up the contents of the directory and return path to the zipfile. This method can be used inside a ``with`` + statement so it will cleanup the zipfile after the context exists. + + :param string directory: Path to the directory to zip up + :param string extension: Extension for the file + :return string: Path to the zip file + """ + tmpdir = None + + try: + tmpdir = tempfile.mkdtemp() + path_prefix = os.path.join(tmpdir, "code") + + zipfile_current_path = shutil.make_archive(path_prefix, 'zip', directory) + + # shutil always sets the file with .zip extension. Hence rename/move the file to be with right extension + expected_path = path_prefix + "." + extension + os.rename(zipfile_current_path, expected_path) + + yield expected_path + finally: + if tmpdir: + shutil.rmtree(tmpdir) diff --git a/tests/functional/init/__init__.py b/tests/functional/init/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/init/test_generate_project.py b/tests/functional/init/test_generate_project.py new file mode 100644 index 0000000000..5df2b6ff41 --- /dev/null +++ b/tests/functional/init/test_generate_project.py @@ -0,0 +1,54 @@ +import os +import random +import tempfile +import shutil +from unittest import TestCase + +from samcli.commands.init import do_cli as init_cli + + +class TestCli(TestCase): + + def setUp(self): + self.location = None + self.runtime = "python3.6" + self.output_dir = tempfile.mkdtemp() + self.name = "testing project {}".format(random.randint(1, 10)) + self.no_input = False + self.cookiecutter_dir = tempfile.mkdtemp() + self.project_folder = os.path.abspath( + os.path.join(self.output_dir, self.name)) + self.custom_location_folder = os.path.abspath( + os.path.join(self.output_dir, 'name-of-the-project')) + + def tearDown(self): + leftover_folders = (self.output_dir, self.cookiecutter_dir) + + for folder in leftover_folders: + if os.path.isdir(folder): + shutil.rmtree(folder) + + def test_generate_project(self): + # GIVEN generate_project successfully created a project + # WHEN a project name has been passed + init_cli( + ctx=None, location=self.location, runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=self.no_input) + + # THEN we should see a new project created and a successful return + self.assertTrue(os.path.isdir(self.project_folder)) + + def test_custom_location(self): + # GIVEN generate_project successfuly created a project + # WHEN a custom template has been passed + # and we were asked to accept default values provided by the template + self.location = "https://github.com/aws-samples/cookiecutter-aws-sam-python" + + init_cli( + ctx=None, location=self.location, runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=True) + + # THEN we should see a new project created and a successful return + # and this new folder should be named 'name-of-the-project' + # which is the default value for this custom template + self.assertTrue(os.path.isdir(self.custom_location_folder)) diff --git a/tests/functional/local/__init__.py b/tests/functional/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/local/apigw/__init__.py b/tests/functional/local/apigw/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/local/apigw/test_service.py b/tests/functional/local/apigw/test_service.py new file mode 100644 index 0000000000..ae6348b1f9 --- /dev/null +++ b/tests/functional/local/apigw/test_service.py @@ -0,0 +1,500 @@ +from unittest import TestCase +import threading +import os +import shutil +import json +import time + +import requests +import random +from mock import Mock + +from samcli.local.apigw.service import Route, Service +from tests.functional.function_code import nodejs_lambda, API_GATEWAY_ECHO_EVENT, API_GATEWAY_BAD_PROXY_RESPONSE, API_GATEWAY_ECHO_BASE64_EVENT +from samcli.commands.local.lib import provider +from samcli.local.lambdafn.runtime import LambdaRuntime +from samcli.commands.local.lib.local_lambda import LocalLambdaRunner +from samcli.local.docker.manager import ContainerManager + + +class TestService_InvalidResponses(TestCase): + @classmethod + def setUpClass(cls): + cls.code_abs_path = nodejs_lambda(API_GATEWAY_BAD_PROXY_RESPONSE) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + cls.cwd = os.path.dirname(cls.code_abs_path) + cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD + + cls.function_name = "name" + + cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.mock_function_provider = Mock() + cls.mock_function_provider.get.return_value = cls.function + + list_of_routes = [Route(['POST', 'GET'], cls.function_name, '/something'), + Route(['GET'], cls.function_name, '/'), + Route(['GET', 'PUT'], cls.function_name, '/something/{event}'), + ] + + cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd) + cls.service.create() + t = threading.Thread(name='thread', target=cls.service.run, args=()) + t.setDaemon(True) + t.start() + time.sleep(1) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.code_abs_path) + + def test_non_proxy_response(self): + expected = {"message": "Internal server error"} + + response = requests.get(self.url) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 502) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + +class TestService_EventSerialization(TestCase): + @classmethod + def setUpClass(cls): + cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + cls.cwd = os.path.dirname(cls.code_abs_path) + cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD + + cls.function_name = "name" + + cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.base64_response_function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.mock_function_provider = Mock() + cls.mock_function_provider.get.return_value = cls.function + + list_of_routes = [Route(['POST', 'GET'], cls.function_name, '/something'), + Route(['GET'], cls.function_name, '/'), + Route(['GET', 'PUT'], cls.function_name, '/something/{event}'), + Route(['GET'], cls.function_name, '/proxypath/{proxy+}') + ] + + cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd) + cls.service.create() + t = threading.Thread(name='thread', target=cls.service.run, args=()) + t.setDaemon(True) + t.start() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.code_abs_path) + + def setUp(self): + # Print full diff when comparing large dictionaries + self.maxDiff = None + + def test_calling_service_root(self): + expected = make_service_response(self.port, + scheme=self.scheme, + method="GET", + resourcePath="/", + resolvedResourcePath="/", + pathParameters=None, + body=None, + queryParams=None, + headers=None) + + response = requests.get(self.url) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_service_with_nonexistent_endpoint(self): + expected = {"message": "Missing Authentication Token"} + + response = requests.get(self.url + "/nothere") + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 403) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_service_with_valid_path_invalid_method(self): + expected = {"message": "Missing Authentication Token"} + + response = requests.put(self.url) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 403) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_service_with_data_on_path(self): + path = "/something" + body = {"json": "data"} + expected = make_service_response(self.port, + scheme=self.scheme, + method="POST", + resourcePath=path, + resolvedResourcePath=path, + pathParameters=None, + body=json.dumps(body), + queryParams=None, + headers={"Content-Length": "16", + "Content-Type": "application/json"}) + + response = requests.post(self.url + path, json=body) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_service_with_path_params(self): + path = '/something/event1' + expected = make_service_response(self.port, + scheme=self.scheme, + method="GET", + resourcePath="/something/{event}", + resolvedResourcePath=path, + pathParameters={"event": "event1"}, + body=None, + queryParams=None, + headers=None) + + response = requests.get(self.url + path) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_proxy_path(self): + path = '/proxypath/thisisproxypath/thatshouldbecaught' + expected = make_service_response(self.port, + scheme=self.scheme, + method="GET", + resourcePath="/proxypath/{proxy+}", + resolvedResourcePath=path, + pathParameters={"proxy": "thisisproxypath/thatshouldbecaught"}, + body=None, + queryParams=None, + headers=None) + + response = requests.get(self.url + path) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + def test_calling_service_with_body_and_query_and_headers(self): + path = "/something/event1" + body = {"json": "data"} + headers = {"X-Test": "TestValue"} + + expected = make_service_response(self.port, + scheme=self.scheme, + method="PUT", + resourcePath="/something/{event}", + resolvedResourcePath=path, + pathParameters={"event": "event1"}, + body=json.dumps(body), + queryParams={"key": ["value"]}, + headers={"X-Test": "TestValue", "Content-Length": "16", + "Content-Type": "application/json"}) + + response = requests.put(self.url + path, + json=body, + params={"key": "value"}, + headers=headers) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + +class TestService_ProxyAtBasePath(TestCase): + + @classmethod + def setUpClass(cls): + cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_EVENT) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + cls.cwd = os.path.dirname(cls.code_abs_path) + cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD + + cls.function_name = "name" + + cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.handler", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.mock_function_provider = Mock() + cls.mock_function_provider.get.return_value = cls.function + + list_of_routes = [ + Route(['GET'], cls.function_name, '/{proxy+}') + ] + + cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd) + cls.service.create() + t = threading.Thread(name='thread', target=cls.service.run, args=()) + t.setDaemon(True) + t.start() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.code_abs_path) + + def setUp(self): + # Print full diff when comparing large dictionaries + self.maxDiff = None + + def test_calling_proxy_path(self): + path = '/proxypath/thisisproxypath/thatshouldbecaught' + expected = make_service_response(self.port, + scheme=self.scheme, + method="GET", + resourcePath="/{proxy+}", + resolvedResourcePath=path, + pathParameters={"proxy": "proxypath/thisisproxypath/thatshouldbecaught"}, + body=None, + queryParams=None, + headers=None) + + response = requests.get(self.url + path) + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + +class TestService_Binary(TestCase): + + @classmethod + def setUpClass(cls): + cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_BASE64_EVENT) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + cls.cwd = os.path.dirname(cls.code_abs_path) + cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD + + cls.function_name = "name" + + cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.echoimagehandler", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.mock_function_provider = Mock() + cls.mock_function_provider.get.return_value = cls.function + + list_of_routes = [ + Route(['GET'], cls.function_name, '/getimagegifbinarydata', binary_types=['image/gif']), + Route(['GET'], cls.function_name, '/getanygifbinarydata', binary_types=['*/*']), + Route(['POST'], cls.function_name, '/postbinarygif', binary_types=['image/gif']) + + ] + + cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd) + cls.service.create() + t = threading.Thread(name='thread', target=cls.service.run, args=()) + t.setDaemon(True) + t.start() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.code_abs_path) + + def setUp(self): + # Print full diff when comparing large dictionaries + self.maxDiff = None + + def test_echo_with_defined_binary_types(self): + path = '/getimagegifbinarydata' + + response = requests.get(self.url + path) + + actual = response.content + + self.assertEquals(actual, 'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "image/gif") + + def test_echo_with_any_binary_types(self): + path = '/getanygifbinarydata' + + response = requests.get(self.url + path) + + actual = response.content + + self.assertEquals(actual, 'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "image/gif") + + def test_accept_json_should_return_base64(self): + # This test is asserting the behavior we currently have. I find it strange that we will return a Content-Type + # that does not match the Accept headers + path = '/getimagegifbinarydata' + + response = requests.get(self.url + path, headers={"Accept": "application/json"}) + + actual = response.content + + self.assertEquals(actual, "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==") # NOQA + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "image/gif") + + +class TestService_PostingBinary(TestCase): + + @classmethod + def setUpClass(cls): + cls.code_abs_path = nodejs_lambda(API_GATEWAY_ECHO_BASE64_EVENT) + + # Let's convert this absolute path to relative path. Let the parent be the CWD, and codeuri be the folder + cls.cwd = os.path.dirname(cls.code_abs_path) + cls.code_uri = os.path.relpath(cls.code_abs_path, cls.cwd) # Get relative path with respect to CWD + + cls.function_name = "name" + + cls.function = provider.Function(name=cls.function_name, runtime="nodejs4.3", memory=256, timeout=5, + handler="index.base54request", codeuri=cls.code_uri, environment=None, + rolearn=None) + + cls.mock_function_provider = Mock() + cls.mock_function_provider.get.return_value = cls.function + + list_of_routes = [ + Route(['POST'], cls.function_name, '/postbinarygif', binary_types=['image/gif']), + Route(['POST'], cls.function_name, '/postanybinary', binary_types=['*/*']) + ] + + cls.service, cls.port, cls.url, cls.scheme = make_service(list_of_routes, cls.mock_function_provider, cls.cwd) + cls.service.create() + t = threading.Thread(name='thread', target=cls.service.run, args=()) + t.setDaemon(True) + t.start() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.code_abs_path) + + def setUp(self): + # Print full diff when comparing large dictionaries + self.maxDiff = None + + def test_post_binary_image_gif(self): + path = '/postbinarygif' + + response = requests.post(self.url + path, + headers={"Content-Type": "image/gif"}, + data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + + actual = response.content + + self.assertEquals(actual, 'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "image/gif") + + def test_post_binary_and_accept_any(self): + path = '/postanybinary' + + response = requests.post(self.url + path, + headers={"Content-Type": "image/gif"}, + data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + + actual = response.content + + self.assertEquals(actual, 'GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get('Content-Type'), "image/gif") + + def test_post_binary_with_incorrect_content_type(self): + expected = {"message": "Internal server error"} + + path = '/postbinarygif' + + response = requests.post(self.url + path, + headers={"Content-Type": "application/json"}, + data='GIF89a=\x00D\x00\xf7\xa8\x00\x9a,3\xff\xc0\xc0\xef\xc0\xc0uXg\xfc\xf9\xf7\x993\x00\xff\xec\xec\xff\xa0\xa0\xe5\xcc\xbf\xcf\x9f\x87\x0f\xef\xef\x7f\x7f\x7f\xef\x0f\x0f\xdf\x1f\x1f\xff&&_\x9f\x9f\xffYY\xbf??5\xa5\xc2\xff\xff\xff\xac\x16\x19\xb2&\x00\xf8\x13\x10\xc2& \xdf`PP\x84\x9b\xf8\x03\x00\xb5\x0b\x0c\xdf\x0f\x00>\x9a\xb5\x87BM\x7f`P\xd2\xa5\x8f\xcc\x19\x00\xa5,\x00\xec\xd9\xcf\xe5\x0c\x00\xeb\t\x00\xff\xd9\xd9\xc7\x0c\x0c\x0f\x0f\x0f\xffyy~MZ\xfb\t\x08\xe5M@\xfb__\xff33\xcf\x90x\xf2\xe5\xdf\xc3\x06\x06\xbf\t\x08\xff\xb3\xb3\xd9\xb2\x9f\xff\x06\x06\xac)\x00\xff\xc6\xc6\x0c\t\x08\xf9\xf2\xef\xc9s`\xb8#\x00\x9f/\x00\xff__\xff\x8c\x8c\xc5\x1c\x00\xdf33\xffpp\xcf\x19\x19\xc0\x13\x10\xbf\x90x\xf7YY\xff\xf6\xf6\xe7??\xd7&&\xefLL2& \xdf\xbf\xaf\xbf\xbf\xbf???\xc5M@cn\x81_\x00\x00___\xcb00\xd8\x13\x00YC8\x80\x80\x80\xf3RRsVH\xc490\x10\x10\x10\x917@\xf2\x06\x00\xcf@@\xca\x86pooo\xa3!&\xc1\x1d\x18\xcf//\x1f\x1f\x1f\xdf\x00\x00\xd2\x16\x00\xcb\x90x\xbf\x1f\x00\x19\x13\x10\xf3\xd0\xd0\xe399&\x1d\x18Yy\x8e\x8f\x8f\x8f\xff\xa9\xa9\xcb\x13\x13\xbf00SF@\xb6& >\x1d\x18\xfb\xdd\xdd@@@\x99\x93\x90\xff\xbc\xbc\x7fPP\xaf\xaf\xaf\xc6VHzsp\x93& \xb7pp\xb3\x86ptPP|pp\xafOO\xd0\xd0\xd0\xef\xef\xefL90\xbc\xa9\xa0o0(\xeb\xb0\xb0\xff\xe0\xe0\xff\xd0\xd0\x870(K0(\xc9|h\x9f__lct\xebFF\xcf\xcf\xcf\xe0\xe0\xe0b& \xff },(@0(\xa9\x93\x88\xa6|h\x1f\xdf\xdf\xd5\xac\x97\xe2\xc5\xb7\xc7`POOO\x9cyhppp\xff\x80\x80\xff\x96\x96\xd7``\xcc\x99\x7f,\xb0\xcf\xbf\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00\x00\xffff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\xa8\x00,\x00\x00\x00\x00=\x00D\x00\x00\x08\xff\x00Q\t\x1cH\xb0\xa0\xc1\x83\x08\x13*\\\xc8\xb0\xa1\xc0\x1b\x07\x0c8\x9cHq\xa1\x89\x14\xa72F\xac\xc8\xb1\xa2\t\x1f\x19Cj\x94\xd8\xb1$B\x03\x07D\xaa\x1ci\xb2%*#3V\xcad\xe9\xb2\xa2\x9d 3s\x9e\xdaX\x93!"\x8c:\x83\xf2\xeci\xf0c\xd0\xa3!\x87\x12E\x89\xb4iR\x92.a:\x9d\xfa\xb4\xe5\x0c\x9cT\xb3\xee\x84:\xf1\x06P\xad`\x95*4\n\xb6l\xd5\x84\x06>\x99]\x1b\xb2\xc5\x9c\x83F\xda\xb0\x9d{\xe4\x84\x00\x83W\xe7\xaeM\xe2f\xd4\xa8\xbb\x03\xbd\xea5kE\x88_\xbf\x80\x0fy\x1a\\\xb6\x08\x92\xc3\x87\x01\x070\xe5\x00\x02\xe3\xa9-\x80\xc4\x80\x1cY\xe0dS\x94-_\x0ezd3\xe7\xce\xa8>\x83\x0e=Zf\x92\x13\xa7Gm\x18 \xe1\xaf\xe7\xd5\xb8+\xb7\xceX8\xf6(\xda\xa2D\xd9N\x8d\xbb\xb8n\xc6\x8e}\x8f\xfa\x12<\xf8\xf0\xcf\x11\x1a\x14\x07}|mf\xdf\x00\x9elP\xd1\\\xb8dSaJ\x95\xffz }zu\xadiLs\xa6\xb0&8\x80\x01\xdd\x9f\x9b\x8a ^<\xf9\xe9\xac\xa9:\x82\x1d{\x83\x84\xe6\xef\xc5\xf7\x1d}\xf5\xd9W\x9eq\xa2\x1d\x95\x84a\xb1\xa9\xb0\x01\x00\xdd\x05\xd8\x9c|\x04\x16X\x8a\x02\x0b0\x80\x9f\x0b=\xe8\x94\\l\x1et \n\x00\x10\x02\x08\xdf\x84\x03ZX \x86\x1a\x16W\x03\x87+]\xe7[\x06\x00\x96\xe8\xde\x89\xce\xa5\xa8\xe2\x8a\x19N\xf7b\x87\x19\xa5\x17\x1b\x05\xa3P\x10\xa1\x8d#\xe2X\x9b\x8e;\xf2\xd8"n/\xd6\xd5\xdf\x13\xa2x\x80$\x89\x11\x9e\xd8\x81\x16\x146\xb9#\x8b\xd3\xf9\xe6\xc1\x7f\xa2\x0cp\xe5\x99\x12\xa8\x80\xdad\x15zi!\x98\xab\xf9Ff\x99gvG$g\xdf1\xa0\x80\x9bM\xc2\t\x19\x00\x19p\xd9\x9d\x99G6\xd7Hl\xdf\x99\xc2\xc8\x9e|~\t\x88)~Q@c\x99\xa3\x0cZg\x06\x00\xf8\x96\xa8)\x0c,\xc0h\xa3\x05^\x02\xe9(\x93Rji\x84\xcb)\'\x1fn\x9d~\nj)\xa3\x0e\xffZis\x84\x06\xd7\x81\xaak\xae\xc6\x01\x07\xa0\xb5\xfa*\xac~\xc9z\xaa\x04\x03l\x80+b\xb7\x81V@\x01$\xac\xd6\xe9\xab\xb1\xd2:kpj\x0ep\xe7\xb1\xab\x9aRA\x01!\x14\xd7\xc0\x03\x8dF\x1b\xdc\x00\xd3\x8ar-\xb6\xc8\x12\x07Z\t\x15\xf0:\xdd\xb7n\x8ak\xaa(\x1ddz\xac\x14\x86\x80\x92+~\xf8\xc1\xbb\xa3\xbc\xe4\xae\xe1\x01\xbaR\xfcAG\'\\\xa4\xab\x1a\xbf\xef\x82k\xa1\xbc\x03\xa3\xeb\xd7\x1d\xa4T\xcc\x87\xc2\xc5qP\x02\xc3\xab\xf9+\x9e\xb8OH\xec\xd7\x1bYTL\x8a\x1f~\xa1\x91\xecj"\xd8\xc01n\xfe\x8e\xdaA\x06\xe7\xa2;\t)Q\xb0AJ\x15\\\xa8\xbc2h!\x14\xe0\xee\xcb\xa05\x10\xc6\xa8"s&\x07\n\x13L\xb0sA\x0b\x9b\xa2\x81\x08"h\xf02\x0f\x15\xe0\x964g2\xa8\xd1D\xd3\xa4\xe8\x01\xf5t\x1c\x14`\xc6\xcb\xcbN\x11\xe7\xd6\x87]@\xca\xd7\x8f\x90\xf2\x01\x08#\x10t\x80$\xc5\x99\xc1-\xc7?\x14\xff@\xc6\xdal\x8f\xe2\x04)b0\xb1\t)}\x84\x12J&\x04\x05\x02\xc5\x18\xb8\xd9P\xc0\x0f\x1c\x93`5h\x81_\xb0H(j\x98\xacD( \xc0`P\xc5\x8f\x83\xa6\xc1\xb6;l1\x9d\x06\x1bk\x9d4\x18:(\x1e\n\x15&sR\xb7A9\xc0Q\xf1 \x18X\x00Z\xdf<\x84\xa0:h$H^\x1cgC\\\xa0\xdc\x10\x9a\xc8\xae8\x11gdQ\x07\x01\x07!\x10\n\x11W| {\xef\xa6\x90\xb0m\x01"T B\x01<\xa8\xed\xba_X|pE\x1e\xa7\xc9\xe0D\x19\xce\xcb\xbe\x04\xf5\x08\x11\x80@\x02\xf1+\xce}\t!\xecP\xc1\x0ed\xb8\xdc\xf9\x86\xa0\x88\x8aQA\x06\x90\xc1\x02\xfc\xf2G\x83\x1c4\xc4~\xf8\xcb\x1f\xf7^v\x98D\x98\x0c\x07\xca\x1b\xc5\x05\xba\x90\xbfP`Bt\x14\x81`\x07\'\xc8/\xbf\xc8@\toC\x01)\x9c\x00\xbb\x0e\xd2\xcd$"\x94\xa0\xef\xf0\xe3\x978\xe0l\x02^ \x05\x07\xf3\x97\x00\x04\xd0\xaf%1t\xde\x0b|X\xb0\x820\x8db\x0f\xa4`\xc2\x04\x16@\x8a\x0e\xce\x8f(\x02\t\xa2\xec\x86X\xc4\xb5\x15"\x898\xc4A\xfc\x1a\x08\xc5\x82HQqT\xc4\xdc("A\n<\x08\x02\x05\x94\x90\x1d\r@\xd8E\x83|1\x14T\xbc\x80\x0e>@\n\x14\x88An\xa0\xbb]\x1b\x13\xf2F\xd9Y\xc2dg\xe8\xe1\x1e\x1d\xd2\xc7P\xa0\x10\x07\x84\xf8\xe1 \x1fx\xbf\xfc\x11\xa1\x12\x90XdG\x82\xb8FI\x02q\t/\xb4\xa4&[\x12\x10\x00;') # NOQA + + actual = response.json() + + self.assertEquals(actual, expected) + self.assertEquals(response.status_code, 502) + self.assertEquals(response.headers.get('Content-Type'), "application/json") + + +def make_service(list_of_routes, function_provider, cwd): + port = random_port() + manager = ContainerManager() + local_runtime = LambdaRuntime(manager) + lambda_runner = LocalLambdaRunner(local_runtime=local_runtime, + function_provider=function_provider, + cwd=cwd) + + service = Service(list_of_routes, lambda_runner, port=port) + + scheme = "http" + url = '{}://0.0.0.0:{}'.format(scheme, port) + return service, port, url, scheme + + +def make_service_response(port, method, scheme, resourcePath, resolvedResourcePath, pathParameters=None, + body=None, headers=None, queryParams=None, isBase64Encoded=False): + response_str = '{"httpMethod": "GET", "body": null, "resource": "/something/{event}", "requestContext": {"resourceId": "123456", "apiId": "1234567890", "resourcePath": "/something/{event}", "httpMethod": "GET", "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "accountId": "123456789012", "stage": "prod", "identity": {"apiKey": null, "userArn": null, "cognitoAuthenticationType": null, "caller": null, "userAgent": "Custom User Agent String", "user": null, "cognitoIdentityPoolId": null, "cognitoAuthenticationProvider": null, "sourceIp": "127.0.0.1", "accountId": null}, "extendedRequestId": null, "path": "/something/{event}"}, "queryStringParameters": null, "headers": {"Host": "0.0.0.0:33651", "User-Agent": "python-requests/2.18.4", "Accept-Encoding": "gzip, deflate", "Accept": "*/*", "Connection": "keep-alive"}, "pathParameters": {"event": "event1"}, "stageVariables": null, "path": "/something/event1", "isBase64Encoded": false}' # NOQA + response = json.loads(response_str) + + if body: + response["body"] = body + + response["httpMethod"] = method + response['requestContext']["httpMethod"] = method + response["requestContext"]["resourcePath"] = resourcePath + response["requestContext"]["path"] = resourcePath + response["resource"] = resourcePath + response["path"] = resolvedResourcePath + response["pathParameters"] = pathParameters + response["queryStringParameters"] = queryParams + response["isBase64Encoded"] = isBase64Encoded + + + headers = headers or {} + for header, value in headers.items(): + response["headers"][header] = value + + response["headers"]["Host"] = "0.0.0.0:{}".format(port) + response["headers"]["X-Forwarded-Port"] = str(port) + response["headers"]["X-Forwarded-Proto"] = scheme + + return response + + +def random_port(): + return random.randint(30000, 40000) + diff --git a/tests/functional/local/docker/__init__.py b/tests/functional/local/docker/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/local/docker/test_container_manager.py b/tests/functional/local/docker/test_container_manager.py new file mode 100644 index 0000000000..1a23f871e3 --- /dev/null +++ b/tests/functional/local/docker/test_container_manager.py @@ -0,0 +1,41 @@ +import docker + +from unittest import TestCase +from samcli.local.docker.manager import ContainerManager + + +class TestContainerManager(TestCase): + """ + Verifies functionality of ContainerManager by calling Docker APIs + """ + IMAGE = "busybox" # small sized Linux container + + @classmethod + def setUpClass(cls): + # Make sure we start with a clean slate + docker_client = docker.from_env() + TestContainerManager._remove_image(docker_client) + + def setUp(self): + self.manager = ContainerManager() + self.docker_client = docker.from_env() + + def tearDown(self): + self._remove_image(self.docker_client) + + def test_pull_image(self): + # Image should not exist + self.assertFalse(self.manager.has_image(self.IMAGE)) + + # Pull the image + self.manager.pull_image(self.IMAGE) + + # Image should be available now + self.assertTrue(self.manager.has_image(self.IMAGE)) + + @classmethod + def _remove_image(cls, docker_client): + try: + docker_client.images.remove(cls.IMAGE) + except docker.errors.ImageNotFound: + pass diff --git a/tests/functional/local/docker/test_lambda_container.py b/tests/functional/local/docker/test_lambda_container.py new file mode 100644 index 0000000000..50212de553 --- /dev/null +++ b/tests/functional/local/docker/test_lambda_container.py @@ -0,0 +1,166 @@ +""" +Functional test to ensure Lambda runtime Docker containers can be created, run and managed +""" +import os +import io +import random +import shutil +import docker +import six + +from contextlib import contextmanager +from unittest import TestCase + +from tests.functional.function_code import nodejs_lambda +from samcli.local.docker.lambda_container import LambdaContainer +from samcli.local.docker.manager import ContainerManager + + +class TestLambdaContainer(TestCase): + """ + Verify that the Lambda runtime Docker container is setup properly. It focuses on functionality that are + non-trivial to unit test such as connecting container to correct network, mounting folder properly, or + setting up debug port forwarding. These operations might also exhibit differences across Operating Systems, hence + necessary to tests them here. + """ + IMAGE_NAME = "lambci/lambda:nodejs4.3" + + HELLO_WORLD_CODE = """ + exports.handler = function(event, context, callback){ + + console.log("**This string is printed from Lambda function**"); + callback(null, {"a": "b"}) + } + """ + + @classmethod + def setUpClass(cls): + + manager = ContainerManager() + if not manager.has_image(cls.IMAGE_NAME): + manager.pull_image(cls.IMAGE_NAME) + + def setUp(self): + random.seed() + + self.runtime = "nodejs4.3" + self.expected_docker_image = self.IMAGE_NAME + self.handler = "index.handler" + self.debug_port = _rand_port() + self.code_dir = nodejs_lambda(self.HELLO_WORLD_CODE) + self.network_prefix = "sam_cli_test_network" + + self.docker_client = docker.from_env() + + def testDown(self): + + # Delete the code path if it exists + if os.path.exists(self.code_dir): + shutil.rmtree(self.code_dir) + + def test_basic_creation(self): + """ + A docker container must be successfully created + """ + + container = LambdaContainer(self.runtime, self.handler, self.code_dir) + + self.assertIsNone(container.id, "Container must not have ID before creation") + + # Create the container and verify its properties + with self._create(container): + self.assertIsNotNone(container.id, "Container must have an ID") + + # Call Docker API to make sure container indeed exists + actual_container = self.docker_client.containers.get(container.id) + self.assertEquals(actual_container.status, "created") + self.assertTrue(self.expected_docker_image in actual_container.image.tags, + "Image name of the container must be " + self.expected_docker_image) + + def test_debug_port_is_created_on_host(self): + + container = LambdaContainer(self.runtime, self.handler, self.code_dir, debug_port=self.debug_port) + + with self._create(container): + + container.start() + + # After container is started, query the container to make sure it is bound to the right ports + port_binding = self.docker_client.api.port(container.id, self.debug_port) + self.assertIsNotNone(port_binding, "Container must be bound to a port on host machine") + self.assertEquals(1, len(port_binding), "Only one port must be bound to the container") + self.assertEquals(port_binding[0]["HostPort"], str(self.debug_port)) + + def test_container_is_attached_to_network(self): + container = LambdaContainer(self.runtime, self.handler, self.code_dir) + + with self._network_create() as network: + + # Ask the container to attach to the network + container.network_id = network.id + with self._create(container): + + container.start() + + # Now that the container has been created, it would be connected to the network + # Fetch the latest information about this network from server + network.reload() + + self.assertEquals(1, len(network.containers)) + self.assertEquals(container.id, network.containers[0].id) + + def test_function_result_is_available_in_stdout_and_logs_in_stderr(self): + + # This is the JSON result from Lambda function + # Convert to proper binary type to be compatible with Python 2 & 3 + expected_output = six.binary_type('{"a":"b"}'.encode('utf-8')) + expected_stderr = six.binary_type("**This string is printed from Lambda function**".encode("utf-8")) + + container = LambdaContainer(self.runtime, self.handler, self.code_dir) + stdout_stream = io.BytesIO() + stderr_stream = io.BytesIO() + + with self._create(container): + + container.start() + container.wait_for_logs(stdout=stdout_stream, stderr=stderr_stream) + + function_output = stdout_stream.getvalue() + function_stderr = stderr_stream.getvalue() + + self.assertEquals(function_output.strip(), expected_output) + self.assertIn(expected_stderr, function_stderr) + + @contextmanager + def _create(self, container): + """ + Create a container and delete it when execute leaves the given context + + :param samcli.local.docker.container.Container container: Container to create + :yield: ID of the created container + """ + + id = None + try: + id = container.create() + yield id + finally: + if id: + container.delete() + + @contextmanager + def _network_create(self): + + name = "{}_{}".format(self.network_prefix, random.randint(1, 100)) + network = None + + try: + network = self.docker_client.networks.create(name) + yield network + finally: + if network: + network.remove() + +def _rand_port(): + return random.randint(30000, 40000) + diff --git a/tests/functional/local/lambdafn/__init__.py b/tests/functional/local/lambdafn/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/functional/local/lambdafn/test_runtime.py b/tests/functional/local/lambdafn/test_runtime.py new file mode 100644 index 0000000000..9205ac1736 --- /dev/null +++ b/tests/functional/local/lambdafn/test_runtime.py @@ -0,0 +1,252 @@ +import shutil +import io +import logging +import json +import random +import threading + +from collections import namedtuple +from timeit import default_timer as timer +from unittest import TestCase +from parameterized import parameterized, param + +from tests.functional.function_code import nodejs_lambda, make_zip, ECHO_CODE, SLEEP_CODE, GET_ENV_VAR +from samcli.local.docker.manager import ContainerManager +from samcli.local.lambdafn.runtime import LambdaRuntime +from samcli.local.lambdafn.config import FunctionConfig + +logging.basicConfig(level=logging.INFO) + +RUNTIME = "nodejs4.3" +HANDLER = "index.handler" +MEMORY = 1024 + + +class TestLambdaRuntime(TestCase): + + # Approx Number of seconds it takes to startup a Docker container. This helps us measure + # the approx time that the Lambda Function actually ran for + CONTAINER_STARTUP_OVERHEAD_SECONDS = 5 + + def setUp(self): + self.code_dir = { + "echo": nodejs_lambda(ECHO_CODE), + "sleep": nodejs_lambda(SLEEP_CODE), + "envvar": nodejs_lambda(GET_ENV_VAR) + } + + self.container_manager = ContainerManager() + self.runtime = LambdaRuntime(self.container_manager) + + def tearDown(self): + for _, dir in self.code_dir.items(): + shutil.rmtree(dir) + + def test_echo_function(self): + timeout = 3 + input_event = '{"a":"b"}' + expected_output = '{"a":"b"}' + + config = FunctionConfig(name="helloworld", + runtime=RUNTIME, + handler=HANDLER, + code_abs_path=self.code_dir["echo"], + timeout=timeout) + + stdout_stream = io.BytesIO() + self.runtime.invoke(config, input_event, stdout=stdout_stream) + + actual_output = stdout_stream.getvalue() + self.assertEquals(actual_output.strip().decode('utf-8'), expected_output) + + def test_function_timeout(self): + """ + Setup a short timeout and verify that the container is stopped + """ + stdout_stream = io.BytesIO() + timeout = 1 # 1 second timeout + sleep_seconds = 20 # Ask the function to sleep for 20 seconds + + config = FunctionConfig(name="sleep_timeout", + runtime=RUNTIME, + handler=HANDLER, + code_abs_path=self.code_dir["sleep"], + timeout=timeout) + + # Measure the actual duration of execution + start = timer() + self.runtime.invoke(config, str(sleep_seconds), stdout=stdout_stream) + end = timer() + + # Make sure that the wall clock duration is around the ballpark of timeout value + wall_clock_func_duration = end - start + print("Function completed in {} seconds".format(wall_clock_func_duration)) + # The function should *not* preemptively stop + self.assertGreater(wall_clock_func_duration, timeout - 1) + # The function should not run for much longer than timeout. + self.assertLess(wall_clock_func_duration, timeout + self.CONTAINER_STARTUP_OVERHEAD_SECONDS) + + # There should be no output from the function because timer was interrupted + actual_output = stdout_stream.getvalue() + self.assertEquals(actual_output.strip().decode('utf-8'), "") + + @parameterized.expand([ + ("zip"), + ("jar"), + ("ZIP"), + ("JAR") + ]) + def test_echo_function_with_zip_file(self, file_name_extension): + timeout = 3 + input_event = '"this input should be echoed"' + expected_output = '"this input should be echoed"' + + code_dir = self.code_dir["echo"] + with make_zip(code_dir, file_name_extension) as code_zip_path: + + config = FunctionConfig(name="helloworld", + runtime=RUNTIME, + handler=HANDLER, + code_abs_path=code_zip_path, + timeout=timeout) + + stdout_stream = io.BytesIO() + self.runtime.invoke(config, input_event, stdout=stdout_stream) + + actual_output = stdout_stream.getvalue() + self.assertEquals(actual_output.strip().decode('utf-8'), expected_output) + + def test_check_environment_variables(self): + variables = {"var1": "value1", "var2": "value2"} + aws_creds = {"region": "ap-south-1", "key": "mykey", "secret": "mysecret"} + + timeout = 30 + input_event = "" + stdout_stream = io.BytesIO() + expected_output = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "30", + "AWS_LAMBDA_FUNCTION_HANDLER": "index.handler", + + # Values coming from AWS Credentials + "AWS_REGION": "ap-south-1", + "AWS_DEFAULT_REGION": "ap-south-1", + "AWS_ACCESS_KEY_ID": "mykey", + "AWS_SECRET_ACCESS_KEY": "mysecret", + + # Custom environment variables + "var1": "value1", + "var2": "value2" + } + + config = FunctionConfig(name="helloworld", + runtime=RUNTIME, + handler=HANDLER, + code_abs_path=self.code_dir["envvar"], + memory=MEMORY, + timeout=timeout) + + # Set the appropriate environment variables + config.env_vars.variables = variables + config.env_vars.aws_creds = aws_creds + + self.runtime.invoke(config, input_event, stdout=stdout_stream) + + actual_output = json.loads(stdout_stream.getvalue().strip()) # Output is a JSON String. Deserialize. + + # Make sure all key/value from expected_output is present in actual_output + for key, value in expected_output.items(): + # Do the key check first to print a nice error error message when it fails + self.assertTrue(key in actual_output, "'{}' should be in environment variable output".format(key)) + self.assertEquals(actual_output[key], expected_output[key], + "Value of environment variable '{}' differs fromm expectation".format(key)) + + +class TestLambdaRuntime_MultipleInvokes(TestCase): + + def setUp(self): + self.code_dir = nodejs_lambda(SLEEP_CODE) + + Input = namedtuple('Input', ["timeout", "sleep", "check_stdout"]) + self.inputs = [ + Input(sleep=1, timeout=10, check_stdout=True), + Input(sleep=2, timeout=10, check_stdout=True), + Input(sleep=3, timeout=10, check_stdout=True), + Input(sleep=5, timeout=10, check_stdout=True), + Input(sleep=8, timeout=10, check_stdout=True), + Input(sleep=13, timeout=12, check_stdout=False), # Must timeout + Input(sleep=21, timeout=20, check_stdout=False), # Must timeout. So stdout will be empty + ] + random.shuffle(self.inputs) + + container_manager = ContainerManager() + self.runtime = LambdaRuntime(container_manager) + + def tearDown(self): + shutil.rmtree(self.code_dir) + + def _invoke_sleep(self, timeout, sleep_duration, check_stdout, exceptions=None): + + name = "sleepfunction_timeout_{}_sleep_{}".format(timeout, sleep_duration) + print("Invoking function " + name) + try: + stdout_stream = io.BytesIO() + config = FunctionConfig(name=name, + runtime=RUNTIME, + handler=HANDLER, + code_abs_path=self.code_dir, + memory=1024, + timeout=timeout) + + self.runtime.invoke(config, sleep_duration, stdout=stdout_stream) + actual_output = stdout_stream.getvalue().strip() # Must output the sleep duration + if check_stdout: + self.assertEquals(actual_output.decode('utf-8'), str(sleep_duration)) + except Exception as ex: + if exceptions is not None: + exceptions.append({"name": name, "error": ex}) + else: + raise + + def test_serial(self): + """ + Making sure we can invoke multiple times on the same ``LambdaRuntime`` object. This is test is necessary to + catch timer that was not cancelled, race conditions, memory leak issues, etc. + """ + + for input in self.inputs: + self._invoke_sleep(input.timeout, input.sleep, input.check_stdout) + + def test_parallel(self): + """ + Making sure we can invoke multiple times on the same ``LambdaRuntime`` object. This is test is necessary to + catch timer that was not cancelled, race conditions, memory leak issues, etc. + """ + + threads = [] + + # Collect all exceptions from threads. This is important because exceptions reported in thread don't bubble + # to the main thread. Therefore test runner will never catch and fail the test. + exceptions = [] + + for input in self.inputs: + + t = threading.Thread(name='thread', target=self._invoke_sleep, + args=(input.timeout, input.sleep, input.check_stdout, exceptions)) + t.setDaemon(True) + t.start() + threads.append(t) + + # Wait for all threads to exit + for t in threads: + t.join() + + for e in exceptions: + print("-------------") + print("ERROR in function " + e["name"]) + print(e["error"]) + print("-------------") + + if len(exceptions) > 0: + raise AssertionError("Test failed. See print outputs above for details on the thread that failed") diff --git a/tests/integration/__init__.py b/tests/integration/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/init/__init__.py b/tests/integration/init/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/init/test_init_command.py b/tests/integration/init/test_init_command.py new file mode 100644 index 0000000000..f657ee53d7 --- /dev/null +++ b/tests/integration/init/test_init_command.py @@ -0,0 +1,24 @@ +from unittest import TestCase +from subprocess import Popen +import os + +from backports import tempfile + + +class TestBasicInitCommand(TestCase): + + def test_init_command_passes_and_dir_created(self): + with tempfile.TemporaryDirectory() as temp: + process = Popen([TestBasicInitCommand._get_command(), "init", "-o", temp]) + return_code = process.wait() + + self.assertEquals(return_code, 0) + self.assertTrue(os.path.isdir(temp + "/sam-app")) + + @staticmethod + def _get_command(): + command = "sam" + if os.getenv("SAM_CLI_DEV"): + command = "samdev" + + return command diff --git a/tests/integration/local/__init__.py b/tests/integration/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/local/invoke/__init__.py b/tests/integration/local/invoke/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/local/invoke/invoke_integ_base.py b/tests/integration/local/invoke/invoke_integ_base.py new file mode 100644 index 0000000000..7d2faefe18 --- /dev/null +++ b/tests/integration/local/invoke/invoke_integ_base.py @@ -0,0 +1,42 @@ +import os +from unittest import TestCase + +try: + from pathlib import Path +except ImportError: + from pathlib2 import Path + + +class InvokeIntegBase(TestCase): + + @classmethod + def setUpClass(cls): + cls.cmd = cls.base_command() + + integration_dir = str(Path(__file__).resolve().parents[2]) + + cls.template_path = integration_dir + "/testdata/invoke/template.yml" + cls.event_path = integration_dir + "/testdata/invoke/event.json" + cls.env_var_path = integration_dir + "/testdata/invoke/vars.json" + + @classmethod + def base_command(cls): + command = "sam" + if os.getenv("SAM_CLI_DEV"): + command = "samdev" + + return command + + def get_command_list(self, function_to_invoke, template_path=None, event_path=None, env_var_path=None): + command_list = [self.cmd, "local", "invoke", function_to_invoke] + + if template_path: + command_list = command_list + ["-t", template_path] + + if event_path: + command_list = command_list + ["-e", event_path] + + if env_var_path: + command_list = command_list + ["-n", env_var_path] + + return command_list diff --git a/tests/integration/local/invoke/test_integrations_cli.py b/tests/integration/local/invoke/test_integrations_cli.py new file mode 100644 index 0000000000..ca5889f1fd --- /dev/null +++ b/tests/integration/local/invoke/test_integrations_cli.py @@ -0,0 +1,96 @@ +from subprocess import Popen, PIPE +from timeit import default_timer as timer + +from .invoke_integ_base import InvokeIntegBase + + +class TestSamPython36HelloWorldIntegration(InvokeIntegBase): + + def test_invoke_returncode_is_zero(self): + command_list = self.get_command_list("HelloWorldServerlessFunction", + template_path=self.template_path, + event_path=self.event_path) + + process = Popen(command_list, stdout=PIPE) + return_code = process.wait() + + self.assertEquals(return_code, 0) + + def test_invoke_returns_execpted_results(self): + command_list = self.get_command_list("HelloWorldServerlessFunction", + template_path=self.template_path, + event_path=self.event_path) + + process = Popen(command_list, stdout=PIPE) + process.wait() + process_stdout = "".join(process.stdout.readlines()).strip() + self.assertEquals(process_stdout, '"Hello world"') + + def test_invoke_of_lambda_function(self): + command_list = self.get_command_list("HelloWorldLambdaFunction", + template_path=self.template_path, + event_path=self.event_path) + + process = Popen(command_list, stdout=PIPE) + process.wait() + process_stdout = "".join(process.stdout.readlines()).strip() + self.assertEquals(process_stdout, '"Hello world"') + + def test_invoke_with_timeout_set(self): + command_list = self.get_command_list("HelloWorldSleepFunction", + template_path=self.template_path, + event_path=self.event_path) + + start = timer() + process = Popen(command_list, stdout=PIPE) + return_code = process.wait() + end = timer() + + wall_clock_cli_duration = end - start + + process_stdout = "".join(process.stdout.readlines()).strip() + + # validate the time of the cli (timeout is set to 5s) + self.assertGreater(wall_clock_cli_duration, 5) + self.assertLess(wall_clock_cli_duration, 20) + + self.assertEquals(return_code, 0) + self.assertEquals(process_stdout, "", msg="The return statement in the LambdaFunction " + "should never return leading to an empty string") + + def test_invoke_with_env_vars(self): + command_list = self.get_command_list("EchoCustomEnvVarFunction", + template_path=self.template_path, + event_path=self.event_path, + env_var_path=self.env_var_path) + + process = Popen(command_list, stdout=PIPE) + process.wait() + process_stdout = "".join(process.stdout.readlines()).strip() + self.assertEquals(process_stdout, '"MyVar"') + + def test_invoke_when_function_writes_stdout(self): + command_list = self.get_command_list("WriteToStdoutFunction", + template_path=self.template_path, + event_path=self.event_path) + + process = Popen(command_list, stdout=PIPE, stderr=PIPE) + process.wait() + + process_stdout = "".join(process.stdout.readlines()).strip() + process_stderr = "".join(process.stderr.readlines()).strip() + + self.assertIn("Docker Lambda is writing to stdout", process_stderr) + self.assertIn("wrote to stdout", process_stdout) + + def test_invoke_when_function_writes_stderr(self): + command_list = self.get_command_list("WriteToStderrFunction", + template_path=self.template_path, + event_path=self.event_path) + + process = Popen(command_list, stderr=PIPE) + process.wait() + + process_stderr = "".join(process.stderr.readlines()).strip() + + self.assertIn("Docker Lambda is writing to stderr", process_stderr) diff --git a/tests/integration/local/start_api/__init__.py b/tests/integration/local/start_api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/integration/local/start_api/start_api_integ_base.py b/tests/integration/local/start_api/start_api_integ_base.py new file mode 100644 index 0000000000..08306a2649 --- /dev/null +++ b/tests/integration/local/start_api/start_api_integ_base.py @@ -0,0 +1,59 @@ +from unittest import TestCase +import threading +from subprocess import Popen +import time +import os +import random + +try: + from pathlib import Path +except ImportError: + from pathlib2 import Path + + +class StartApiIntegBaseClass(TestCase): + template = None + binary_data_file = None + integration_dir = str(Path(__file__).resolve().parents[2]) + + @classmethod + def setUpClass(cls): + # This is the directory for tests/integration which will be used to file the testdata + # files for integ tests + cls.template = cls.integration_dir + cls.template_path + + if cls.binary_data_file: + cls.binary_data_file = os.path.join(cls.integration_dir, cls.binary_data_file) + + cls.port = str(StartApiIntegBaseClass.random_port()) + + cls.thread = threading.Thread(target=cls.start_api()) + cls.thread.setDaemon(True) + cls.thread.start() + + @classmethod + def start_api(cls): + command = "sam" + if os.getenv("SAM_CLI_DEV"): + command = "samdev" + + cls.start_api_process = Popen([command, "local", "start-api", "-t", cls.template, "-p", cls.port, "--debug"]) + # we need to wait some time for start-api to start, hence the sleep + time.sleep(5) + + @classmethod + def tearDownClass(cls): + # After all the tests run, we need to kill the start-api process. + cls.start_api_process.kill() + + @staticmethod + def random_port(): + return random.randint(30000, 40000) + + @staticmethod + def get_binary_data(filename): + if not filename: + return None + + with open(filename, "rb") as fp: + return fp.read() diff --git a/tests/integration/local/start_api/test_start_api.py b/tests/integration/local/start_api/test_start_api.py new file mode 100644 index 0000000000..be1350f501 --- /dev/null +++ b/tests/integration/local/start_api/test_start_api.py @@ -0,0 +1,418 @@ +import requests +from concurrent.futures import ThreadPoolExecutor, as_completed +from time import time + +from .start_api_integ_base import StartApiIntegBaseClass + + +class TestParallelRequests(StartApiIntegBaseClass): + """ + Test Class centered around sending parallel requests to the service `sam local start-api` + """ + # This is here so the setUpClass doesn't fail. Set to this something else once the class is implemented + template_path = "/testdata/start_api/template.yaml" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_same_endpoint(self): + """ + Send two requests to the same path at the same time. This is to ensure we can handle + multiple requests at once and do not block/queue up requests + """ + number_of_requests = 10 + start_time = time() + thread_pool = ThreadPoolExecutor(number_of_requests) + + futures = [thread_pool.submit(requests.get, self.url + "/sleepfortenseconds/function1") + for _ in range(0, number_of_requests)] + results = [r.result() for r in as_completed(futures)] + + end_time = time() + + self.assertEquals(len(results), 10) + self.assertGreater(end_time - start_time, 10) + self.assertLess(end_time - start_time, 20) + + for result in results: + self.assertEquals(result.status_code, 200) + self.assertEquals(result.json(), {"message": "HelloWorld! I just slept and waking up."}) + + def test_different_endpoints(self): + """ + Send two requests to different paths at the same time. This is to ensure we can handle + multiple requests for different paths and do not block/queue up the requests + """ + number_of_requests = 10 + start_time = time() + thread_pool = ThreadPoolExecutor(10) + + test_url_paths = ["/sleepfortenseconds/function0", "/sleepfortenseconds/function1"] + + futures = [thread_pool.submit(requests.get, self.url + test_url_paths[function_num % len(test_url_paths)]) + for function_num in range(0, number_of_requests)] + results = [r.result() for r in as_completed(futures)] + + end_time = time() + + self.assertEquals(len(results), 10) + self.assertGreater(end_time - start_time, 10) + self.assertLess(end_time - start_time, 20) + + for result in results: + self.assertEquals(result.status_code, 200) + self.assertEquals(result.json(), {"message": "HelloWorld! I just slept and waking up."}) + + +class TestServiceErrorResponses(StartApiIntegBaseClass): + """ + Test Class centered around the Error Responses the Service can return for a given api + """ + # This is here so the setUpClass doesn't fail. Set to this something else once the class is implemented. + template_path = "/testdata/start_api/template.yaml" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_invalid_http_verb_for_endpoint(self): + response = requests.get(self.url + "/id") + + self.assertEquals(response.status_code, 403) + self.assertEquals(response.json(), {"message": "Missing Authentication Token"}) + + def test_invalid_response_from_lambda(self): + response = requests.get(self.url + "/invalidresponsereturned") + + self.assertEquals(response.status_code, 502) + self.assertEquals(response.json(), {"message": "Internal server error"}) + + def test_request_timeout(self): + pass + + +class TestService(StartApiIntegBaseClass): + """ + Testing general requirements around the Service that powers `sam local start-api` + """ + template_path = "/testdata/start_api/template.yaml" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_static_directory(self): + pass + + def test_calling_proxy_endpoint(self): + response = requests.get(self.url + "/proxypath/this/is/some/path") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_get_call_with_path_setup_with_any_implicit_api(self): + """ + Get Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.get(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_post_call_with_path_setup_with_any_implicit_api(self): + """ + Post Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.post(self.url + "/anyandall", json={}) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_put_call_with_path_setup_with_any_implicit_api(self): + """ + Put Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.put(self.url + "/anyandall", json={}) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_head_call_with_path_setup_with_any_implicit_api(self): + """ + Head Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.head(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + + def test_delete_call_with_path_setup_with_any_implicit_api(self): + """ + Delete Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.delete(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_options_call_with_path_setup_with_any_implicit_api(self): + """ + Options Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.options(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + + def test_patch_call_with_path_setup_with_any_implicit_api(self): + """ + Patch Request to a path that was defined as ANY in SAM through AWS::Serverless::Function Events + """ + response = requests.patch(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + +class TestStartApiWithSwaggerApis(StartApiIntegBaseClass): + template_path = "/testdata/start_api/swagger-template.yaml" + binary_data_file = "testdata/start_api/binarydata.gif" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_get_call_with_path_setup_with_any_swagger(self): + """ + Get Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.get(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_post_call_with_path_setup_with_any_swagger(self): + """ + Post Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.post(self.url + "/anyandall", json={}) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_put_call_with_path_setup_with_any_swagger(self): + """ + Put Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.put(self.url + "/anyandall", json={}) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_head_call_with_path_setup_with_any_swagger(self): + """ + Head Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.head(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + + def test_delete_call_with_path_setup_with_any_swagger(self): + """ + Delete Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.delete(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_options_call_with_path_setup_with_any_swagger(self): + """ + Options Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.options(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + + def test_patch_call_with_path_setup_with_any_swagger(self): + """ + Patch Request to a path that was defined as ANY in SAM through Swagger + """ + response = requests.patch(self.url + "/anyandall") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_function_not_defined_in_template(self): + response = requests.get(self.url + "/nofunctionfound") + + self.assertEquals(response.status_code, 502) + self.assertEquals(response.json(), {"message": "No function defined for resource method"}) + + def test_function_with_no_api_event_is_reachable(self): + response = requests.get(self.url + "/functionwithnoapievent") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_lambda_function_resource_is_reachable(self): + response = requests.get(self.url + "/nonserverlessfunction") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_binary_request(self): + """ + This tests that the service can accept and invoke a lambda when given binary data in a request + """ + input_data = self.get_binary_data(self.binary_data_file) + response = requests.post(self.url + '/echobase64eventbody', + headers={"Content-Type": "image/gif"}, + data=input_data) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get("Content-Type"), "image/gif") + self.assertEquals(response.content, input_data) + + def test_binary_response(self): + """ + Binary data is returned correctly + """ + expected = self.get_binary_data(self.binary_data_file) + + response = requests.get(self.url + '/base64response') + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get("Content-Type"), "image/gif") + self.assertEquals(response.content, expected) + + +class TestServiceResponses(StartApiIntegBaseClass): + """ + Test Class centered around the different responses that can happen in Lambda and pass through start-api + """ + template_path = "/testdata/start_api/template.yaml" + binary_data_file = "testdata/start_api/binarydata.gif" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_binary_response(self): + """ + Binary data is returned correctly + """ + expected = self.get_binary_data(self.binary_data_file) + + response = requests.get(self.url + '/base64response') + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get("Content-Type"), "image/gif") + self.assertEquals(response.content, expected) + + def test_default_header_content_type(self): + """ + Test that if no ContentType is given the default is "application/json" + """ + response = requests.get(self.url + "/onlysetstatuscode") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.content, "no data") + self.assertEquals(response.headers.get("Content-Type"), "application/json") + + def test_default_status_code(self): + """ + Test that if no status_code is given, the status code is 200 + :return: + """ + response = requests.get(self.url + "/onlysetbody") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_default_body(self): + """ + Test that if no body is given, the response is 'no data' + """ + response = requests.get(self.url + "/onlysetstatuscode") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.content, "no data") + + def test_function_writing_to_stdout(self): + response = requests.get(self.url + "/writetostdout") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + def test_function_writing_to_stderr(self): + response = requests.get(self.url + "/writetostderr") + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.json(), {'hello': 'world'}) + + +class TestServiceRequests(StartApiIntegBaseClass): + """ + Test Class centered around the different requests that can happen + """ + template_path = "/testdata/start_api/template.yaml" + binary_data_file = "testdata/start_api/binarydata.gif" + + def setUp(self): + self.url = "http://127.0.0.1:{}".format(self.port) + + def test_binary_request(self): + """ + This tests that the service can accept and invoke a lambda when given binary data in a request + """ + input_data = self.get_binary_data(self.binary_data_file) + response = requests.post(self.url + '/echobase64eventbody', + headers={"Content-Type": "image/gif"}, + data=input_data) + + self.assertEquals(response.status_code, 200) + self.assertEquals(response.headers.get("Content-Type"), "image/gif") + self.assertEquals(response.content, input_data) + + def test_request_with_query_params(self): + """ + Query params given should be put into the Event to Lambda + """ + response = requests.get(self.url + "/id/4", + params={"key": "value"}) + + self.assertEquals(response.status_code, 200) + + response_data = response.json() + + self.assertEquals(response_data.get("queryStringParameters"), {"key": ["value"]}) + + def test_request_with_path_params(self): + """ + Path Parameters given should be put into the Event to Lambda + """ + response = requests.get(self.url + "/id/4") + + self.assertEquals(response.status_code, 200) + + response_data = response.json() + + self.assertEquals(response_data.get("pathParameters"), {"id": "4"}) + + def test_request_with_many_path_params(self): + """ + Path Parameters given should be put into the Event to Lambda + """ + response = requests.get(self.url + "/id/4/user/jacob") + + self.assertEquals(response.status_code, 200) + + response_data = response.json() + + self.assertEquals(response_data.get("pathParameters"), {"id": "4", "user": "jacob"}) + + def test_forward_headers_are_added_to_event(self): + """ + Test the Forwarding Headers exist in the Api Event to Lambda + """ + response = requests.get(self.url + "/id/4") + + response_data = response.json() + + self.assertEquals(response_data.get("headers").get("X-Forwarded-Proto"), "http") + self.assertEquals(response_data.get("headers").get("X-Forwarded-Port"), self.port) diff --git a/samples/hello-world/golang/event.json b/tests/integration/testdata/invoke/event.json similarity index 100% rename from samples/hello-world/golang/event.json rename to tests/integration/testdata/invoke/event.json diff --git a/tests/integration/testdata/invoke/main.py b/tests/integration/testdata/invoke/main.py new file mode 100644 index 0000000000..f36b7e9d63 --- /dev/null +++ b/tests/integration/testdata/invoke/main.py @@ -0,0 +1,35 @@ +import time +import os +import sys +print('Loading function') + + +def handler(event, context): + print("value1 = " + event['key1']) + print("value2 = " + event['key2']) + print("value3 = " + event['key3']) + + sys.stdout.write("Docker Lambda is writing to stderr") + + return "Hello world" + + +def sleep_handler(event, context): + time.sleep(10) + return "Slept for 10s" + + +def env_var_echo_hanler(event, context): + return os.environ.get("CustomEnvVar") + + +def write_to_stderr(event, context): + sys.stderr.write("Docker Lambda is writing to stderr") + + return "wrote to stderr" + + +def write_to_stdout(event, context): + sys.stdout.write("Docker Lambda is writing to stdout") + + return "wrote to stdout" diff --git a/tests/integration/testdata/invoke/template.yml b/tests/integration/testdata/invoke/template.yml new file mode 100644 index 0000000000..7ff2617d26 --- /dev/null +++ b/tests/integration/testdata/invoke/template.yml @@ -0,0 +1,50 @@ +AWSTemplateFormatVersion : '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: A hello world application. +Resources: + HelloWorldServerlessFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + Timeout: 600 + + HelloWorldLambdaFunction: + Type: AWS::Lambda::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + + HelloWorldSleepFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.sleep_handler + Runtime: python3.6 + CodeUri: . + Timeout: 5 + + EchoCustomEnvVarFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.env_var_echo_hanler + Runtime: python3.6 + CodeUri: . + Environment: + Variables: + CustomEnvVar: "MyVar" + + WriteToStderrFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.write_to_stderr + Runtime: python3.6 + CodeUri: . + + WriteToStdoutFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.write_to_stdout + Runtime: python3.6 + CodeUri: . diff --git a/tests/integration/testdata/invoke/vars.json b/tests/integration/testdata/invoke/vars.json new file mode 100644 index 0000000000..a55702360a --- /dev/null +++ b/tests/integration/testdata/invoke/vars.json @@ -0,0 +1,5 @@ +{ + "EchoCustomEnvVarFunction": { + "CustomEnvVar": "MyVar" + } +} \ No newline at end of file diff --git a/tests/integration/testdata/start_api/binarydata.gif b/tests/integration/testdata/start_api/binarydata.gif new file mode 100644 index 0000000000..855b404179 Binary files /dev/null and b/tests/integration/testdata/start_api/binarydata.gif differ diff --git a/tests/integration/testdata/start_api/main.py b/tests/integration/testdata/start_api/main.py new file mode 100644 index 0000000000..7e13f99dd8 --- /dev/null +++ b/tests/integration/testdata/start_api/main.py @@ -0,0 +1,75 @@ +import json +import sys +import time + + +def handler(event, context): + + return {"statusCode": 200, "body": json.dumps({"hello": "world"})} + + +def echo_event_handler(event, context): + + return {"statusCode": 200, "body": json.dumps(event)} + + +def content_type_setter_handler(event, context): + + return {"statusCode": 200, "body": "hello", "headers": {"Content-Type": "text/plain"}} + + +def only_set_status_code_handler(event, context): + + return {"statusCode": 200} + + +def only_set_body_handler(event, context): + + return {"body": json.dumps({"hello": "world"})} + + +def sleep_10_sec_handler(event, context): + # sleep thread for 10s. This is useful for testing multiple requests + time.sleep(10) + + return {"statusCode": 200, "body": json.dumps({"message": "HelloWorld! I just slept and waking up."})} + + +def write_to_stderr(event, context): + sys.stderr.write("Docker Lambda is writing to stderr") + + return {"statusCode": 200, "body": json.dumps({"hello": "world"})} + + +def write_to_stdout(event, context): + sys.stdout.write("Docker Lambda is writing to stdout") + + return {"statusCode": 200, "body": json.dumps({"hello": "world"})} + + +def invalid_response_returned(event, context): + return "This is invalid" + + +def base64_response(event, context): + gifImageBase64 = "R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAKgALAAAAAA9AEQAAAj/AFEJHEiwoMGDCBMqXMiwocAbBww4nEhxoYkUpzJGrMixogkfGUNqlNixJEIDB0SqHGmyJSojM1bKZOmyop0gM3Oe2liTISKMOoPy7GnwY9CjIYcSRYm0aVKSLmE6nfq05QycVLPuhDrxBlCtYJUqNAq2bNWEBj6ZXRuyxZyDRtqwnXvkhACDV+euTeJm1Ki7A73qNWtFiF+/gA95Gly2CJLDhwEHMOUAAuOpLYDEgBxZ4GRTlC1fDnpkM+fOqD6DDj1aZpITp0dtGCDhr+fVuCu3zlg49ijaokTZTo27uG7Gjn2P+hI8+PDPERoUB318bWbfAJ5sUNFcuGRTYUqV/3ogfXp1rWlMc6awJjiAAd2fm4ogXjz56aypOoIde4OE5u/F9x199dlXnnGiHZWEYbGpsAEA3QXYnHwEFliKAgswgJ8LPeiUXGwedCAKABACCN+EA1pYIIYaFlcDhytd51sGAJbo3onOpajiihlO92KHGaUXGwWjUBChjSPiWJuOO/LYIm4v1tXfE6J4gCSJEZ7YgRYUNrkji9P55sF/ogxw5ZkSqIDaZBV6aSGYq/lGZplndkckZ98xoICbTcIJGQAZcNmdmUc210hs35nCyJ58fgmIKX5RQGOZowxaZwYA+JaoKQwswGijBV4C6SiTUmpphMspJx9unX4KaimjDv9aaXOEBteBqmuuxgEHoLX6Kqx+yXqqBANsgCtit4FWQAEkrNbpq7HSOmtwag5w57GrmlJBASEU18ADjUYb3ADTinIttsgSB1oJFfA63bduimuqKB1keqwUhoCSK374wbujvOSu4QG6UvxBRydcpKsav++Ca6G8A6Pr1x2kVMyHwsVxUALDq/krnrhPSOzXG1lUTIoffqGR7Goi2MAxbv6O2kEG56I7CSlRsEFKFVyovDJoIRTg7sugNRDGqCJzJgcKE0ywc0ELm6KBCCJo8DIPFeCWNGcyqNFE06ToAfV0HBRgxsvLThHn1oddQMrXj5DyAQgjEHSAJMWZwS3HPxT/QMbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==" # NOQA + + return { + "statusCode": 200, + "body": gifImageBase64, + "isBase64Encoded": True, + "headers": { + "Content-Type": "image/gif" + } + } + + +def echo_base64_event_body(event, context): + return { + "statusCode": 200, + "body": event["body"], + "headers": { + "Content-Type": event["headers"]["Content-Type"] + }, + "isBase64Encoded": event["isBase64Encoded"] + } diff --git a/tests/integration/testdata/start_api/swagger-template.yaml b/tests/integration/testdata/start_api/swagger-template.yaml new file mode 100644 index 0000000000..bee44de7cf --- /dev/null +++ b/tests/integration/testdata/start_api/swagger-template.yaml @@ -0,0 +1,111 @@ +AWSTemplateFormatVersion : '2010-09-09' +Transform: AWS::Serverless-2016-10-31 + +Globals: + Api: + BinaryMediaTypes: + # These are equivalent to image/gif and image/png when deployed + - image~1png + +Resources: + MyApi: + Type: AWS::Serverless::Api + Properties: + StageName: prod + DefinitionBody: + swagger: "2.0" + info: + title: + Ref: AWS::StackName + "x-amazon-apigateway-binary-media-types": + - image/gif + paths: + "/functionwithnoapievent": + get: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${NoApiEventFunction.Arn}/invocations + responses: {} + "/anyandall": + x-amazon-apigateway-any-method: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations + responses: {} + "/nonserverlessfunction": + get: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyNonServerlessLambdaFunction.Arn}/invocations + "/nofunctionfound": + get: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${WhatFunction.Arn}/invocations + + "/base64response": + get: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Base64ResponseFunction.Arn}/invocations + + "/echobase64eventbody": + post: + x-amazon-apigateway-integration: + httpMethod: POST + type: aws_proxy + uri: + Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${EchoBase64EventBodyFunction.Arn}/invocations + + MyLambdaFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + Events: + GetApi: + Type: Api + Properties: + Path: /get + Method: GET + RestApiId: + Ref: MyApi + + NoApiEventFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + + MyNonServerlessLambdaFunction: + Type: AWS::Lambda::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + + Base64ResponseFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.base64_response + Runtime: python3.6 + CodeUri: . + + EchoBase64EventBodyFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.echo_base64_event_body + Runtime: python3.6 + CodeUri: . diff --git a/tests/integration/testdata/start_api/template.yaml b/tests/integration/testdata/start_api/template.yaml new file mode 100644 index 0000000000..bb80fccb0e --- /dev/null +++ b/tests/integration/testdata/start_api/template.yaml @@ -0,0 +1,186 @@ +AWSTemplateFormatVersion : '2010-09-09' +Transform: AWS::Serverless-2016-10-31 + +Globals: + Api: + BinaryMediaTypes: + # These are equivalent to image/gif and image/png when deployed + - image~1gif + - image~1png + +Resources: + HelloWorldFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.handler + Runtime: python3.6 + CodeUri: . + Events: + IdBasePath: + Type: Api + Properties: + Method: POST + Path: /id + + PathWithAnyMethod: + Type: Api + Properties: + Method: ANY + Path: /anyandall + + ProxyPath: + Type: Api + Properties: + Method: GET + Path: /proxypath/{proxy+} + + EchoEventFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.echo_event_handler + Runtime: python3.6 + CodeUri: . + Events: + PathWithPathParams: + Type: Api + Properties: + Method: GET + Path: /id/{id}/user/{user} + + PathWithPathParam: + Type: Api + Properties: + Method: GET + Path: /id/{id} + + ContentTypeSetterFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.content_type_setter_handler + Runtime: python3.6 + CodeUri: . + Events: + ContentTypeSetter: + Type: Api + Properties: + Method: GET + Path: /getcontenttype + + OnlySetStatusCodeFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.only_set_status_code_handler + Runtime: python3.6 + CodeUri: . + Events: + OnlySetStatusCodePath: + Type: Api + Properties: + Method: Get + Path: /onlysetstatuscode + + OnlySetBodyFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.only_set_body_handler + Runtime: python3.6 + CodeUri: . + Events: + OnlySetBodyPath: + Type: Api + Properties: + Method: Get + Path: /onlysetbody + + SleepFunction0: + Type: AWS::Serverless::Function + Properties: + Handler: main.sleep_10_sec_handler + Runtime: python3.6 + CodeUri: . + Timeout: 20 + Events: + SleepPath: + Type: Api + Properties: + Method: GET + Path: /sleepfortenseconds/function0 + + SleepFunction1: + Type: AWS::Serverless::Function + Properties: + Handler: main.sleep_10_sec_handler + Runtime: python3.6 + CodeUri: . + Timeout: 20 + Events: + SleepPath: + Type: Api + Properties: + Method: GET + Path: /sleepfortenseconds/function1 + + WriteToStderrFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.write_to_stderr + Runtime: python3.6 + CodeUri: . + Events: + WriteToStderrPath: + Type: Api + Properties: + Method: GET + Path: /writetostderr + + WriteToStdoutFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.write_to_stdout + Runtime: python3.6 + CodeUri: . + Events: + WriteToStdoutPath: + Type: Api + Properties: + Method: GET + Path: /writetostdout + + InvalidResponseFromLambdaFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.invalid_response_returned + Runtime: python3.6 + CodeUri: . + Events: + InvalidResponseReturned: + Type: Api + Properties: + Method: GET + Path: /invalidresponsereturned + + Base64ResponseFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.base64_response + Runtime: python3.6 + CodeUri: . + Events: + Base64ResponsePath: + Type: Api + Properties: + Method: GET + Path: /base64response + + EchoBase64EventBodyFunction: + Type: AWS::Serverless::Function + Properties: + Handler: main.echo_base64_event_body + Runtime: python3.6 + CodeUri: . + Events: + EchoBase64EventBodyPath: + Type: Api + Properties: + Method: POST + Path: /echobase64eventbody diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/cli/__init__.py b/tests/unit/cli/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/cli/test_command.py b/tests/unit/cli/test_command.py new file mode 100644 index 0000000000..baa93e14a8 --- /dev/null +++ b/tests/unit/cli/test_command.py @@ -0,0 +1,93 @@ +import click + +from unittest import TestCase +from mock import Mock, patch, call +from samcli.cli.command import BaseCommand + + +class TestBaseCommand(TestCase): + + def setUp(self): + + self.packages = [ + "a.b.cmd1", + "foo.cmd2", + "cmd3" + ] + + def test_must_inherit(self): + + cmd = BaseCommand() + self.assertTrue(isinstance(cmd, click.MultiCommand)) + + def test_set_commands_must_extract_command_name(self): + expected = { + "cmd1": "a.b.cmd1", + "cmd2": "foo.cmd2", + "cmd3": "cmd3" + } + + result = BaseCommand._set_commands(self.packages) + self.assertEquals(result, expected) + + def test_list_commands_must_return_commands_name(self): + expected = ["cmd1", "cmd2", "cmd3"].sort() + + cmd = BaseCommand(cmd_packages=self.packages) + result = cmd.list_commands(ctx=None) + self.assertEquals(result.sort(), expected) + + @patch("samcli.cli.command.importlib") + def test_get_command_must_return_command_module(self, importlib_mock): + module_mock = Mock() + module_mock.cli = Mock() + + importlib_mock.import_module = Mock() + importlib_mock.import_module.return_value = module_mock + + cmd = BaseCommand(cmd_packages=self.packages) + + result = cmd.get_command(None, "cmd1") + self.assertEquals(result, module_mock.cli) + + result = cmd.get_command(None, "cmd2") + self.assertEquals(result, module_mock.cli) + + result = cmd.get_command(None, "cmd3") + self.assertEquals(result, module_mock.cli) + + # Library to import the modules must be called three times + importlib_mock.import_module.assert_has_calls([ + call("a.b.cmd1"), + call("foo.cmd2"), + call("cmd3") + ]) + + def test_get_command_must_skip_unknown_commands(self): + + cmd = BaseCommand(cmd_packages=self.packages) + result = cmd.get_command(None, "unknown_command") + + self.assertEquals(result, None, "must not return a command") + + @patch("samcli.cli.command.importlib") + def test_get_command_must_skip_on_exception_loading_module(self, importlib_mock): + + cmd = BaseCommand(cmd_packages=self.packages) + + importlib_mock.import_module = Mock() + importlib_mock.import_module.side_effect = ImportError() + + result = cmd.get_command(None, "cmd1") + self.assertEquals(result, None, "must not return a command") + + @patch("samcli.cli.command.importlib") + def test_get_command_must_skip_on_absence_of_cli_method(self, importlib_mock): + + cmd = BaseCommand(cmd_packages=self.packages) + + importlib_mock.import_module = Mock() + importlib_mock.import_module.return_value = {} # Returned Module does *not* have 'cli' property + + result = cmd.get_command(None, "cmd1") + self.assertEquals(result, None, "must not return a command") diff --git a/tests/unit/cli/test_context.py b/tests/unit/cli/test_context.py new file mode 100644 index 0000000000..219118ba45 --- /dev/null +++ b/tests/unit/cli/test_context.py @@ -0,0 +1,29 @@ +import logging + +from unittest import TestCase +from samcli.cli.context import Context + + +class TestContext(TestCase): + + def test_must_initialize_with_defaults(self): + ctx = Context() + + self.assertEquals(ctx.debug, False, "debug must default to False") + + def test_must_set_get_debug_flag(self): + ctx = Context() + + ctx.debug = True + self.assertEquals(ctx.debug, True, "debug must be set to True") + self.assertEquals(logging.getLogger().getEffectiveLevel(), logging.DEBUG) + + def test_must_unset_get_debug_flag(self): + ctx = Context() + + ctx.debug = True + self.assertEquals(ctx.debug, True, "debug must be set to True") + + # Flipping from True to False + ctx.debug = False + self.assertEquals(ctx.debug, False, "debug must be set to False") diff --git a/tests/unit/cli/test_main.py b/tests/unit/cli/test_main.py new file mode 100644 index 0000000000..d22372e16e --- /dev/null +++ b/tests/unit/cli/test_main.py @@ -0,0 +1,29 @@ +from unittest import TestCase +from click.testing import CliRunner +from samcli.cli.main import cli + + +class TestCliBase(TestCase): + + def test_cli_base(self): + """ + Just invoke the CLI without any commands and assert that help text was printed + :return: + """ + runner = CliRunner() + result = runner.invoke(cli, []) + self.assertEquals(result.exit_code, 0) + self.assertTrue("--help" in result.output, "Help text must be printed") + self.assertTrue("--debug" in result.output, "--debug option must be present in help text") + + def test_cli_some_command(self): + + runner = CliRunner() + result = runner.invoke(cli, ["validate"]) + self.assertEquals(result.exit_code, 1) + + def test_cli_with_debug(self): + + runner = CliRunner() + result = runner.invoke(cli, ["validate", "--debug"]) + self.assertEquals(result.exit_code, 1) diff --git a/tests/unit/commands/__init__.py b/tests/unit/commands/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/init/__init__.py b/tests/unit/commands/init/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/init/test_cli.py b/tests/unit/commands/init/test_cli.py new file mode 100644 index 0000000000..a2a201076a --- /dev/null +++ b/tests/unit/commands/init/test_cli.py @@ -0,0 +1,49 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.init import do_cli as init_cli +from samcli.local.init.exceptions import GenerateProjectFailedError +from samcli.commands.local.cli_common.user_exceptions import UserException + + +class TestCli(TestCase): + + def setUp(self): + self.ctx = None + self.location = None + self.runtime = "python3.6" + self.output_dir = "." + self.name = "testing project" + self.no_input = False + + @patch("samcli.commands.init.generate_project") + def test_init_cli(self, generate_project_patch): + # GIVEN generate_project successfully created a project + # WHEN a project name has been passed + init_cli( + ctx=self.ctx, location=self.location, runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=self.no_input) + + # THEN we should receive no errors + generate_project_patch.assert_called_once_with( + self.location, self.runtime, + self.output_dir, self.name, self.no_input) + + @patch("samcli.commands.init.generate_project") + def test_init_cli_generate_project_fails(self, generate_project_patch): + + # GIVEN generate_project fails to create a project + generate_project_patch.side_effect = GenerateProjectFailedError( + project=self.name, provider_error="Something wrong happened" + ) + + # WHEN generate_project returns an error + # THEN we should receive a GenerateProjectFailedError Exception + with self.assertRaises(UserException): + init_cli( + self.ctx, location="self.location", runtime=self.runtime, + output_dir=self.output_dir, name=self.name, no_input=self.no_input) + + generate_project_patch.assert_called_with( + self.location, self.runtime, + self.output_dir, self.name, self.no_input) diff --git a/tests/unit/commands/local/__init__.py b/tests/unit/commands/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/cli_common/__init__.py b/tests/unit/commands/local/cli_common/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/cli_common/test_invoke_context.py b/tests/unit/commands/local/cli_common/test_invoke_context.py new file mode 100644 index 0000000000..1b0cdcde49 --- /dev/null +++ b/tests/unit/commands/local/cli_common/test_invoke_context.py @@ -0,0 +1,387 @@ +""" +Tests the InvokeContext class +""" + +import os +import sys +import yaml +import docker + +import requests + +from samcli.commands.local.cli_common.user_exceptions import InvokeContextException +from samcli.commands.local.cli_common.invoke_context import InvokeContext + +from unittest import TestCase +from mock import Mock, patch, ANY, mock_open +from parameterized import parameterized, param + + +class TestInvokeContext__enter__(TestCase): + + @patch("samcli.commands.local.cli_common.invoke_context.SamFunctionProvider") + def test_must_read_from_necessary_files(self, SamFunctionProviderMock): + function_provider = Mock() + + SamFunctionProviderMock.return_value = function_provider + + template_file = "template_file" + env_vars_file = "env_vars_file" + log_file = "log_file" + + invoke_context = InvokeContext(template_file=template_file, + function_identifier="id", + env_vars_file=env_vars_file, + debug_port=123, + debug_args="args", + docker_volume_basedir="volumedir", + docker_network="network", + log_file=log_file, + skip_pull_image=True, + aws_profile="profile") + + template_dict = "template_dict" + invoke_context._get_template_data = Mock() + invoke_context._get_template_data.return_value = template_dict + + env_vars_value = "env_vars_value" + invoke_context._get_env_vars_value = Mock() + invoke_context._get_env_vars_value.return_value = env_vars_value + + log_file_handle = "handle" + invoke_context._setup_log_file = Mock() + invoke_context._setup_log_file.return_value = log_file_handle + + invoke_context._check_docker_connectivity = Mock() + + # Call Enter method manually for testing purposes + result = invoke_context.__enter__() + self.assertTrue(result is invoke_context, "__enter__() must return self") + + self.assertEquals(invoke_context._template_dict, template_dict) + self.assertEquals(invoke_context._function_provider, function_provider) + self.assertEquals(invoke_context._env_vars_value, env_vars_value) + self.assertEquals(invoke_context._log_file_handle, log_file_handle) + + invoke_context._get_template_data.assert_called_with(template_file) + SamFunctionProviderMock.assert_called_with(template_dict) + invoke_context._get_env_vars_value.assert_called_with(env_vars_file) + invoke_context._setup_log_file.assert_called_with(log_file) + invoke_context._check_docker_connectivity.assert_called_with() + + +class TestInvokeContext__exit__(TestCase): + + def test_must_close_opened_logfile(self): + context = InvokeContext(template_file="template") + handle_mock = Mock() + context._log_file_handle = handle_mock + + context.__exit__() + + handle_mock.close.assert_called_with() + self.assertIsNone(context._log_file_handle) + + def test_must_ignore_if_handle_is_absent(self): + context = InvokeContext(template_file="template") + context._log_file_handle = None + + context.__exit__() + self.assertIsNone(context._log_file_handle) + + +class TestInvokeContextAsContextManager(TestCase): + """ + Must be able to use the class as a context manager + """ + + @patch.object(InvokeContext, "__enter__") + @patch.object(InvokeContext, "__exit__") + def test_must_work_in_with_statement(self, ExitMock, EnterMock): + + context_obj = Mock() + EnterMock.return_value = context_obj + + with InvokeContext(template_file="template_file", + function_identifier="id", + env_vars_file="env_vars_file", + debug_port=123, + debug_args="args", + docker_volume_basedir="volumedir", + docker_network="network", + log_file="log_file", + skip_pull_image=True, + aws_profile="profile") as context: + self.assertEquals(context_obj, context) + + EnterMock.assert_called_with() + self.assertEquals(1, ExitMock.call_count) + + +class TestInvokeContext_function_name_property(TestCase): + + def test_must_return_function_name_if_present(self): + id = "id" + context = InvokeContext(template_file="template_file", function_identifier=id) + + self.assertEquals(id, context.function_name) + + def test_must_return_one_function_from_template(self): + context = InvokeContext(template_file="template_file") + + function = Mock() + function.name = "myname" + context._function_provider = Mock() + context._function_provider.get_all.return_value = [function] # Provider returns only one function + + self.assertEquals("myname", context.function_name) + + def test_must_raise_if_more_than_one_function(self): + context = InvokeContext(template_file="template_file") + + context._function_provider = Mock() + context._function_provider.get_all.return_value = [Mock(), Mock(), Mock()] # Provider returns three functions + + with self.assertRaises(InvokeContextException): + context.function_name + + +class TestInvokeContext_local_lambda_runner(TestCase): + + def setUp(self): + self.context = InvokeContext(template_file="template_file", + function_identifier="id", + env_vars_file="env_vars_file", + debug_port=123, + debug_args="args", + docker_volume_basedir="volumedir", + docker_network="network", + log_file="log_file", + skip_pull_image=True, + aws_profile="profile") + + @patch("samcli.commands.local.cli_common.invoke_context.ContainerManager") + @patch("samcli.commands.local.cli_common.invoke_context.LambdaRuntime") + @patch("samcli.commands.local.cli_common.invoke_context.LocalLambdaRunner") + def test_must_create_runner(self, LocalLambdaMock, LambdaRuntimeMock, ContainerManagerMock): + + container_mock = Mock() + ContainerManagerMock.return_value = container_mock + + runtime_mock = Mock() + LambdaRuntimeMock.return_value = runtime_mock + + runner_mock = Mock() + LocalLambdaMock.return_value = runner_mock + + cwd = "cwd" + self.context.get_cwd = Mock() + self.context.get_cwd.return_value = cwd + + result = self.context.local_lambda_runner + self.assertEquals(result, runner_mock) + + ContainerManagerMock.assert_called_with(docker_network_id="network", + skip_pull_image=True) + LambdaRuntimeMock.assert_called_with(container_mock) + LocalLambdaMock.assert_called_with(local_runtime=runtime_mock, + function_provider=ANY, + cwd=cwd, + env_vars_values=ANY, + debug_port=123, + debug_args="args", + aws_profile="profile") + + +class TestInvokeContext_stdout_property(TestCase): + + def test_must_return_log_file_handle(self): + context = InvokeContext(template_file="template") + context._log_file_handle = "handle" + + self.assertEquals("handle", context.stdout) + + def test_must_return_sys_stdout(self): + context = InvokeContext(template_file="template") + + self.assertEquals(sys.stdout, context.stdout) + + +class TestInvokeContext_stderr_property(TestCase): + + def test_must_return_log_file_handle(self): + context = InvokeContext(template_file="template") + context._log_file_handle = "handle" + + self.assertEquals("handle", context.stderr) + + def test_must_return_sys_stderr(self): + context = InvokeContext(template_file="template") + + self.assertEquals(sys.stderr, context.stderr) + + +class TestInvokeContext_template_property(TestCase): + + def test_must_return_tempalte_dict(self): + context = InvokeContext(template_file="file") + context._template_dict = "My template" + + self.assertEquals("My template", context.template) + + +class TestInvokeContextget_cwd(TestCase): + + def test_must_return_template_file_dir_name(self): + filename = "filename" + context = InvokeContext(template_file=filename) + + expected = os.path.dirname(os.path.abspath(filename)) + result = context.get_cwd() + + self.assertEquals(result, expected) + + def test_must_return_docker_volume_dir(self): + filename = "filename" + context = InvokeContext(template_file=filename, docker_volume_basedir="basedir") + + result = context.get_cwd() + self.assertEquals(result, "basedir") + + +class TestInvokeContext_get_template_data(TestCase): + + def test_must_raise_if_file_does_not_exist(self): + filename = "filename" + + with self.assertRaises(InvokeContextException) as exception_ctx: + InvokeContext._get_template_data(filename) + + ex = exception_ctx.exception + self.assertEquals(str(ex), "Template file not found at {}".format(filename)) + + @patch("samcli.commands.local.cli_common.invoke_context.yaml_parse") + @patch("samcli.commands.local.cli_common.invoke_context.os") + def test_must_read_file_and_parse(self, os_mock, yaml_parse_mock): + filename = "filename" + file_data = "contents of the file" + parse_result = "parse result" + + os_mock.patch.exists.return_value = True # Fake that the file exists + + m = mock_open(read_data=file_data) + yaml_parse_mock.return_value = parse_result + + with patch("samcli.commands.local.cli_common.invoke_context.open", m): + result = InvokeContext._get_template_data(filename) + + self.assertEquals(result, parse_result) + + m.assert_called_with(filename, 'r') + yaml_parse_mock.assert_called_with(file_data) + + @parameterized.expand([ + param(ValueError()), + param(yaml.YAMLError()) + ]) + @patch("samcli.commands.local.cli_common.invoke_context.yaml_parse") + @patch("samcli.commands.local.cli_common.invoke_context.os") + def test_must_raise_on_parse_errors(self, exception, os_mock, yaml_parse_mock): + filename = "filename" + file_data = "contents of the file" + + os_mock.patch.exists.return_value = True # Fake that the file exists + + m = mock_open(read_data=file_data) + yaml_parse_mock.side_effect = exception + + with patch("samcli.commands.local.cli_common.invoke_context.open", m): + + with self.assertRaises(InvokeContextException) as ex_ctx: + InvokeContext._get_template_data(filename) + + actual_exception = ex_ctx.exception + self.assertTrue(str(actual_exception).startswith("Failed to parse template: ")) + + +class TestInvokeContext_get_env_vars_value(TestCase): + + def test_must_return_if_no_file(self): + result = InvokeContext._get_env_vars_value(filename=None) + self.assertIsNone(result, "No value must be returned") + + def test_must_read_file_and_parse_as_json(self): + filename = "filename" + file_data = '{"a": "b"}' + expected = {"a": "b"} + + m = mock_open(read_data=file_data) + + with patch("samcli.commands.local.cli_common.invoke_context.open", m): + result = InvokeContext._get_env_vars_value(filename) + + self.assertEquals(expected, result) + + m.assert_called_with(filename, 'r') + + def test_must_raise_if_failed_to_parse_json(self): + filename = "filename" + file_data = 'invalid json' + + m = mock_open(read_data=file_data) + + with patch("samcli.commands.local.cli_common.invoke_context.open", m): + + with self.assertRaises(InvokeContextException) as ex_ctx: + InvokeContext._get_env_vars_value(filename) + + msg = str(ex_ctx.exception) + self.assertTrue(msg.startswith("Could not read environment variables overrides from file {}".format( + filename))) + + +class TestInvokeContext_setup_log_file(TestCase): + + def test_must_return_if_file_not_given(self): + result = InvokeContext._setup_log_file(log_file=None) + self.assertIsNone(result, "Log file must not be setup") + + def test_must_open_file_for_writing(self): + filename = "foo" + m = mock_open() + + with patch("samcli.commands.local.cli_common.invoke_context.open", m): + InvokeContext._setup_log_file(filename) + + m.assert_called_with(filename, 'w') + + +class TestInvokeContext_check_docker_connectivity(TestCase): + + def test_must_call_ping(self): + client = Mock() + InvokeContext._check_docker_connectivity(client) + client.ping.assert_called_with() + + @patch("samcli.commands.local.cli_common.invoke_context.docker") + def test_must_call_ping_with_docker_client_from_env(self, docker_mock): + client = Mock() + docker_mock.from_env.return_value = client + + InvokeContext._check_docker_connectivity() + client.ping.assert_called_with() + + @parameterized.expand([ + param("Docker APIError thrown", docker.errors.APIError("error")), + param("Requests ConnectionError thrown", requests.exceptions.ConnectionError("error")) + ]) + def test_must_raise_if_docker_not_found(self, test_name, error_docker_throws): + client = Mock() + + client.ping.side_effect = error_docker_throws + + with self.assertRaises(InvokeContextException) as ex_ctx: + InvokeContext._check_docker_connectivity(client) + + msg = str(ex_ctx.exception) + self.assertEquals(msg, "Running AWS SAM projects locally requires Docker. Have you got it installed?") diff --git a/tests/unit/commands/local/cli_common/test_options.py b/tests/unit/commands/local/cli_common/test_options.py new file mode 100644 index 0000000000..e15ef13218 --- /dev/null +++ b/tests/unit/commands/local/cli_common/test_options.py @@ -0,0 +1,41 @@ +""" +Test the common CLI options for invoke +""" + +import os + +from unittest import TestCase +from mock import patch +from samcli.commands.local.cli_common.options import get_or_default_template_file_name, _TEMPLATE_OPTION_DEFAULT_VALUE + + +class TestGetOrDefaultTemplateFileName(TestCase): + + def test_must_return_abspath_of_user_provided_value(self): + filename = "foo.txt" + expected = os.path.abspath(filename) + + result = get_or_default_template_file_name(None, None, filename) + self.assertEquals(result, expected) + + @patch("samcli.commands.local.cli_common.options.os") + def test_must_return_yml_extension(self, os_mock): + expected = "template.yml" + + os_mock.path.exists.return_value = False # Fake .yaml file to not exist. + os_mock.path.abspath.return_value = "absPath" + + result = get_or_default_template_file_name(None, None, _TEMPLATE_OPTION_DEFAULT_VALUE) + self.assertEquals(result, "absPath") + os_mock.path.abspath.assert_called_with(expected) + + @patch("samcli.commands.local.cli_common.options.os") + def test_must_return_yaml_extension(self, os_mock): + expected = "template.yaml" + + os_mock.path.exists.return_value = True + os_mock.path.abspath.return_value = "absPath" + + result = get_or_default_template_file_name(None, None, _TEMPLATE_OPTION_DEFAULT_VALUE) + self.assertEquals(result, "absPath") + os_mock.path.abspath.assert_called_with(expected) diff --git a/tests/unit/commands/local/generate_event/__init__.py b/tests/unit/commands/local/generate_event/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/api/__init__.py b/tests/unit/commands/local/generate_event/api/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/api/test_cli.py b/tests/unit/commands/local/generate_event/api/test_cli.py new file mode 100644 index 0000000000..cb8d16f9e2 --- /dev/null +++ b/tests/unit/commands/local/generate_event/api/test_cli.py @@ -0,0 +1,23 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.api.cli import do_cli as api_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.api.cli.json") + @patch("samcli.commands.local.generate_event.api.cli.click") + @patch("samcli.commands.local.generate_event.api.cli.generate_api_event") + def test_generate_schedule_event(self, api_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + method = "method" + body = "body" + resource = "resource" + path = "path" + + api_cli(ctx=None, method=method, body=body, resource=resource, path=path) + + api_event_patch.assert_called_once_with(method, body, resource, path) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/generate_event/dynamodb/__init__.py b/tests/unit/commands/local/generate_event/dynamodb/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/dynamodb/test_cli.py b/tests/unit/commands/local/generate_event/dynamodb/test_cli.py new file mode 100644 index 0000000000..56a45f5d19 --- /dev/null +++ b/tests/unit/commands/local/generate_event/dynamodb/test_cli.py @@ -0,0 +1,20 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.dynamodb.cli import do_cli as dynamodb_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.dynamodb.cli.json") + @patch("samcli.commands.local.generate_event.dynamodb.cli.click") + @patch("samcli.commands.local.generate_event.dynamodb.cli.generate_dynamodb_event") + def test_generate_schedule_event(self, dynamodb_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + region = "region" + + dynamodb_cli(ctx=None, region=region) + + dynamodb_event_patch.assert_called_once_with(region) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/generate_event/kinesis/__init__.py b/tests/unit/commands/local/generate_event/kinesis/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/kinesis/test_cli.py b/tests/unit/commands/local/generate_event/kinesis/test_cli.py new file mode 100644 index 0000000000..ae91e3fb70 --- /dev/null +++ b/tests/unit/commands/local/generate_event/kinesis/test_cli.py @@ -0,0 +1,25 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.kinesis.cli import do_cli as kinesis_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.kinesis.cli.json") + @patch("samcli.commands.local.generate_event.kinesis.cli.click") + @patch("samcli.commands.local.generate_event.kinesis.cli.generate_kinesis_event") + def test_generate_schedule_event(self, kinesis_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + region = "region" + partition = "partition" + sequence = "sequence" + data = "data" + + data_base64 = b"ZGF0YQ==" + + kinesis_cli(ctx=None, region=region, partition=partition, sequence=sequence, data=data) + + kinesis_event_patch.assert_called_once_with(region, partition, sequence, data_base64) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/generate_event/s3/__init__.py b/tests/unit/commands/local/generate_event/s3/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/s3/test_cli.py b/tests/unit/commands/local/generate_event/s3/test_cli.py new file mode 100644 index 0000000000..da2d86035d --- /dev/null +++ b/tests/unit/commands/local/generate_event/s3/test_cli.py @@ -0,0 +1,22 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.s3.cli import do_cli as s3_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.s3.cli.json") + @patch("samcli.commands.local.generate_event.s3.cli.click") + @patch("samcli.commands.local.generate_event.s3.cli.generate_s3_event") + def test_generate_schedule_event(self, s3_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + region = "region" + bucket = "bucket" + key = "key" + + s3_cli(ctx=None, region=region, bucket=bucket, key=key) + + s3_event_patch.assert_called_once_with(region, bucket, key) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/generate_event/schedule/__init__.py b/tests/unit/commands/local/generate_event/schedule/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/schedule/test_cli.py b/tests/unit/commands/local/generate_event/schedule/test_cli.py new file mode 100644 index 0000000000..0bd874608a --- /dev/null +++ b/tests/unit/commands/local/generate_event/schedule/test_cli.py @@ -0,0 +1,20 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.schedule.cli import do_cli as schedule_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.schedule.cli.json") + @patch("samcli.commands.local.generate_event.schedule.cli.click") + @patch("samcli.commands.local.generate_event.schedule.cli.generate_schedule_event") + def test_generate_schedule_event(self, schedule_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + region = "us-east-1" + + schedule_cli(ctx=None, region=region) + + schedule_event_patch.assert_called_once_with(region) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/generate_event/sns/__init__.py b/tests/unit/commands/local/generate_event/sns/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/generate_event/sns/test_cli.py b/tests/unit/commands/local/generate_event/sns/test_cli.py new file mode 100644 index 0000000000..a3091c6a98 --- /dev/null +++ b/tests/unit/commands/local/generate_event/sns/test_cli.py @@ -0,0 +1,22 @@ +from unittest import TestCase +from mock import patch + +from samcli.commands.local.generate_event.sns.cli import do_cli as sns_cli + + +class TestCli(TestCase): + + @patch("samcli.commands.local.generate_event.sns.cli.json") + @patch("samcli.commands.local.generate_event.sns.cli.click") + @patch("samcli.commands.local.generate_event.sns.cli.generate_sns_event") + def test_generate_schedule_event(self, sns_event_patch, click_patch, json_patch): + json_patch.dumps.return_value = "This to be echoed by click" + + message = "message" + topic = "topic" + subject = "subject" + + sns_cli(ctx=None, message=message, topic=topic, subject=subject) + + sns_event_patch.assert_called_once_with(message, topic, subject) + click_patch.echo.assert_called_once_with("This to be echoed by click") diff --git a/tests/unit/commands/local/invoke/__init__.py b/tests/unit/commands/local/invoke/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/invoke/test_cli.py b/tests/unit/commands/local/invoke/test_cli.py new file mode 100644 index 0000000000..e635ef95ff --- /dev/null +++ b/tests/unit/commands/local/invoke/test_cli.py @@ -0,0 +1,147 @@ +""" +Tests Local Invoke CLI +""" + +from unittest import TestCase +from mock import patch, Mock +from parameterized import parameterized, param + +from samcli.local.lambdafn.exceptions import FunctionNotFound +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException +from samcli.commands.local.cli_common.user_exceptions import UserException +from samcli.commands.local.invoke.cli import do_cli as invoke_cli, _get_event as invoke_cli_get_event + + +class TestCli(TestCase): + + def setUp(self): + self.function_id = "id" + self.template = "template" + self.eventfile = "eventfile" + self.env_vars = "env-vars" + self.debug_port = 123 + self.debug_args = "args" + self.docker_volume_basedir = "basedir" + self.docker_network = "network" + self.log_file = "logfile" + self.skip_pull_image = True + self.profile = "profile" + + @patch("samcli.commands.local.invoke.cli.InvokeContext") + @patch("samcli.commands.local.invoke.cli._get_event") + def test_cli_must_setup_context_and_invoke(self, get_event_mock, InvokeContextMock): + event_data = "data" + get_event_mock.return_value = event_data + + # Mock the __enter__ method to return a object inside a context manager + context_mock = Mock() + InvokeContextMock.return_value.__enter__.return_value = context_mock + + invoke_cli(ctx=None, + function_identifier=self.function_id, + template=self.template, + event=self.eventfile, + env_vars=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + profile=self.profile) + + InvokeContextMock.assert_called_with(template_file=self.template, + function_identifier=self.function_id, + env_vars_file=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + aws_profile=self.profile) + + context_mock.local_lambda_runner.invoke.assert_called_with(context_mock.function_name, + event=event_data, + stdout=context_mock.stdout, + stderr=context_mock.stderr) + get_event_mock.assert_called_with(self.eventfile) + + @patch("samcli.commands.local.invoke.cli.InvokeContext") + @patch("samcli.commands.local.invoke.cli._get_event") + def test_must_raise_user_exception_on_function_not_found(self, get_event_mock, InvokeContextMock): + event_data = "data" + get_event_mock.return_value = event_data + + # Mock the __enter__ method to return a object inside a context manager + context_mock = Mock() + InvokeContextMock.return_value.__enter__.return_value = context_mock + + context_mock.local_lambda_runner.invoke.side_effect = FunctionNotFound("not found") + + with self.assertRaises(UserException) as ex_ctx: + + invoke_cli(ctx=None, + function_identifier=self.function_id, + template=self.template, + event=self.eventfile, + env_vars=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + profile=self.profile) + + msg = str(ex_ctx.exception) + self.assertEquals(msg, "Function {} not found in template".format(self.function_id)) + + @patch("samcli.commands.local.invoke.cli.InvokeContext") + @patch("samcli.commands.local.invoke.cli._get_event") + def test_must_raise_user_exception_on_invalid_sam_template(self, get_event_mock, InvokeContextMock): + event_data = "data" + get_event_mock.return_value = event_data + + InvokeContextMock.side_effect = InvalidSamDocumentException("bad template") + + with self.assertRaises(UserException) as ex_ctx: + + invoke_cli(ctx=None, + function_identifier=self.function_id, + template=self.template, + event=self.eventfile, + env_vars=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + profile=self.profile) + + msg = str(ex_ctx.exception) + self.assertEquals(msg, "bad template") + + +class TestGetEvent(TestCase): + + @parameterized.expand([ + param("-"), + param("somefile") + ]) + @patch("samcli.commands.local.invoke.cli.click") + def test_must_work_with_stdin(self, filename, click_mock): + event_data = "some data" + + # Mock file pointer + fp_mock = Mock() + + # Mock the context manager + click_mock.open_file.return_value.__enter__.return_value = fp_mock + fp_mock.read.return_value = event_data + + result = invoke_cli_get_event(filename) + + self.assertEquals(result, event_data) + fp_mock.read.assert_called_with() diff --git a/tests/unit/commands/local/lib/__init__.py b/tests/unit/commands/local/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/lib/swagger/__init__.py b/tests/unit/commands/local/lib/swagger/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/local/lib/swagger/test_integration_uri.py b/tests/unit/commands/local/lib/swagger/test_integration_uri.py new file mode 100644 index 0000000000..4eb9dc1813 --- /dev/null +++ b/tests/unit/commands/local/lib/swagger/test_integration_uri.py @@ -0,0 +1,182 @@ +""" +Unit test for Lambda Integration URI parsing +""" + +import logging + +from samcli.commands.local.lib.swagger.integration_uri import LambdaUri +from unittest import TestCase +from parameterized import parameterized + + +logging.basicConfig(level=logging.DEBUG) + + +class TestLambdaUri(TestCase): + + FUNCTION_NAME = "MyCoolFunction" + + SUCCESS_CASES = [ + ( + "URI is a string with fully resolved ARN", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:MyCoolFunction/invocations" # NOQA + ), + + ( + "URI is a full ARN with any region and any account id", + "arn:aws:apigateway:<>:<>:path/2015-03-31/functions/arn:aws:lambda:region:accountid:function:MyCoolFunction/invocations" # NOQA + ), + + ( + + "URI is a Fn::Sub with a Lambda ARN as a variable", + { + "Fn::Sub": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyCoolFunction.Arn}/invocations" # NOQA + } + ), + + ( + "URI is a Fn::Sub with a Lambda Alias as a variable", + { + "Fn::Sub": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyCoolFunction.Alias}/invocations" # NOQA + } + ), + + ( + "URI is a Fn::Sub with a Lambda ARN as a variable in addition to others provided as string", + { + "Fn::Sub": "arn:${AWS::Partition}:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyCoolFunction.Arn}/invocations" # NOQA + } + ), + + ( + "URI is a Fn::Sub with a Lambda ARN as a variable in addition to others provided as array", + { + "Fn::Sub": [ + "arn:aws:apigateway:${region}:lambda:path/2015-03-31/functions/${MyCoolFunction.Arn}/invocations", + {"region": {"Ref": "AWS::Region"}} + ] + } + ), + + ( + "URI is a Fn::Sub resolvable intrinsic as an array", + { + "Fn::Sub": [ + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyCoolFunction.Arn}/invocations", + ] + } + ), + + ( + "URI is a string with just enough information to pass regex tests", + "foo/functions/bar:function:MyCoolFunction/invocations" # NOQA + ), + ] + + @parameterized.expand(SUCCESS_CASES) + def test_get_function_name_success(self, test_case_name, uri): + + result = LambdaUri.get_function_name(uri) + self.assertEquals(result, self.FUNCTION_NAME) + + FAILURE_CASES = [ + + ( + "URI is a string with stage variables", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:${stageVariables.FunctionName}/invocations" # NOQA + ), + + ( + "URI is an ARN string of non-Lambda resource", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:something:us-east-1:123456789012:event:MyCoolFunction/invocations" # NOQA + ), + + ( + "URI is a random string", + "hello world" + ), + + ( + "URI is an integration ARN without proper Lambda function name", + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:${ThisIntrinsicDidntGetSubstituted}/invocations" # NOQA + ), + + ( + "URI is a list", + [1, 2, 3] + ), + + ( + "URI is a dictionary with more than one keys", + { + "Fn::Sub": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyCoolFunction.Arn}/invocations", # NOQA + "SomeKey": "value" + } + ), + + ( + "URI is a Ref", + { + "Ref": "MyCoolFunction" + } + ), + + ( + "URI is a GetAtt", + { + "Fn::GetAtt": "MyCoolFunction.Arn" + } + ), + + ( + "URI is a Fn::Sub with array values that would resolve in CloudFormation", + { + "Fn::Sub": [ + # In CloudFormation this intrinsic function will resolve to correct function name. + # But unfortunately we don't support this here + "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyArn}/invocations", + { + "MyArn": {"Fn::GetAtt": "MyCoolFunction.Arn"} + } + ], + } + ), + + ( + "URI is a Fn::Sub with intrinsic that does not return an Arn or Alias", + { + "Fn::Sub": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${MyCoolFunction}/invocations", # NOQA + } + ), + + ( + "URI is a Fn::Sub with ignored variable created with ${! syntax", + { + "Fn::Sub": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/${!MyCoolFunction.Arn}/invocations", # NOQA + } + ), + + ( + "URI is a Fn::Sub is invalid in structure", + { + "Fn::Sub": {"foo": "bar"}, + } + ), + + ( + "URI is empty string", + "" + ), + + ( + "URI without enough information to pass regex test", + "bar:function:MyCoolFunction/invocations" + ), + ] + + @parameterized.expand(FAILURE_CASES) + def test_get_function_name_failure(self, test_case_name, uri): + + result = LambdaUri.get_function_name(uri) + self.assertIsNone(result, "Must fail to get function name when " + test_case_name) diff --git a/tests/unit/commands/local/lib/swagger/test_parser.py b/tests/unit/commands/local/lib/swagger/test_parser.py new file mode 100644 index 0000000000..59db1ea969 --- /dev/null +++ b/tests/unit/commands/local/lib/swagger/test_parser.py @@ -0,0 +1,211 @@ +""" +Test the swagger parser +""" + +from samcli.commands.local.lib.swagger.parser import SwaggerParser +from samcli.commands.local.lib.provider import Api + +from unittest import TestCase +from mock import patch, Mock +from parameterized import parameterized, param + + +class TestSwaggerParser_get_apis(TestCase): + + def test_with_one_path_method(self): + function_name = "myfunction" + swagger = { + "paths": { + "/path1": { + "get": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + } + } + } + + parser = SwaggerParser(swagger) + parser._get_integration_function_name = Mock() + parser._get_integration_function_name.return_value = function_name + + expected = [Api(path="/path1", method="get", function_name=function_name, cors=None)] + result = parser.get_apis() + + self.assertEquals(expected, result) + parser._get_integration_function_name.assert_called_with({ + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + }) + + def test_with_combination_of_paths_methods(self): + function_name = "myfunction" + swagger = { + "paths": { + "/path1": { + "get": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + }, + "delete": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + }, + + "/path2": { + "post": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + } + } + } + + parser = SwaggerParser(swagger) + parser._get_integration_function_name = Mock() + parser._get_integration_function_name.return_value = function_name + + expected = { + Api(path="/path1", method="get", function_name=function_name, cors=None), + Api(path="/path1", method="delete", function_name=function_name, cors=None), + Api(path="/path2", method="post", function_name=function_name, cors=None), + } + result = parser.get_apis() + + self.assertEquals(expected, set(result)) + + def test_with_any_method(self): + function_name = "myfunction" + swagger = { + "paths": { + "/path1": { + "x-amazon-apigateway-any-method": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + } + } + } + + parser = SwaggerParser(swagger) + parser._get_integration_function_name = Mock() + parser._get_integration_function_name.return_value = function_name + + expected = [Api(path="/path1", method="ANY", function_name=function_name, cors=None)] + result = parser.get_apis() + + self.assertEquals(expected, result) + + def test_does_not_have_function_name(self): + swagger = { + "paths": { + "/path1": { + "post": { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + } + } + } + + parser = SwaggerParser(swagger) + parser._get_integration_function_name = Mock() + parser._get_integration_function_name.return_value = None # Function Name could not be resolved + + expected = [] + result = parser.get_apis() + + self.assertEquals(expected, result) + + @parameterized.expand([ + param("empty swagger", {}), + param("'paths' property is absent", {"foo": "bar"}), + param("no paths", {"paths": {}}), + param("no methods", {"paths": { + "/path1": {} + }}), + param("no integration", {"paths": { + "/path1": { + "get": {} + } + }}) + ]) + def test_invalid_swagger(self, test_case_name, swagger): + + parser = SwaggerParser(swagger) + result = parser.get_apis() + + expected = [] + self.assertEquals(expected, result) + + +class TestSwaggerParser_get_integration_function_name(TestCase): + + @patch('samcli.commands.local.lib.swagger.parser.LambdaUri') + def test_valid_integration(self, LambdaUriMock): + function_name = "name" + LambdaUriMock.get_function_name.return_value = function_name + + method_config = { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "someuri" + } + } + + parser = SwaggerParser({}) + result = parser._get_integration_function_name(method_config) + + self.assertEquals(function_name, result) + LambdaUriMock.get_function_name.assert_called_with("someuri") + + @parameterized.expand([ + param("config is not dict", "myconfig"), + param("integration key is not in config", {"key": "value"}), + param("integration value is empty", {"x-amazon-apigateway-integration": {}}), + param("integration value is not dict", {"x-amazon-apigateway-integration": "someval"}), + param("integration type is not aws_proxy", {"x-amazon-apigateway-integration": { + "type": "mock", + }}), + param("integration uri is not present", {"x-amazon-apigateway-integration": { + "type": "aws_proxy" + }}) + ]) + @patch('samcli.commands.local.lib.swagger.parser.LambdaUri') + def test_invalid_integration(self, test_case_name, method_config, LambdaUriMock): + LambdaUriMock.get_function_name.return_value = None + + parser = SwaggerParser({}) + result = parser._get_integration_function_name(method_config) + + self.assertIsNone(result, "must not parse invalid integration") + + +class TestSwaggerParser_get_binary_media_types(TestCase): + + @parameterized.expand([ + param("Swagger was none", None, []), + param("Swagger is has no binary media types defined", {}, []), + param("Swagger define binary media types", + {"x-amazon-apigateway-binary-media-types": ["image/gif", "application/json"]}, + ["image/gif", "application/json"]) + ]) + def test_binary_media_type_returned(self, test_case_name, swagger, expected_result): + parser = SwaggerParser(swagger) + + self.assertEquals(parser.get_binary_media_types(), expected_result) diff --git a/tests/unit/commands/local/lib/swagger/test_reader.py b/tests/unit/commands/local/lib/swagger/test_reader.py new file mode 100644 index 0000000000..249ae61a82 --- /dev/null +++ b/tests/unit/commands/local/lib/swagger/test_reader.py @@ -0,0 +1,352 @@ + +import tempfile +import json +import os +import botocore + +from unittest import TestCase +from parameterized import parameterized, param +from mock import Mock, patch + +from samcli.commands.local.lib.swagger.reader import parse_aws_include_transform, SamSwaggerReader + + +class TestParseAwsIncludeTransform(TestCase): + + def test_must_return_location(self): + + data = { + "Fn::Transform": { + "Name": "AWS::Include", + "Parameters": { + "Location": "s3://bucket/swagger.yaml" + } + } + } + + expected = "s3://bucket/swagger.yaml" + result = parse_aws_include_transform(data) + + self.assertEquals(result, expected) + + @parameterized.expand([ + param({}), + param(None), + param({ + "Name": "AWS::Include", + "Parameters": { + "Location": "s3://bucket/swagger.yaml" + } + }), + param({ + "Fn::Transform": { + "Name": "AWS::SomeTransformName", + "Parameters": { + "Location": "s3://bucket/swagger.yaml" + } + } + }) + ]) + def test_invalid_aws_include_data(self, data): + result = parse_aws_include_transform(data) + self.assertIsNone(result) + + +class TestSamSwaggerReader_init(TestCase): + + def test_definition_body_and_uri_required(self): + + with self.assertRaises(ValueError): + SamSwaggerReader() + + +class TestSamSwaggerReader_read(TestCase): + + def test_must_read_first_from_definition_body(self): + body = {"this is": "swagger"} + uri = "./file.txt" + expected = {"some": "value"} + + reader = SamSwaggerReader(definition_body=body, definition_uri=uri) + reader._download_swagger = Mock() + reader._read_from_definition_body = Mock() + reader._read_from_definition_body.return_value = expected + + actual = reader.read() + self.assertEquals(actual, expected) + + reader._read_from_definition_body.assert_called_with() + reader._download_swagger.assert_not_called() + + def test_read_from_definition_uri(self): + uri = "./file.txt" + expected = {"some": "value"} + + reader = SamSwaggerReader(definition_uri=uri) + reader._download_swagger = Mock() + reader._download_swagger.return_value = expected + + actual = reader.read() + self.assertEquals(actual, expected) + + reader._download_swagger.assert_called_with(uri) + + def test_must_use_definition_uri_if_body_does_not_exist(self): + body = {"this is": "swagger"} + uri = "./file.txt" + expected = {"some": "value"} + + reader = SamSwaggerReader(definition_body=body, definition_uri=uri) + reader._download_swagger = Mock() + reader._download_swagger.return_value = expected + + # Set the output of reading the definition body to be None + reader._read_from_definition_body = Mock() + reader._read_from_definition_body.return_value = None + + actual = reader.read() + self.assertEquals(actual, expected) + + reader._read_from_definition_body.assert_called_with() + reader._download_swagger.assert_called_with(uri) + + +class TestSamSwaggerReader_read_from_definition_body(TestCase): + + @patch("samcli.commands.local.lib.swagger.reader.parse_aws_include_transform") + def test_must_work_with_include_transform(self, parse_mock): + body = {'this': 'swagger'} + expected = {'k': 'v'} + location = "some location" + + reader = SamSwaggerReader(definition_body=body) + reader._download_swagger = Mock() + reader._download_swagger.return_value = expected + parse_mock.return_value = location + + actual = reader._read_from_definition_body() + self.assertEquals(actual, expected) + parse_mock.assert_called_with(body) + + @patch("samcli.commands.local.lib.swagger.reader.parse_aws_include_transform") + def test_must_get_body_directly(self, parse_mock): + body = {'this': 'swagger'} + + reader = SamSwaggerReader(definition_body=body) + parse_mock.return_value = None # No location is returned from aws_include parser + + actual = reader._read_from_definition_body() + self.assertEquals(actual, body) + + +class TestSamSwaggerReader_download_swagger(TestCase): + + @patch("samcli.commands.local.lib.swagger.reader.yaml_parse") + def test_must_download_from_s3_for_s3_locations(self, yaml_parse_mock): + location = { + "Bucket": "mybucket", + "Key": "swagger.yaml", + "Version": "versionId" + } + swagger_str = "some swagger str" + expected = "some data" + + reader = SamSwaggerReader(definition_uri=location) + reader._download_from_s3 = Mock() + reader._download_from_s3.return_value = swagger_str + yaml_parse_mock.return_value = expected + + actual = reader._download_swagger(location) + + self.assertEquals(actual, expected) + reader._download_from_s3.assert_called_with(location["Bucket"], + location["Key"], + location["Version"]) + yaml_parse_mock.assert_called_with(swagger_str) + + @patch("samcli.commands.local.lib.swagger.reader.yaml_parse") + def test_must_skip_non_s3_dictionaries(self, yaml_parse_mock): + + location = {"some": "value"} + + reader = SamSwaggerReader(definition_uri=location) + reader._download_from_s3 = Mock() + + actual = reader._download_swagger(location) + + self.assertIsNone(actual) + reader._download_from_s3.assert_not_called() + yaml_parse_mock.assert_not_called() + + @patch("samcli.commands.local.lib.swagger.reader.yaml_parse") + def test_must_read_from_local_file(self, yaml_parse_mock): + data = {"some": "value"} + expected = "parsed result" + yaml_parse_mock.return_value = expected + + with tempfile.NamedTemporaryFile() as fp: + filepath = fp.name + + json.dump(data, fp) + fp.flush() + + cwd = os.path.dirname(filepath) + filename = os.path.basename(filepath) + + reader = SamSwaggerReader(definition_uri=filename, working_dir=cwd) + actual = reader._download_swagger(filename) + + self.assertEquals(actual, expected) + yaml_parse_mock.assert_called_with('{"some": "value"}') # data was read back from the file as JSON string + + @patch("samcli.commands.local.lib.swagger.reader.yaml_parse") + def test_must_read_from_local_file_without_working_directory(self, yaml_parse_mock): + data = {"some": "value"} + expected = "parsed result" + yaml_parse_mock.return_value = expected + + with tempfile.NamedTemporaryFile() as fp: + filepath = fp.name + + json.dump(data, fp) + fp.flush() + + reader = SamSwaggerReader(definition_uri=filepath) + actual = reader._download_swagger(filepath) + + self.assertEquals(actual, expected) + yaml_parse_mock.assert_called_with('{"some": "value"}') # data was read back from the file as JSON string + + @patch("samcli.commands.local.lib.swagger.reader.yaml_parse") + def test_must_return_none_if_file_not_found(self, yaml_parse_mock): + expected = "parsed result" + yaml_parse_mock.return_value = expected + + reader = SamSwaggerReader(definition_uri="somepath") + actual = reader._download_swagger("abcdefgh.txt") + + self.assertIsNone(actual) + yaml_parse_mock.assert_not_called() + + def test_with_invalid_location(self): + + reader = SamSwaggerReader(definition_uri="something") + actual = reader._download_swagger({}) + + self.assertIsNone(actual) + + +class TestSamSwaggerReaderDownloadFromS3(TestCase): + + def setUp(self): + self.bucket = "mybucket" + self.key = "mykey" + self.version = "versionid" + + @patch('samcli.commands.local.lib.swagger.reader.boto3') + @patch('samcli.commands.local.lib.swagger.reader.tempfile') + def test_must_download_file_from_s3(self, tempfilemock, botomock): + + s3_mock = Mock() + botomock.client.return_value = s3_mock + + fp_mock = Mock() + tempfilemock.TemporaryFile.return_value.__enter__.return_value = fp_mock # mocking context manager + + expected = "data from file" + fp_mock.read.return_value = expected + + actual = SamSwaggerReader._download_from_s3(self.bucket, self.key, self.version) + self.assertEquals(actual, expected) + + s3_mock.download_file.assert_called_with(self.bucket, self.key, fp_mock, + ExtraArgs={"VersionId": self.version}) + + fp_mock.seek.assert_called_with(0) # make sure we seek the file before reading + fp_mock.read.assert_called_with() + + @patch('samcli.commands.local.lib.swagger.reader.boto3') + @patch('samcli.commands.local.lib.swagger.reader.tempfile') + def test_must_work_without_object_version_id(self, tempfilemock, botomock): + + s3_mock = Mock() + botomock.client.return_value = s3_mock + + fp_mock = Mock() + tempfilemock.TemporaryFile.return_value.__enter__.return_value = fp_mock # mocking context manager + + expected = "data from file" + fp_mock.read.return_value = expected + + actual = SamSwaggerReader._download_from_s3(self.bucket, self.key) + self.assertEquals(actual, expected) + + s3_mock.download_file.assert_called_with(self.bucket, self.key, fp_mock, + ExtraArgs={}) + + @patch('samcli.commands.local.lib.swagger.reader.boto3') + @patch('samcli.commands.local.lib.swagger.reader.tempfile') + def test_must_log_on_download_exception(self, tempfilemock, botomock): + + s3_mock = Mock() + botomock.client.return_value = s3_mock + + fp_mock = Mock() + tempfilemock.TemporaryFile.return_value.__enter__.return_value = fp_mock # mocking context manager + s3_mock.download_file.side_effect = botocore.exceptions.ClientError({"Error": {}}, + "download_file") + + with self.assertRaises(botocore.exceptions.ClientError): + SamSwaggerReader._download_from_s3(self.bucket, self.key) + + fp_mock.read.assert_not_called() + + +class TestSamSwaggerReader_parse_s3_location(TestCase): + + def setUp(self): + self.bucket = "mybucket" + self.key = "mykey" + self.version = "myversion" + + def test_must_parse_valid_dict(self): + location = { + "Bucket": self.bucket, + "Key": self.key, + "Version": self.version + } + + result = SamSwaggerReader._parse_s3_location(location) + self.assertEquals(result, (self.bucket, self.key, self.version)) + + def test_must_parse_dict_without_version(self): + location = { + "Bucket": self.bucket, + "Key": self.key + } + + result = SamSwaggerReader._parse_s3_location(location) + self.assertEquals(result, (self.bucket, self.key, None)) + + def test_must_parse_s3_uri_string(self): + location = "s3://{}/{}?versionId={}".format(self.bucket, self.key, self.version) + + result = SamSwaggerReader._parse_s3_location(location) + self.assertEquals(result, (self.bucket, self.key, self.version)) + + def test_must_parse_s3_uri_string_without_version_id(self): + location = "s3://{}/{}".format(self.bucket, self.key) + + result = SamSwaggerReader._parse_s3_location(location) + self.assertEquals(result, (self.bucket, self.key, None)) + + @parameterized.expand([ + param("http://s3.amazonaws.com/bucket/key"), + param("./foo/bar.txt"), + param("/home/user/bar.txt"), + param({"k": "v"}), + ]) + def test_must_parse_invalid_location(self, location): + + result = SamSwaggerReader._parse_s3_location(location) + self.assertEquals(result, (None, None, None)) diff --git a/tests/unit/commands/local/lib/test_events.py b/tests/unit/commands/local/lib/test_events.py new file mode 100644 index 0000000000..825d2b5f14 --- /dev/null +++ b/tests/unit/commands/local/lib/test_events.py @@ -0,0 +1,285 @@ +from unittest import TestCase + +from samcli.commands.local.lib.events import generate_api_event, generate_dynamodb_event, generate_kinesis_event, \ + generate_schedule_event, generate_sns_event, generate_s3_event + + +class TestGeneratedEvent(TestCase): + + def test_s3_event(self): + actual_event = generate_s3_event("us-east-1", "bucket", "key") + + expected_event = { + "Records": [{ + "eventVersion": "2.0", + "eventTime": "1970-01-01T00:00:00.000Z", + "requestParameters": { + "sourceIPAddress": "127.0.0.1" + }, + "s3": { + "configurationId": "testConfigRule", + "object": { + "eTag": "0123456789abcdef0123456789abcdef", + "sequencer": "0A1B2C3D4E5F678901", + "key": "key", + "size": 1024 + }, + "bucket": { + "arn": "arn:aws:s3:::bucket", + "name": "bucket", + "ownerIdentity": { + "principalId": "EXAMPLE" + } + }, + "s3SchemaVersion": "1.0" + }, + "responseElements": { + "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH", + "x-amz-request-id": "EXAMPLE123456789" + }, + "awsRegion": "us-east-1", + "eventName": "ObjectCreated:Put", + "userIdentity": { + "principalId": "EXAMPLE" + }, + "eventSource": "aws:s3" + }] + } + + self.assertEquals(actual_event, expected_event) + + def test_sns_event(self): + actual_event = generate_sns_event("message", "topic", "subject") + + expected_event = { + "Records": [{ + "EventVersion": "1.0", + "EventSubscriptionArn": "arn:aws:sns:EXAMPLE", + "EventSource": "aws:sns", + "Sns": { + "SignatureVersion": "1", + "Timestamp": "1970-01-01T00:00:00.000Z", + "Signature": "EXAMPLE", + "SigningCertUrl": "EXAMPLE", + "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e", + "Message": "message", + "MessageAttributes": { + "Test": { + "Type": "String", + "Value": "TestString" + }, + "TestBinary": { + "Type": "Binary", + "Value": "TestBinary" + } + }, + "Type": "Notification", + "UnsubscribeUrl": "EXAMPLE", + "TopicArn": "topic", + "Subject": "subject" + } + }] + } + + self.assertEquals(actual_event, expected_event) + + def test_api_event(self): + actual_event = generate_api_event("GET", "body of the request", "/path", "/path") + self.maxDiff = None + + expected_event = { + 'body': 'body of the request', + 'headers': { + 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', + 'Accept-Encoding': 'gzip, deflate, sdch', + 'Accept-Language': 'en-US,en;q=0.8', + 'Cache-Control': 'max-age=0', + 'CloudFront-Forwarded-Proto': 'https', + 'CloudFront-Is-Desktop-Viewer': 'true', + 'CloudFront-Is-Mobile-Viewer': 'false', + 'CloudFront-Is-SmartTV-Viewer': 'false', + 'CloudFront-Is-Tablet-Viewer': 'false', + 'CloudFront-Viewer-Country': 'US', + 'Host': '1234567890.execute-api.us-east-1.amazonaws.com', + 'Upgrade-Insecure-Requests': '1', + 'User-Agent': 'Custom User Agent String', + 'Via': '1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)', + 'X-Amz-Cf-Id': 'aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==', + 'X-Forwarded-For': '127.0.0.1, 127.0.0.2', + 'X-Forwarded-Port': '443', + 'X-Forwarded-Proto': 'https' + }, + 'httpMethod': 'GET', + 'isBase64Encoded': False, + 'path': '/path', + 'pathParameters': {'proxy': '/path'}, + 'queryStringParameters': {'foo': 'bar'}, + 'requestContext': { + 'accountId': "123456789012", + 'apiId': "1234567890", + 'extendedRequestId': None, + 'httpMethod': 'GET', + 'identity': { + 'accountId': None, + 'apiKey': None, + 'caller': None, + 'cognitoAuthenticationProvider': None, + 'cognitoAuthenticationType': None, + 'cognitoIdentityPoolId': None, + 'sourceIp': '127.0.0.1', + 'user': None, + 'userAgent': "Custom User Agent String", + 'userArn': None + }, + 'path': '/path', + 'requestId': "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + 'resourceId': "123456", + 'resourcePath': '/path', + 'stage': 'prod' + }, + 'resource': '/path', + 'stageVariables': None + } + + self.assertEquals(actual_event, expected_event) + + def test_dynamodb_event(self): + actual_event = generate_dynamodb_event("us-east-1") + + expected_event = { + "Records": [ + { + "eventID": "1", + "eventVersion": "1.0", + "dynamodb": { + "Keys": { + "Id": { + "N": "101" + } + }, + "NewImage": { + "Message": { + "S": "New item!" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES", + "SequenceNumber": "111", + "SizeBytes": 26 + }, + "awsRegion": "us-east-1", + "eventName": "INSERT", + "eventSourceARN": "arn:aws:dynamodb:us-east-1:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899", + "eventSource": "aws:dynamodb" + }, + { + "eventID": "2", + "eventVersion": "1.0", + "dynamodb": { + "OldImage": { + "Message": { + "S": "New item!" + }, + "Id": { + "N": "101" + } + }, + "SequenceNumber": "222", + "Keys": { + "Id": { + "N": "101" + } + }, + "SizeBytes": 59, + "NewImage": { + "Message": { + "S": "This item has changed" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES" + }, + "awsRegion": "us-east-1", + "eventName": "MODIFY", + "eventSourceARN": "arn:aws:dynamodb:us-east-1:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899", + "eventSource": "aws:dynamodb" + }, + { + "eventID": "3", + "eventVersion": "1.0", + "dynamodb": { + "Keys": { + "Id": { + "N": "101" + } + }, + "SizeBytes": 38, + "SequenceNumber": "333", + "OldImage": { + "Message": { + "S": "This item has changed" + }, + "Id": { + "N": "101" + } + }, + "StreamViewType": "NEW_AND_OLD_IMAGES" + }, + "awsRegion": "us-east-1", + "eventName": "REMOVE", + "eventSourceARN": "arn:aws:dynamodb:us-east-1:account-id:table/" + "ExampleTableWithStream/stream/2015-06-27T00:48:05.899", + "eventSource": "aws:dynamodb" + } + ] + } + + self.assertEquals(actual_event, expected_event) + + def test_scheudle_event(self): + actual_event = generate_schedule_event("us-east-1") + + expected_event = { + "account": "123456789012", + "region": "us-east-1", + "detail": {}, + "detail-type": "Scheduled Event", + "source": "aws.events", + "time": "1970-01-01T00:00:00Z", + "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c", + "resources": [ + "arn:aws:events:us-east-1:123456789012:rule/my-schedule" + ] + } + + self.assertEquals(actual_event, expected_event) + + def test_kinesis_event(self): + actual_event = generate_kinesis_event("us-east-1", "partition", "sequence", "this is data") + + expected_event = { + "Records": [{ + "eventID": "shardId-000000000000:sequence", + "eventVersion": "1.0", + "kinesis": { + "approximateArrivalTimestamp": 1428537600, + "partitionKey": "partition", + "data": "this is data", + "kinesisSchemaVersion": "1.0", + "sequenceNumber": "sequence" + }, + "invokeIdentityArn": "arn:aws:iam::EXAMPLE", + "eventName": "aws:kinesis:record", + "eventSourceARN": "arn:aws:kinesis:EXAMPLE", + "eventSource": "aws:kinesis", + "awsRegion": "us-east-1" + }] + } + + self.assertEquals(actual_event, expected_event) diff --git a/tests/unit/commands/local/lib/test_local_api_service.py b/tests/unit/commands/local/lib/test_local_api_service.py new file mode 100644 index 0000000000..aee6f7f4fa --- /dev/null +++ b/tests/unit/commands/local/lib/test_local_api_service.py @@ -0,0 +1,181 @@ +""" +Unit test for local API service +""" + +from unittest import TestCase +from mock import Mock, patch + +from samcli.commands.local.lib.local_api_service import LocalApiService +from samcli.commands.local.lib.exceptions import NoApisDefined +from samcli.commands.local.lib.provider import Api +from samcli.local.apigw.service import Route + + +class TestLocalApiService_start(TestCase): + + def setUp(self): + self.port = 123 + self.host = "abc" + self.static_dir = "static" + self.cwd = "cwd" + self.template = {"hello": "world"} + + self.lambda_invoke_context_mock = Mock() + self.lambda_runner_mock = Mock() + self.api_provider_mock = Mock() + self.apigw_service = Mock() + self.stderr_mock = Mock() + + self.lambda_invoke_context_mock.template = self.template + self.lambda_invoke_context_mock.local_lambda_runner = self.lambda_runner_mock + self.lambda_invoke_context_mock.get_cwd = Mock() + self.lambda_invoke_context_mock.get_cwd.return_value = self.cwd + self.lambda_invoke_context_mock.stderr = self.stderr_mock + + @patch("samcli.commands.local.lib.local_api_service.Service") + @patch("samcli.commands.local.lib.local_api_service.SamApiProvider") + @patch.object(LocalApiService, "_make_static_dir_path") + @patch.object(LocalApiService, "_print_routes") + @patch.object(LocalApiService, "_make_routing_list") + def test_must_start_service(self, + make_routing_list_mock, + log_routes_mock, + make_static_dir_mock, + SamApiProviderMock, + ApiGwServiceMock): + + routing_list = [1, 2, 3] # something + static_dir_path = "/foo/bar" + + make_routing_list_mock.return_value = routing_list + make_static_dir_mock.return_value = static_dir_path + + SamApiProviderMock.return_value = self.api_provider_mock + ApiGwServiceMock.return_value = self.apigw_service + + # Now start the service + local_service = LocalApiService(self.lambda_invoke_context_mock, self.port, self.host, self.static_dir) + local_service.start() + + # Make sure the right methods are called + SamApiProviderMock.assert_called_with(self.template, cwd=self.cwd) + + make_routing_list_mock.assert_called_with(self.api_provider_mock) + log_routes_mock.assert_called_with(self.api_provider_mock, self.host, self.port) + make_static_dir_mock.assert_called_with(self.cwd, self.static_dir) + ApiGwServiceMock.assert_called_with(routing_list=routing_list, + lambda_runner=self.lambda_runner_mock, + static_dir=static_dir_path, + port=self.port, + host=self.host, + stderr=self.stderr_mock) + + self.apigw_service.create.assert_called_with() + self.apigw_service.run.assert_called_with() + + @patch("samcli.commands.local.lib.local_api_service.Service") + @patch("samcli.commands.local.lib.local_api_service.SamApiProvider") + @patch.object(LocalApiService, "_make_static_dir_path") + @patch.object(LocalApiService, "_print_routes") + @patch.object(LocalApiService, "_make_routing_list") + def test_must_raise_if_route_not_available(self, + make_routing_list_mock, + log_routes_mock, + make_static_dir_mock, + SamApiProviderMock, + ApiGwServiceMock): + + routing_list = [] # Empty + + make_routing_list_mock.return_value = routing_list + + SamApiProviderMock.return_value = self.api_provider_mock + ApiGwServiceMock.return_value = self.apigw_service + + # Now start the service + local_service = LocalApiService(self.lambda_invoke_context_mock, self.port, self.host, self.static_dir) + + with self.assertRaises(NoApisDefined): + local_service.start() + + +class TestLocalApiService_make_routing_list(TestCase): + + def test_must_return_routing_list_from_apis(self): + api_provider = Mock() + apis = [ + Api(path="/1", method="GET1", function_name="name1", cors="CORS1"), + Api(path="/2", method="GET2", function_name="name2", cors="CORS2"), + Api(path="/3", method="GET3", function_name="name3", cors="CORS3"), + ] + expected = [ + Route(path="/1", methods=["GET1"], function_name="name1"), + Route(path="/2", methods=["GET2"], function_name="name2"), + Route(path="/3", methods=["GET3"], function_name="name3") + ] + + api_provider.get_all.return_value = apis + + result = LocalApiService._make_routing_list(api_provider) + self.assertEquals(len(result), len(expected)) + for index, r in enumerate(result): + self.assertEquals(r.__dict__, expected[index].__dict__) + + +class TestLocalApiService_print_routes(TestCase): + + def test_must_print_routes(self): + host = "host" + port = 123 + + api_provider = Mock() + apis = [ + Api(path="/1", method="GET", function_name="name1", cors="CORS1"), + Api(path="/1", method="POST", function_name="name1", cors="CORS1"), + Api(path="/1", method="DELETE", function_name="othername1", cors="CORS1"), + Api(path="/2", method="GET2", function_name="name2", cors="CORS2"), + Api(path="/3", method="GET3", function_name="name3", cors="CORS3"), + ] + api_provider.get_all.return_value = apis + + expected = {"Mounting name1 at http://host:123/1 [GET, POST]", + "Mounting othername1 at http://host:123/1 [DELETE]", + "Mounting name2 at http://host:123/2 [GET2]", + "Mounting name3 at http://host:123/3 [GET3]"} + + actual = LocalApiService._print_routes(api_provider, host, port) + self.assertEquals(expected, set(actual)) + + +class TestLocalApiService_make_static_dir_path(TestCase): + + def test_must_skip_if_none(self): + result = LocalApiService._make_static_dir_path("something", None) + self.assertIsNone(result) + + @patch("samcli.commands.local.lib.local_api_service.os") + def test_must_resolve_with_respect_to_cwd(self, os_mock): + static_dir = "mydir" + cwd = "cwd" + resolved_path = "cwd/mydir" + + os_mock.path.join.return_value = resolved_path + os_mock.path.exists.return_value = True # Fake the path to exist + + result = LocalApiService._make_static_dir_path(cwd, static_dir) + self.assertEquals(resolved_path, result) + + os_mock.path.join.assert_called_with(cwd, static_dir) + os_mock.path.exists.assert_called_with(resolved_path) + + @patch("samcli.commands.local.lib.local_api_service.os") + def test_must_return_none_if_path_not_exists(self, os_mock): + static_dir = "mydir" + cwd = "cwd" + resolved_path = "cwd/mydir" + + os_mock.path.join.return_value = resolved_path + os_mock.path.exists.return_value = False # Resolved path does not exist + + result = LocalApiService._make_static_dir_path(cwd, static_dir) + self.assertIsNone(result) diff --git a/tests/unit/commands/local/lib/test_local_lambda.py b/tests/unit/commands/local/lib/test_local_lambda.py new file mode 100644 index 0000000000..812ce60daf --- /dev/null +++ b/tests/unit/commands/local/lib/test_local_lambda.py @@ -0,0 +1,496 @@ +""" +Testing local lambda runner +""" +import os + +from unittest import TestCase +from mock import Mock, patch +from parameterized import parameterized, param + +from samcli.commands.local.lib.local_lambda import LocalLambdaRunner +from samcli.commands.local.lib.provider import Function +from samcli.local.lambdafn.exceptions import FunctionNotFound + + +class TestLocalLambda_get_aws_creds(TestCase): + + def setUp(self): + self.region = "region" + self.key = "key" + self.secret = "secret" + self.token = "token" + + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "cwd" + self.env_vars_values = {} + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_get_from_boto_session(self, boto3_mock): + creds = Mock() + creds.access_key = self.key + creds.secret_key = self.secret + creds.token = self.token + + mock_session = Mock() + mock_session.region_name = self.region + + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = creds + + expected = { + "region": self.region, + "key": self.key, + "secret": self.secret, + "sessiontoken": self.token + } + + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_region_name(self, boto3_mock): + creds = Mock() + creds.access_key = self.key + creds.secret_key = self.secret + creds.token = self.token + + mock_session = Mock() + del mock_session.region_name # Ask mock to return AttributeError when 'region_name' is accessed + + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = creds + + expected = { + "key": self.key, + "secret": self.secret, + "sessiontoken": self.token + } + + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_access_key(self, boto3_mock): + creds = Mock() + del creds.access_key # No access key + creds.secret_key = self.secret + creds.token = self.token + + mock_session = Mock() + mock_session.region_name = self.region + + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = creds + + expected = { + "region": self.region, + "secret": self.secret, + "sessiontoken": self.token + } + + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_secret_key(self, boto3_mock): + creds = Mock() + creds.access_key = self.key + del creds.secret_key # No secret key + creds.token = self.token + + mock_session = Mock() + mock_session.region_name = self.region + + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = creds + + expected = { + "region": self.region, + "key": self.key, + "sessiontoken": self.token + } + + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_session_token(self, boto3_mock): + creds = Mock() + creds.access_key = self.key + creds.secret_key = self.secret + del creds.token # No Token + + mock_session = Mock() + mock_session.region_name = self.region + + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = creds + + expected = { + "region": self.region, + "key": self.key, + "secret": self.secret + } + + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_credentials(self, boto3_mock): + mock_session = Mock() + boto3_mock.session.Session.return_value = mock_session + mock_session.get_credentials.return_value = None + + expected = {} + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + @patch("samcli.commands.local.lib.local_lambda.boto3") + def test_must_work_with_no_session(self, boto3_mock): + boto3_mock.session.Session.return_value = None + + expected = {} + actual = self.local_lambda.get_aws_creds() + self.assertEquals(expected, actual) + + boto3_mock.session.Session.assert_called_with(profile_name=self.aws_profile) + + +class TestLocalLambda_get_code_path(TestCase): + + def setUp(self): + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "/my/current/working/directory" + self.env_vars_values = {} + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + + self.relative_codeuri = "./my/path" + self.absolute_codeuri = "/home/foo/bar" # Some absolute path to use + self.os_cwd = os.getcwd() + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + @parameterized.expand([ + ("."), + ("") + ]) + def test_must_resolve_present_cwd(self, cwd_path): + + self.local_lambda.cwd = cwd_path + codeuri = self.relative_codeuri + expected = os.path.normpath(os.path.join(self.os_cwd, codeuri)) + + actual = self.local_lambda._get_code_path(codeuri) + self.assertEquals(expected, actual) + self.assertTrue(os.path.isabs(actual), "Result must be an absolute path") + + @parameterized.expand([ + ("var/task"), + ("some/dir") + ]) + def test_must_resolve_relative_cwd(self, cwd_path): + + self.local_lambda.cwd = cwd_path + codeuri = self.relative_codeuri + + abs_cwd = os.path.abspath(cwd_path) + expected = os.path.normpath(os.path.join(abs_cwd, codeuri)) + + actual = self.local_lambda._get_code_path(codeuri) + self.assertEquals(expected, actual) + self.assertTrue(os.path.isabs(actual), "Result must be an absolute path") + + @parameterized.expand([ + (""), + ("."), + ("hello"), + ("a/b/c/d"), + ("../../c/d/e") + ]) + def test_must_resolve_relative_codeuri(self, codeuri): + + expected = os.path.normpath(os.path.join(self.cwd, codeuri)) + + actual = self.local_lambda._get_code_path(codeuri) + self.assertEquals(expected, actual) + self.assertTrue(os.path.isabs(actual), "Result must be an absolute path") + + @parameterized.expand([ + ("/a/b/c"), + ("/") + ]) + def test_must_resolve_absolute_codeuri(self, codeuri): + + expected = codeuri # CodeUri must be return as is for absolute paths + + actual = self.local_lambda._get_code_path(codeuri) + self.assertEquals(expected, actual) + self.assertTrue(os.path.isabs(actual), "Result must be an absolute path") + + +class TestLocalLambda_make_env_vars(TestCase): + + def setUp(self): + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "/my/current/working/directory" + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + self.env_vars_values = {} + + self.environ = { + "Variables": { + "var1": "value1", + } + } + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + self.aws_creds = {"key": "key"} + self.local_lambda.get_aws_creds = Mock() + self.local_lambda.get_aws_creds.return_value = self.aws_creds + + @parameterized.expand([ + # Override for the function exists + ({"function_name": {"a": "b"}}, {"a": "b"}), + + # Override for the function does *not* exist + ({"otherfunction": {"c": "d"}}, None), + + # Using a CloudFormation parameter file format + ({"Parameters": {"p1": "v1"}}, {"p1": "v1"}), + ]) + @patch("samcli.commands.local.lib.local_lambda.EnvironmentVariables") + @patch("samcli.commands.local.lib.local_lambda.os") + def test_must_work_with_override_values(self, env_vars_values, expected_override_value, os_mock, + EnvironmentVariablesMock): + os_environ = {"some": "value"} + os_mock.environ = os_environ + + function = Function(name="function_name", + runtime="runtime", + memory=1234, + timeout=12, + handler="handler", + codeuri="codeuri", + environment=self.environ, + rolearn=None) + + self.local_lambda.env_vars_values = env_vars_values + + self.local_lambda._make_env_vars(function) + + EnvironmentVariablesMock.assert_called_with(function.memory, + function.timeout, + function.handler, + variables={"var1": "value1"}, + shell_env_values=os_environ, + override_values=expected_override_value, + aws_creds=self.aws_creds) + + @parameterized.expand([ + param({"a": "b"}), # Does not have the "Variables" Key + param("somestring"), # Must be a dict type + param(None) + ]) + @patch("samcli.commands.local.lib.local_lambda.EnvironmentVariables") + @patch("samcli.commands.local.lib.local_lambda.os") + def test_must_work_with_invalid_environment_variable(self, environment_variable, os_mock, EnvironmentVariablesMock): + os_environ = {"some": "value"} + os_mock.environ = os_environ + + function = Function(name="function_name", + runtime="runtime", + memory=1234, + timeout=12, + handler="handler", + codeuri="codeuri", + environment=environment_variable, + rolearn=None) + + self.local_lambda.env_vars_values = {} + + self.local_lambda._make_env_vars(function) + + EnvironmentVariablesMock.assert_called_with(function.memory, + function.timeout, + function.handler, + variables=None, + shell_env_values=os_environ, + override_values=None, + aws_creds=self.aws_creds) + + +class TestLocalLambda_get_invoke_config(TestCase): + + def setUp(self): + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "/my/current/working/directory" + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + self.env_vars_values = {} + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + @patch('samcli.commands.local.lib.local_lambda.FunctionConfig') + def test_must_work(self, FunctionConfigMock): + env_vars = "envvars" + self.local_lambda._make_env_vars = Mock() + self.local_lambda._make_env_vars.return_value = env_vars + + codepath = "codepath" + self.local_lambda._get_code_path = Mock() + self.local_lambda._get_code_path.return_value = codepath + + function = Function(name="function_name", + runtime="runtime", + memory=1234, + timeout=12, + handler="handler", + codeuri="codeuri", + environment=None, + rolearn=None) + + config = "someconfig" + FunctionConfigMock.return_value = config + actual = self.local_lambda._get_invoke_config(function) + self.assertEquals(actual, config) + + FunctionConfigMock.assert_called_with(name=function.name, + runtime=function.runtime, + handler=function.handler, + code_abs_path=codepath, + memory=function.memory, + timeout=function.timeout, + env_vars=env_vars) + + self.local_lambda._get_code_path.assert_called_with(function.codeuri) + self.local_lambda._make_env_vars.assert_called_with(function) + + +class TestLocalLambda_invoke(TestCase): + + def setUp(self): + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "/my/current/working/directory" + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + self.env_vars_values = {} + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + def test_must_work(self): + name = "name" + event = "event" + stdout = "stdout" + stderr = "stderr" + function = Mock() + invoke_config = "config" + + self.function_provider_mock.get.return_value = function + self.local_lambda._get_invoke_config = Mock() + self.local_lambda._get_invoke_config.return_value = invoke_config + + self.local_lambda.invoke(name, event, stdout, stderr) + + self.runtime_mock.invoke.assert_called_with(invoke_config, event, + debug_port=self.debug_port, + debug_args=self.debug_args, + stdout=stdout, stderr=stderr) + + def test_must_raise_if_function_not_found(self): + + self.function_provider_mock.get.return_value = None # function not found + with self.assertRaises(FunctionNotFound): + self.local_lambda.invoke("name", "event") + + +class TestLocalLambda_is_debugging(TestCase): + + def setUp(self): + self.runtime_mock = Mock() + self.function_provider_mock = Mock() + self.cwd = "/my/current/working/directory" + self.debug_port = 123 + self.debug_args = "abc" + self.aws_profile = "myprofile" + self.env_vars_values = {} + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + self.debug_port, + self.debug_args, + self.aws_profile) + + def test_must_be_on(self): + self.assertTrue(self.local_lambda.is_debugging()) + + def test_must_be_off(self): + + self.local_lambda = LocalLambdaRunner(self.runtime_mock, + self.function_provider_mock, + self.cwd, + self.env_vars_values, + debug_port=None, # No debug port + debug_args=self.debug_args, + aws_profile=self.aws_profile) + + self.assertFalse(self.local_lambda.is_debugging()) diff --git a/tests/unit/commands/local/lib/test_sam_api_provider.py b/tests/unit/commands/local/lib/test_sam_api_provider.py new file mode 100644 index 0000000000..aeed24c236 --- /dev/null +++ b/tests/unit/commands/local/lib/test_sam_api_provider.py @@ -0,0 +1,1005 @@ +import tempfile +import json + +from unittest import TestCase +from mock import patch +from nose_parameterized import parameterized + +from samcli.commands.local.lib.sam_api_provider import SamApiProvider +from samcli.commands.local.lib.provider import Api +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + +import logging +logging.basicConfig(level=logging.INFO) + + +class TestSamApiProvider_init(TestCase): + + @patch.object(SamApiProvider, "_extract_apis") + @patch("samcli.commands.local.lib.sam_api_provider.SamBaseProvider") + def test_provider_with_valid_template(self, SamBaseProviderMock, extract_api_mock): + extract_api_mock.return_value = {"set", "of", "values"} + + template = {"Resources": {"a": "b"}} + SamBaseProviderMock.get_template.return_value = template + + provider = SamApiProvider(template) + + self.assertEquals(len(provider.apis), 3) + self.assertEquals(provider.apis, set(["set", "of", "values"])) + self.assertEquals(provider.template_dict, {"Resources": {"a": "b"}}) + self.assertEquals(provider.resources, {"a": "b"}) + + +class TestSamApiProviderWithImplicitApis(TestCase): + + def test_provider_with_no_resource_properties(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Lambda::Function" + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(len(provider.apis), 0) + self.assertEquals(provider.apis, []) + + @parameterized.expand([("GET"), ("get")]) + def test_provider_has_correct_api(self, method): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": method + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(len(provider.apis), 1) + self.assertEquals(list(provider.apis)[0], Api(path="/path", method="GET", function_name="SamFunc1", cors=None)) + + def test_provider_creates_api_for_all_events(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "GET" + } + }, + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "POST" + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + api_event1 = Api(path="/path", method="GET", function_name="SamFunc1", cors=None) + api_event2 = Api(path="/path", method="POST", function_name="SamFunc1", cors=None) + + self.assertIn(api_event1, provider.apis) + self.assertIn(api_event2, provider.apis) + self.assertEquals(len(provider.apis), 2) + + def test_provider_has_correct_template(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "GET" + } + } + } + } + }, + "SamFunc2": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "POST" + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + api1 = Api(path="/path", method="GET", function_name="SamFunc1", cors=None) + api2 = Api(path="/path", method="POST", function_name="SamFunc2", cors=None) + + self.assertIn(api1, provider.apis) + self.assertIn(api2, provider.apis) + + def test_provider_with_no_api_events(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "S3", + "Properties": { + "Property1": "value" + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(provider.apis, []) + + def test_provider_with_no_serverless_function(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Lambda::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(provider.apis, []) + + def test_provider_get_all(self): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "GET" + } + } + } + } + }, + "SamFunc2": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "POST" + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + result = [f for f in provider.get_all()] + + api1 = Api(path="/path", method="GET", function_name="SamFunc1") + api2 = Api(path="/path", method="POST", function_name="SamFunc2") + + self.assertIn(api1, result) + self.assertIn(api2, result) + + def test_provider_get_all_with_no_apis(self): + template = {} + + provider = SamApiProvider(template) + + result = [f for f in provider.get_all()] + + self.assertEquals(result, []) + + @parameterized.expand([("ANY"), ("any")]) + def test_provider_with_any_method(self, method): + template = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": method + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + api_get = Api(path="/path", method="GET", function_name="SamFunc1", cors=None) + api_post = Api(path="/path", method="POST", function_name="SamFunc1", cors=None) + api_put = Api(path="/path", method="PUT", function_name="SamFunc1", cors=None) + api_delete = Api(path="/path", method="DELETE", function_name="SamFunc1", cors=None) + api_patch = Api(path="/path", method="PATCH", function_name="SamFunc1", cors=None) + api_head = Api(path="/path", method="HEAD", function_name="SamFunc1", cors=None) + api_options = Api(path="/path", method="OPTIONS", function_name="SamFunc1", cors=None) + + self.assertEquals(len(provider.apis), 7) + self.assertIn(api_get, provider.apis) + self.assertIn(api_post, provider.apis) + self.assertIn(api_put, provider.apis) + self.assertIn(api_delete, provider.apis) + self.assertIn(api_patch, provider.apis) + self.assertIn(api_head, provider.apis) + self.assertIn(api_options, provider.apis) + + def test_provider_must_support_binary_media_types(self): + template = { + "Globals": { + "Api": { + "BinaryMediaTypes": [ + "image~1gif", + "image~1png", + "image~1png", # Duplicates must be ignored + {"Ref": "SomeParameter"} # Refs are ignored as well + ] + } + }, + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "get" + } + } + } + } + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(len(provider.apis), 1) + self.assertEquals(list(provider.apis)[0], Api(path="/path", method="GET", function_name="SamFunc1", + binary_media_types=["image/gif", "image/png"], cors=None)) + + def test_provider_must_support_binary_media_types_with_any_method(self): + template = { + "Globals": { + "Api": { + "BinaryMediaTypes": [ + "image~1gif", + "image~1png", + "text/html" + ] + } + }, + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler", + "Events": { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path", + "Method": "any" + } + } + } + } + } + } + } + + binary = ["image/gif", "image/png", "text/html"] + + expected_apis = [ + Api(path="/path", method="GET", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="POST", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="PUT", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="DELETE", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="HEAD", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="OPTIONS", function_name="SamFunc1", binary_media_types=binary), + Api(path="/path", method="PATCH", function_name="SamFunc1", binary_media_types=binary) + ] + + provider = SamApiProvider(template) + + self.assertItemsEqual(provider.apis, expected_apis) + + def test_convert_event_api_with_invalid_event_properties(self): + properties = { + "Path": "/foo", + "Method": "get", + "RestApiId": { + # This is not supported. Only Ref is supported + "Fn::Sub": "foo" + } + } + + with self.assertRaises(InvalidSamDocumentException): + SamApiProvider._convert_event_api("logicalId", properties) + + +class TestSamApiProviderWithExplicitApis(TestCase): + + def setUp(self): + self.binary_types = ["image/png", "image/jpg"] + self.input_apis = [ + Api(path="/path1", method="GET", function_name="SamFunc1", cors=None), + Api(path="/path1", method="POST", function_name="SamFunc1", cors=None), + + Api(path="/path2", method="PUT", function_name="SamFunc1", cors=None), + Api(path="/path2", method="GET", function_name="SamFunc1", cors=None), + + Api(path="/path3", method="DELETE", function_name="SamFunc1", cors=None) + ] + + def test_with_no_apis(self): + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod" + } + } + } + } + + provider = SamApiProvider(template) + + self.assertEquals(len(provider.apis), 0) + self.assertEquals(provider.apis, []) + + def test_with_inline_swagger_apis(self): + + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionBody": make_swagger(self.input_apis) + } + } + } + } + + provider = SamApiProvider(template) + self.assertItemsEqual(self.input_apis, provider.apis) + + def test_with_swagger_as_local_file(self): + + with tempfile.NamedTemporaryFile() as fp: + filename = fp.name + + swagger = make_swagger(self.input_apis) + json.dump(swagger, fp) + fp.flush() + + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionUri": filename + } + } + } + } + + provider = SamApiProvider(template) + self.assertItemsEqual(self.input_apis, provider.apis) + + @patch("samcli.commands.local.lib.sam_api_provider.SamSwaggerReader") + def test_with_swagger_as_both_body_and_uri(self, SamSwaggerReaderMock): + + body = {"some": "body"} + filename = "somefile.txt" + + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionUri": filename, + "DefinitionBody": body + } + } + } + } + + SamSwaggerReaderMock.return_value.read.return_value = make_swagger(self.input_apis) + + cwd = "foo" + provider = SamApiProvider(template, cwd=cwd) + self.assertItemsEqual(self.input_apis, provider.apis) + SamSwaggerReaderMock.assert_called_with(definition_body=body, definition_uri=filename, working_dir=cwd) + + def test_swagger_with_any_method(self): + + apis = [ + Api(path="/path", method="any", function_name="SamFunc1", cors=None) + ] + + expected_apis = [ + Api(path="/path", method="GET", function_name="SamFunc1", cors=None), + Api(path="/path", method="POST", function_name="SamFunc1", cors=None), + Api(path="/path", method="PUT", function_name="SamFunc1", cors=None), + Api(path="/path", method="DELETE", function_name="SamFunc1", cors=None), + Api(path="/path", method="HEAD", function_name="SamFunc1", cors=None), + Api(path="/path", method="OPTIONS", function_name="SamFunc1", cors=None), + Api(path="/path", method="PATCH", function_name="SamFunc1", cors=None) + ] + + template = { + "Resources": { + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionBody": make_swagger(apis) + } + } + } + } + + provider = SamApiProvider(template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_with_binary_media_types(self): + + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionBody": make_swagger(self.input_apis, binary_media_types=self.binary_types) + } + } + } + } + + expected_binary_types = sorted(self.binary_types) + expected_apis = [ + Api(path="/path1", method="GET", function_name="SamFunc1", cors=None, + binary_media_types=expected_binary_types), + Api(path="/path1", method="POST", function_name="SamFunc1", cors=None, + binary_media_types=expected_binary_types), + + Api(path="/path2", method="PUT", function_name="SamFunc1", cors=None, + binary_media_types=expected_binary_types), + Api(path="/path2", method="GET", function_name="SamFunc1", cors=None, + binary_media_types=expected_binary_types), + + Api(path="/path3", method="DELETE", function_name="SamFunc1", cors=None, + binary_media_types=expected_binary_types) + ] + + provider = SamApiProvider(template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_with_binary_media_types_in_swagger_and_on_resource(self): + + input_apis = [ + Api(path="/path", method="OPTIONS", function_name="SamFunc1"), + ] + extra_binary_types = ["text/html"] + + template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "BinaryMediaTypes": extra_binary_types, + "StageName": "Prod", + "DefinitionBody": make_swagger(input_apis, binary_media_types=self.binary_types) + } + } + } + } + + expected_binary_types = sorted(self.binary_types + extra_binary_types) + expected_apis = [ + Api(path="/path", method="OPTIONS", function_name="SamFunc1", binary_media_types=expected_binary_types), + ] + + provider = SamApiProvider(template) + self.assertItemsEqual(expected_apis, provider.apis) + + +class TestSamApiProviderWithExplicitAndImplicitApis(TestCase): + + def setUp(self): + self.explicit_apis = [ + Api(path="/path1", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path2", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path3", method="GET", function_name="explicitfunction", cors=None) + ] + + self.swagger = make_swagger(self.explicit_apis) + + self.template = { + "Resources": { + + "Api1": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + } + }, + + "ImplicitFunc": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + } + } + } + + def test_must_union_implicit_and_explicit(self): + + events = { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/path1", + "Method": "POST" + } + }, + + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/path2", + "Method": "POST" + } + }, + + "Event3": { + "Type": "Api", + "Properties": { + "Path": "/path3", + "Method": "POST" + } + } + } + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = self.swagger + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = events + + expected_apis = [ + # From Explicit APIs + Api(path="/path1", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path2", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path3", method="GET", function_name="explicitfunction", cors=None), + # From Implicit APIs + Api(path="/path1", method="POST", function_name="ImplicitFunc", cors=None), + Api(path="/path2", method="POST", function_name="ImplicitFunc", cors=None), + Api(path="/path3", method="POST", function_name="ImplicitFunc", cors=None) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_must_prefer_implicit_api_over_explicit(self): + + implicit_apis = { + "Event1": { + "Type": "Api", + "Properties": { + # This API is duplicated between implicit & explicit + "Path": "/path1", + "Method": "get" + } + }, + + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/path2", + "Method": "POST" + } + } + } + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = self.swagger + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = implicit_apis + + expected_apis = [ + Api(path="/path1", method="GET", function_name="ImplicitFunc", cors=None), # Comes from Implicit + + Api(path="/path2", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path2", method="POST", function_name="ImplicitFunc", cors=None), # Comes from implicit + + Api(path="/path3", method="GET", function_name="explicitfunction", cors=None), + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_must_prefer_implicit_with_any_method(self): + + implicit_apis = { + "Event1": { + "Type": "Api", + "Properties": { + # This API is duplicated between implicit & explicit + "Path": "/path", + "Method": "ANY" + } + } + } + + explicit_apis = [ + # Explicit should be over masked completely by implicit, because of "ANY" + Api(path="/path", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path", method="DELETE", function_name="explicitfunction", cors=None), + ] + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = make_swagger(explicit_apis) + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = implicit_apis + + expected_apis = [ + Api(path="/path", method="GET", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="POST", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="PUT", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="DELETE", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="HEAD", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="OPTIONS", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="PATCH", function_name="ImplicitFunc", cors=None) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_with_any_method_on_both(self): + + implicit_apis = { + "Event1": { + "Type": "Api", + "Properties": { + # This API is duplicated between implicit & explicit + "Path": "/path", + "Method": "ANY" + } + }, + "Event2": { + "Type": "Api", + "Properties": { + # This API is duplicated between implicit & explicit + "Path": "/path2", + "Method": "GET" + } + } + } + + explicit_apis = [ + # Explicit should be over masked completely by implicit, because of "ANY" + Api(path="/path", method="ANY", function_name="explicitfunction", cors=None), + Api(path="/path2", method="POST", function_name="explicitfunction", cors=None), + ] + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = make_swagger(explicit_apis) + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = implicit_apis + + expected_apis = [ + Api(path="/path", method="GET", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="POST", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="PUT", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="DELETE", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="HEAD", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="OPTIONS", function_name="ImplicitFunc", cors=None), + Api(path="/path", method="PATCH", function_name="ImplicitFunc", cors=None), + + Api(path="/path2", method="GET", function_name="ImplicitFunc", cors=None), + Api(path="/path2", method="POST", function_name="explicitfunction", cors=None) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_must_add_explicit_api_when_ref_with_rest_api_id(self): + + events = { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/newpath1", + "Method": "POST", + "RestApiId": "Api1" # This path must get added to this API + } + }, + + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/newpath2", + "Method": "POST", + "RestApiId": {"Ref": "Api1"} # This path must get added to this API + } + } + } + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = self.swagger + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = events + + expected_apis = [ + # From Explicit APIs + Api(path="/path1", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path2", method="GET", function_name="explicitfunction", cors=None), + Api(path="/path3", method="GET", function_name="explicitfunction", cors=None), + # From Implicit APIs + Api(path="/newpath1", method="POST", function_name="ImplicitFunc", cors=None), + Api(path="/newpath2", method="POST", function_name="ImplicitFunc", cors=None) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_both_apis_must_get_binary_media_types(self): + + events = { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/newpath1", + "Method": "POST" + } + }, + + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/newpath2", + "Method": "POST" + } + } + } + + # Binary type for implicit + self.template["Globals"] = { + "Api": { + "BinaryMediaTypes": ["image~1gif", "image~1png"] + } + } + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = events + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = self.swagger + # Binary type for explicit + self.template["Resources"]["Api1"]["Properties"]["BinaryMediaTypes"] = ["explicit/type1", "explicit/type2"] + + # Because of Globals, binary types will be concatenated on the explicit API + expected_explicit_binary_types = ["explicit/type1", "explicit/type2", "image/gif", "image/png"] + expected_implicit_binary_types = ["image/gif", "image/png"] + + expected_apis = [ + # From Explicit APIs + Api(path="/path1", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + Api(path="/path2", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + Api(path="/path3", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + # From Implicit APIs + Api(path="/newpath1", method="POST", function_name="ImplicitFunc", + binary_media_types=expected_implicit_binary_types), + Api(path="/newpath2", method="POST", function_name="ImplicitFunc", + binary_media_types=expected_implicit_binary_types) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + def test_binary_media_types_with_rest_api_id_reference(self): + + events = { + "Event1": { + "Type": "Api", + "Properties": { + "Path": "/connected-to-explicit-path", + "Method": "POST", + "RestApiId": "Api1" + } + }, + + "Event2": { + "Type": "Api", + "Properties": { + "Path": "/true-implicit-path", + "Method": "POST" + } + } + } + + # Binary type for implicit + self.template["Globals"] = { + "Api": { + "BinaryMediaTypes": ["image~1gif", "image~1png"] + } + } + self.template["Resources"]["ImplicitFunc"]["Properties"]["Events"] = events + + self.template["Resources"]["Api1"]["Properties"]["DefinitionBody"] = self.swagger + # Binary type for explicit + self.template["Resources"]["Api1"]["Properties"]["BinaryMediaTypes"] = ["explicit/type1", "explicit/type2"] + + # Because of Globals, binary types will be concatenated on the explicit API + expected_explicit_binary_types = ["explicit/type1", "explicit/type2", "image/gif", "image/png"] + expected_implicit_binary_types = ["image/gif", "image/png"] + + expected_apis = [ + # From Explicit APIs + Api(path="/path1", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + Api(path="/path2", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + Api(path="/path3", method="GET", function_name="explicitfunction", + binary_media_types=expected_explicit_binary_types), + + # Because of the RestApiId, Implicit APIs will also get the binary media types inherited from + # the corresponding Explicit API + Api(path="/connected-to-explicit-path", method="POST", function_name="ImplicitFunc", + binary_media_types=expected_explicit_binary_types), + + # This is still just a true implicit API because it does not have RestApiId property + Api(path="/true-implicit-path", method="POST", function_name="ImplicitFunc", + binary_media_types=expected_implicit_binary_types) + ] + + provider = SamApiProvider(self.template) + self.assertItemsEqual(expected_apis, provider.apis) + + +def make_swagger(apis, binary_media_types=None): + """ + Given a list of API configurations named tuples, returns a Swagger document + + Parameters + ---------- + apis : list of samcli.commands.local.lib.provider.Api + binary_media_types : list of str + + Returns + ------- + dict + Swagger document + + """ + swagger = { + "paths": { + } + } + + for api in apis: + swagger["paths"].setdefault(api.path, {}) + + integration = { + "x-amazon-apigateway-integration": { + "type": "aws_proxy", + "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789012:function:{}/invocations".format(api.function_name) # NOQA + } + } + + method = api.method + if method.lower() == "any": + method = "x-amazon-apigateway-any-method" + + swagger["paths"][api.path][method] = integration + + if binary_media_types: + swagger["x-amazon-apigateway-binary-media-types"] = binary_media_types + + return swagger diff --git a/tests/unit/commands/local/lib/test_sam_function_provider.py b/tests/unit/commands/local/lib/test_sam_function_provider.py new file mode 100644 index 0000000000..ec50a18de8 --- /dev/null +++ b/tests/unit/commands/local/lib/test_sam_function_provider.py @@ -0,0 +1,403 @@ +from unittest import TestCase +from mock import patch +from parameterized import parameterized + +from samcli.commands.local.lib.provider import Function +from samcli.commands.local.lib.sam_function_provider import SamFunctionProvider + + +class TestSamFunctionProviderEndToEnd(TestCase): + """ + Test all public methods with an input template + """ + + TEMPLATE = { + "Resources": { + + "SamFunc1": { + "Type": "AWS::Serverless::Function", + "Properties": { + "CodeUri": "/usr/foo/bar", + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + }, + "SamFunc2": { + "Type": "AWS::Serverless::Function", + "Properties": { + # CodeUri is unsupported S3 location + "CodeUri": "s3://bucket/key", + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + }, + "SamFunc3": { + "Type": "AWS::Serverless::Function", + "Properties": { + # CodeUri is unsupported S3 location + "CodeUri": { + "Bucket": "bucket", + "Key": "key" + }, + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + }, + "LambdaFunc1": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Code": { + "S3Bucket": "bucket", + "S3Key": "key" + }, + "Runtime": "nodejs4.3", + "Handler": "index.handler" + } + }, + "OtherResource": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "prod", + "DefinitionUri": "s3://bucket/key" + } + } + } + } + + EXPECTED_FUNCTIONS = ["SamFunc1", "SamFunc2", "SamFunc3", "LambdaFunc1"] + + def setUp(self): + self.provider = SamFunctionProvider(self.TEMPLATE) + + @parameterized.expand([ + ("SamFunc1", Function( + name="SamFunc1", + runtime="nodejs4.3", + handler="index.handler", + codeuri="/usr/foo/bar", + memory=None, + timeout=None, + environment=None, + rolearn=None + )), + ("SamFunc2", Function( + name="SamFunc2", + runtime="nodejs4.3", + handler="index.handler", + codeuri=".", + memory=None, + timeout=None, + environment=None, + rolearn=None + )), + ("SamFunc3", Function( + name="SamFunc3", + runtime="nodejs4.3", + handler="index.handler", + codeuri=".", + memory=None, + timeout=None, + environment=None, + rolearn=None + )), + ("LambdaFunc1", Function( + name="LambdaFunc1", + runtime="nodejs4.3", + handler="index.handler", + codeuri=".", + memory=None, + timeout=None, + environment=None, + rolearn=None + )) + ]) + def test_get_must_return_each_function(self, name, expected_output): + + actual = self.provider.get(name) + self.assertEquals(actual, expected_output) + + def test_get_all_must_return_all_functions(self): + + result = {f.name for f in self.provider.get_all()} + expected = {"SamFunc1", "SamFunc2", "SamFunc3", "LambdaFunc1"} + + self.assertEquals(result, expected) + + +class TestSamFunctionProvider_init(TestCase): + + @patch.object(SamFunctionProvider, "_extract_functions") + @patch("samcli.commands.local.lib.sam_function_provider.SamBaseProvider") + def test_must_extract_functions(self, SamBaseProviderMock, extract_mock): + extract_result = {"foo": "bar"} + extract_mock.return_value = extract_result + + template = {"Resources": {"a": "b"}} + SamBaseProviderMock.get_template.return_value = template + provider = SamFunctionProvider(template) + + extract_mock.assert_called_with({"a": "b"}) + SamBaseProviderMock.get_template.assert_called_with(template) + self.assertEquals(provider.functions, extract_result) + + @patch.object(SamFunctionProvider, "_extract_functions") + @patch("samcli.commands.local.lib.sam_function_provider.SamBaseProvider") + def test_must_default_to_empty_resources(self, SamBaseProviderMock, extract_mock): + extract_result = {"foo": "bar"} + extract_mock.return_value = extract_result + + template = {"a": "b"} # Template does *not* have 'Resources' key + SamBaseProviderMock.get_template.return_value = template + provider = SamFunctionProvider(template) + + extract_mock.assert_called_with({}) # Empty Resources value must be passed + self.assertEquals(provider.functions, extract_result) + self.assertEquals(provider.resources, {}) + + +class TestSamFunctionProvider_extract_functions(TestCase): + + @patch.object(SamFunctionProvider, "_convert_sam_function_resource") + def test_must_work_for_sam_function(self, convert_mock): + convertion_result = "some result" + convert_mock.return_value = convertion_result + + resources = { + "Func1": { + "Type": "AWS::Serverless::Function", + "Properties": {"a": "b"} + } + } + + expected = { + "Func1": "some result" + } + + result = SamFunctionProvider._extract_functions(resources) + self.assertEquals(expected, result) + convert_mock.assert_called_with('Func1', {"a": "b"}) + + @patch.object(SamFunctionProvider, "_convert_sam_function_resource") + def test_must_work_with_no_properties(self, convert_mock): + convertion_result = "some result" + convert_mock.return_value = convertion_result + + resources = { + "Func1": { + "Type": "AWS::Serverless::Function" + # No Properties + } + } + + expected = { + "Func1": "some result" + } + + result = SamFunctionProvider._extract_functions(resources) + self.assertEquals(expected, result) + convert_mock.assert_called_with('Func1', {}) + + @patch.object(SamFunctionProvider, "_convert_lambda_function_resource") + def test_must_work_for_lambda_function(self, convert_mock): + convertion_result = "some result" + convert_mock.return_value = convertion_result + + resources = { + "Func1": { + "Type": "AWS::Lambda::Function", + "Properties": {"a": "b"} + } + } + + expected = { + "Func1": "some result" + } + + result = SamFunctionProvider._extract_functions(resources) + self.assertEquals(expected, result) + convert_mock.assert_called_with('Func1', {"a": "b"}) + + def test_must_skip_unknown_resource(self): + resources = { + "Func1": { + "Type": "AWS::SomeOther::Function", + "Properties": {"a": "b"} + } + } + + expected = {} + + result = SamFunctionProvider._extract_functions(resources) + self.assertEquals(expected, result) + + +class TestSamFunctionProvider_convert_sam_function_resource(TestCase): + + def test_must_convert(self): + + name = "myname" + properties = { + "CodeUri": "/usr/local", + "Runtime": "myruntime", + "MemorySize": "mymemorysize", + "Timeout": "mytimeout", + "Handler": "myhandler", + "Environment": "myenvironment", + "Role": "myrole" + } + + expected = Function( + name="myname", + runtime="myruntime", + memory="mymemorysize", + timeout="mytimeout", + handler="myhandler", + codeuri="/usr/local", + environment="myenvironment", + rolearn="myrole" + ) + + result = SamFunctionProvider._convert_sam_function_resource(name, properties) + + self.assertEquals(expected, result) + + def test_must_skip_non_existent_properties(self): + + name = "myname" + properties = { + "CodeUri": "/usr/local" + } + + expected = Function( + name="myname", + runtime=None, + memory=None, + timeout=None, + handler=None, + codeuri="/usr/local", + environment=None, + rolearn=None + ) + + result = SamFunctionProvider._convert_sam_function_resource(name, properties) + + self.assertEquals(expected, result) + + def test_must_default_missing_code_uri(self): + + name = "myname" + properties = { + "Runtime": "myruntime" + } + + result = SamFunctionProvider._convert_sam_function_resource(name, properties) + self.assertEquals(result.codeuri, ".") # Default value + + def test_must_handle_code_dict(self): + + name = "myname" + properties = { + "CodeUri": { + # CodeUri is some dictionary + "a": "b" + } + } + + result = SamFunctionProvider._convert_sam_function_resource(name, properties) + self.assertEquals(result.codeuri, ".") # Default value + + def test_must_handle_code_s3_uri(self): + + name = "myname" + properties = { + "CodeUri": "s3://bucket/key" + } + + result = SamFunctionProvider._convert_sam_function_resource(name, properties) + self.assertEquals(result.codeuri, ".") # Default value + + +class TestSamFunctionProvider_convert_lambda_function_resource(TestCase): + + def test_must_convert(self): + + name = "myname" + properties = { + "Code": { + "Bucket": "bucket" + }, + "Runtime": "myruntime", + "MemorySize": "mymemorysize", + "Timeout": "mytimeout", + "Handler": "myhandler", + "Environment": "myenvironment", + "Role": "myrole" + } + + expected = Function( + name="myname", + runtime="myruntime", + memory="mymemorysize", + timeout="mytimeout", + handler="myhandler", + codeuri=".", + environment="myenvironment", + rolearn="myrole" + ) + + result = SamFunctionProvider._convert_lambda_function_resource(name, properties) + + self.assertEquals(expected, result) + + def test_must_skip_non_existent_properties(self): + + name = "myname" + properties = { + "Code": { + "Bucket": "bucket" + } + } + + expected = Function( + name="myname", + runtime=None, + memory=None, + timeout=None, + handler=None, + codeuri=".", + environment=None, + rolearn=None + ) + + result = SamFunctionProvider._convert_lambda_function_resource(name, properties) + + self.assertEquals(expected, result) + + +class TestSamFunctionProvider_get(TestCase): + + def test_raise_on_invalid_name(self): + provider = SamFunctionProvider({}) + + with self.assertRaises(ValueError): + provider.get(None) + + def test_must_return_function_value(self): + provider = SamFunctionProvider({}) + provider.functions = {"func1": "value"} # Cheat a bit here by setting the value of this property directly + + self.assertEquals("value", provider.get("func1")) + + def test_return_none_if_function_not_found(self): + provider = SamFunctionProvider({}) + + self.assertIsNone(provider.get("somefunc"), "Must return None when Function is not found") + + +class TestSamFunctionProvider_get_all(TestCase): + + def test_must_work_with_no_functions(self): + provider = SamFunctionProvider({}) + + result = [f for f in provider.get_all()] + self.assertEquals(result, []) diff --git a/tests/unit/commands/local/start_api/test_cli.py b/tests/unit/commands/local/start_api/test_cli.py new file mode 100644 index 0000000000..1e5d083519 --- /dev/null +++ b/tests/unit/commands/local/start_api/test_cli.py @@ -0,0 +1,107 @@ +""" +Unit test for `start-api` CLI +""" + +from unittest import TestCase +from mock import patch, Mock + +from samcli.commands.local.start_api.cli import do_cli as start_api_cli +from samcli.commands.local.lib.exceptions import NoApisDefined +from samcli.commands.local.cli_common.user_exceptions import UserException +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException + + +class TestCli(TestCase): + + def setUp(self): + self.template = "template" + self.env_vars = "env-vars" + self.debug_port = 123 + self.debug_args = "args" + self.docker_volume_basedir = "basedir" + self.docker_network = "network" + self.log_file = "logfile" + self.skip_pull_image = True + self.profile = "profile" + + self.host = "host" + self.port = 123 + self.static_dir = "staticdir" + + @patch("samcli.commands.local.start_api.cli.InvokeContext") + @patch("samcli.commands.local.start_api.cli.LocalApiService") + def test_cli_must_setup_context_and_start_service(self, LocalApiServiceMock, InvokeContextMock): + + # Mock the __enter__ method to return a object inside a context manager + context_mock = Mock() + InvokeContextMock.return_value.__enter__.return_value = context_mock + + service_mock = Mock() + LocalApiServiceMock.return_value = service_mock + + self.call_cli() + + InvokeContextMock.assert_called_with(template_file=self.template, + function_identifier=None, + env_vars_file=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + aws_profile=self.profile) + + LocalApiServiceMock.assert_called_with(lambda_invoke_context=context_mock, + port=self.port, + host=self.host, + static_dir=self.static_dir) + + service_mock.start.assert_called_with() + + @patch("samcli.commands.local.start_api.cli.InvokeContext") + @patch("samcli.commands.local.start_api.cli.LocalApiService") + def test_must_raise_if_no_api_defined(self, LocalApiServiceMock, InvokeContextMock): + + # Mock the __enter__ method to return a object inside a context manager + context_mock = Mock() + InvokeContextMock.return_value.__enter__.return_value = context_mock + + service_mock = Mock() + LocalApiServiceMock.return_value = service_mock + service_mock.start.side_effect = NoApisDefined("no apis") + + with self.assertRaises(UserException) as context: + self.call_cli() + + msg = str(context.exception) + expected = "Template does not have any APIs connected to Lambda functions" + self.assertEquals(msg, expected) + + @patch("samcli.commands.local.start_api.cli.InvokeContext") + @patch("samcli.commands.local.start_api.cli.LocalApiService") + def test_must_raise_user_exception_on_invalid_sam_template(self, LocalApiServiceMock, InvokeContextMock): + + InvokeContextMock.side_effect = InvalidSamDocumentException("bad template") + + with self.assertRaises(UserException) as context: + self.call_cli() + + msg = str(context.exception) + expected = "bad template" + self.assertEquals(msg, expected) + + def call_cli(self): + start_api_cli(ctx=None, + host=self.host, + port=self.port, + static_dir=self.static_dir, + template=self.template, + env_vars=self.env_vars, + debug_port=self.debug_port, + debug_args=self.debug_args, + docker_volume_basedir=self.docker_volume_basedir, + docker_network=self.docker_network, + log_file=self.log_file, + skip_pull_image=self.skip_pull_image, + profile=self.profile) diff --git a/tests/unit/commands/test_deploy.py b/tests/unit/commands/test_deploy.py new file mode 100644 index 0000000000..4b3c787984 --- /dev/null +++ b/tests/unit/commands/test_deploy.py @@ -0,0 +1,20 @@ +""" +Tests Deploy CLI command +""" + +from unittest import TestCase +from mock import patch + +from samcli.commands.deploy import do_cli as deploy_cli + + +class TestCli(TestCase): + + def setUp(self): + self.args = ("--template-file", "file.yaml", "--stack-name", "stackName") + + @patch("samcli.commands.deploy.execute_command") + def test_deploy_must_pass_args(self, execute_command_mock): + execute_command_mock.return_value = True + deploy_cli(self.args) + execute_command_mock.assert_called_with("deploy", self.args) diff --git a/tests/unit/commands/test_package.py b/tests/unit/commands/test_package.py new file mode 100644 index 0000000000..51e6e1809e --- /dev/null +++ b/tests/unit/commands/test_package.py @@ -0,0 +1,20 @@ +""" +Tests Package CLI command +""" + +from unittest import TestCase +from mock import patch + +from samcli.commands.package import do_cli as package_cli + + +class TestCli(TestCase): + + def setUp(self): + self.args = ("--template-file", "file.yaml", "--s3-bucket", "bucketName") + + @patch("samcli.commands.package.execute_command") + def test_package_must_pass_args(self, execute_command_mock): + execute_command_mock.return_value = True + package_cli(self.args) + execute_command_mock.assert_called_with("package", self.args) diff --git a/tests/unit/commands/validate/__init__.py b/tests/unit/commands/validate/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/validate/lib/__init__.py b/tests/unit/commands/validate/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/commands/validate/lib/test_sam_template_validator.py b/tests/unit/commands/validate/lib/test_sam_template_validator.py new file mode 100644 index 0000000000..3d33822144 --- /dev/null +++ b/tests/unit/commands/validate/lib/test_sam_template_validator.py @@ -0,0 +1,189 @@ +from unittest import TestCase +from mock import Mock, patch + +from samtranslator.public.exceptions import InvalidDocumentException + +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException +from samcli.commands.validate.lib.sam_template_validator import SamTemplateValidator + + +class TestSamTemplateValidator(TestCase): + + @patch('samcli.commands.validate.lib.sam_template_validator.Translator') + @patch('samcli.commands.validate.lib.sam_template_validator.Parser') + def test_is_valid_returns_true(self, sam_parser, sam_translator): + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"policy": "SomePolicy"} + template = {"a": "b"} + + parser = Mock() + sam_parser.return_value = parser + + translate_mock = Mock() + translate_mock.translate.return_value = {"c": "d"} + sam_translator.return_value = translate_mock + + validator = SamTemplateValidator(template, managed_policy_mock) + + # Should not throw an Exception + validator.is_valid() + + sam_translator.assert_called_once_with(managed_policy_map={"policy": "SomePolicy"}, + sam_parser=parser, + plugins=[]) + translate_mock.translate.assert_called_once_with(sam_template=template, parameter_values={}) + sam_parser.assert_called_once() + + @patch('samcli.commands.validate.lib.sam_template_validator.Translator') + @patch('samcli.commands.validate.lib.sam_template_validator.Parser') + def test_is_valid_raises_exception(self, sam_parser, sam_translator): + managed_policy_mock = Mock() + managed_policy_mock.load.return_value = {"policy": "SomePolicy"} + template = {"a": "b"} + + parser = Mock() + sam_parser.return_value = parser + + translate_mock = Mock() + translate_mock.translate.side_effect = InvalidDocumentException([Exception('message')]) + sam_translator.return_value = translate_mock + + validator = SamTemplateValidator(template, managed_policy_mock) + + with self.assertRaises(InvalidSamDocumentException): + validator.is_valid() + + sam_translator.assert_called_once_with(managed_policy_map={"policy": "SomePolicy"}, + sam_parser=parser, + plugins=[]) + translate_mock.translate.assert_called_once_with(sam_template=template, parameter_values={}) + sam_parser.assert_called_once() + + def test_init(self): + managed_policy_mock = Mock() + template = {"a": "b"} + + validator = SamTemplateValidator(template, managed_policy_mock) + + self.assertEquals(validator.managed_policy_loader, managed_policy_mock) + self.assertEquals(validator.sam_template, template) + + # check to see if SamParser was created + self.assertIsNotNone(validator.sam_parser) + + def test_uri_is_s3_uri(self): + self.assertTrue(SamTemplateValidator.is_s3_uri("s3://bucket/key")) + + def test_uri_is_not_s3_uri(self): + self.assertFalse(SamTemplateValidator.is_s3_uri("www.amazon.com")) + + def test_int_is_not_s3_uri(self): + self.assertFalse(SamTemplateValidator.is_s3_uri(100)) + + def test_update_to_s3_uri_with_non_s3_uri(self): + property_value = {"CodeUri": "somevalue"} + SamTemplateValidator._update_to_s3_uri("CodeUri", property_value) + + self.assertEquals(property_value.get("CodeUri"), "s3://bucket/value") + + def test_update_to_s3_url_with_dict(self): + property_value = {"CodeUri": {"Bucket": "mybucket-name", "Key": "swagger", "Version": 121212}} + SamTemplateValidator._update_to_s3_uri("CodeUri", property_value) + + self.assertEquals(property_value.get("CodeUri"), + {"Bucket": "mybucket-name", "Key": "swagger", "Version": 121212}) + + def test_update_to_s3_url_with_s3_uri(self): + property_value = {"CodeUri": "s3://bucket/key/version"} + SamTemplateValidator._update_to_s3_uri("CodeUri", property_value) + + self.assertEquals(property_value.get("CodeUri"), "s3://bucket/key/version") + + def test_replace_local_codeuri(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + "DefinitionUri": "./" + } + }, + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "CodeUri": "./", + "Runtime": "nodejs6.10", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + + validator = SamTemplateValidator(template, managed_policy_mock) + + validator._replace_local_codeuri() + + # check template + tempalte_resources = validator.sam_template.get("Resources") + self.assertEquals(tempalte_resources.get("ServerlessApi").get("Properties").get("DefinitionUri"), + "s3://bucket/value") + self.assertEquals(tempalte_resources.get("ServerlessFunction").get("Properties").get("CodeUri"), + "s3://bucket/value") + + def test_replace_local_codeuri_when_no_codeuri_given(self): + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": { + "ServerlessApi": { + "Type": "AWS::Serverless::Api", + "Properties": { + "StageName": "Prod", + } + }, + "ServerlessFunction": { + "Type": "AWS::Serverless::Function", + "Properties": { + "Handler": "index.handler", + "Runtime": "nodejs6.10", + "Timeout": 60 + } + } + } + } + + managed_policy_mock = Mock() + + validator = SamTemplateValidator(template, managed_policy_mock) + + validator._replace_local_codeuri() + + # check template + tempalte_resources = validator.sam_template.get("Resources") + self.assertEquals(tempalte_resources.get("ServerlessApi").get("Properties").get("DefinitionUri"), + "s3://bucket/value") + self.assertEquals(tempalte_resources.get("ServerlessFunction").get("Properties").get("CodeUri"), + "s3://bucket/value") + + def test_replace_local_codeuri_with_no_resources(self): + + template = { + "AWSTemplateFormatVersion": "2010-09-09", + "Transform": "AWS::Serverless-2016-10-31", + "Resources": {} + } + + managed_policy_mock = Mock() + + validator = SamTemplateValidator(template, managed_policy_mock) + + validator._replace_local_codeuri() + + # check template + self.assertEquals(validator.sam_template.get("Resources"), {}) diff --git a/tests/unit/commands/validate/test_cli.py b/tests/unit/commands/validate/test_cli.py new file mode 100644 index 0000000000..d440eab06c --- /dev/null +++ b/tests/unit/commands/validate/test_cli.py @@ -0,0 +1,62 @@ +from unittest import TestCase +from mock import Mock, patch + +from samcli.commands.local.cli_common.user_exceptions import SamTemplateNotFoundException, InvalidSamTemplateException +from samcli.commands.validate.lib.exceptions import InvalidSamDocumentException +from samcli.commands.validate.validate import do_cli, _read_sam_file + + +class TestValidateCli(TestCase): + + @patch('samcli.commands.validate.validate.click') + @patch('samcli.commands.validate.validate.os.path.exists') + def test_file_not_found(self, path_exists_patch, click_patch): + template_path = 'path_to_template' + + path_exists_patch.return_value = False + + with self.assertRaises(SamTemplateNotFoundException): + _read_sam_file(template_path) + + @patch('samcli.commands.validate.validate.yaml_parse') + @patch('samcli.commands.validate.validate.click') + @patch('samcli.commands.validate.validate.os.path.exists') + def test_file_parsed(self, path_exists_patch, click_patch, yaml_parse_patch): + template_path = 'path_to_template' + + path_exists_patch.return_value = True + + yaml_parse_patch.return_value = {"a": "b"} + + actual_template = _read_sam_file(template_path) + + self.assertEquals(actual_template, {"a": "b"}) + + @patch('samcli.commands.validate.validate.SamTemplateValidator') + @patch('samcli.commands.validate.validate.click') + @patch('samcli.commands.validate.validate._read_sam_file') + def test_template_fails_validation(self, read_sam_file_patch, click_patch, template_valiadator): + template_path = 'path_to_template' + read_sam_file_patch.return_value = {"a": "b"} + + is_valid_mock = Mock() + is_valid_mock.is_valid.side_effect = InvalidSamDocumentException + template_valiadator.return_value = is_valid_mock + + with self.assertRaises(InvalidSamTemplateException): + do_cli(ctx=None, + template=template_path) + + @patch('samcli.commands.validate.validate.SamTemplateValidator') + @patch('samcli.commands.validate.validate.click') + @patch('samcli.commands.validate.validate._read_sam_file') + def test_template_passes_validation(self, read_sam_file_patch, click_patch, template_valiadator): + template_path = 'path_to_template' + read_sam_file_patch.return_value = {"a": "b"} + + is_valid_mock = Mock() + is_valid_mock.is_valid.return_value = True + template_valiadator.return_value = is_valid_mock + + do_cli(ctx=None, + template=template_path) diff --git a/tests/unit/lib/__init__.py b/tests/unit/lib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/lib/samlib/__init__.py b/tests/unit/lib/samlib/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/lib/samlib/test_cloudformation_command.py b/tests/unit/lib/samlib/test_cloudformation_command.py new file mode 100644 index 0000000000..c67de17358 --- /dev/null +++ b/tests/unit/lib/samlib/test_cloudformation_command.py @@ -0,0 +1,42 @@ +""" +Tests Deploy CLI +""" + +from subprocess import CalledProcessError + +from unittest import TestCase +from mock import patch + +from samcli.lib.samlib.cloudformation_command import execute_command + + +class TestCli(TestCase): + + def setUp(self): + self.args = ("--arg1", "value1", "different args", "more") + + @patch("subprocess.check_call") + @patch("platform.system") + def test_command_must_call_aws_linux(self, platform_system_mock, check_call_mock): + platform_system_mock.return_value = "Linux" + check_call_mock.return_value = True + execute_command("command", self.args) + check_call_mock.assert_called_with(["aws", "cloudformation", "command"] + list(self.args)) + + @patch("subprocess.check_call") + @patch("platform.system") + def test_command_must_call_aws_windows(self, platform_system_mock, check_call_mock): + platform_system_mock.return_value = "Windows" + check_call_mock.return_value = True + execute_command("command", self.args) + check_call_mock.assert_called_with(["aws.cmd", "cloudformation", "command"] + list(self.args)) + + @patch("sys.exit") + @patch("subprocess.check_call") + @patch("platform.system") + def test_command_must_exit_with_status_code(self, platform_system_mock, check_call_mock, exit_mock): + platform_system_mock.return_value = "Any" + check_call_mock.side_effect = CalledProcessError(2, "Error") + exit_mock.return_value = True + execute_command("command", self.args) + exit_mock.assert_called_with(2) diff --git a/tests/unit/local/__init__.py b/tests/unit/local/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/apigw/__init__.py b/tests/unit/local/apigw/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/apigw/test_path_converter.py b/tests/unit/local/apigw/test_path_converter.py new file mode 100644 index 0000000000..e775086890 --- /dev/null +++ b/tests/unit/local/apigw/test_path_converter.py @@ -0,0 +1,79 @@ +from unittest import TestCase + +from samcli.local.apigw.path_converter import PathConverter + + +class TestPathConverter_toFlask(TestCase): + + def test_single_path_param(self): + path = "/{id}" + + flask_path = PathConverter.convert_path_to_flask(path) + + self.assertEquals(flask_path, "/") + + def test_proxy_path(self): + path = "/{proxy+}" + + flask_path = PathConverter.convert_path_to_flask(path) + + self.assertEquals(flask_path, "/") + + def test_proxy_with_path_param(self): + path = "/id/{id}/user/{proxy+}" + + flask_path = PathConverter.convert_path_to_flask(path) + + self.assertEquals(flask_path, "/id//user/") + + def test_multiple_path_params(self): + path = "/id/{id}/user/{user}" + + flask_path = PathConverter.convert_path_to_flask(path) + + self.assertEquals(flask_path, "/id//user/") + + def test_no_changes_to_path(self): + path = "/id/user" + + flask_path = PathConverter.convert_path_to_flask(path) + + self.assertEquals(flask_path, "/id/user") + + +class TestPathConverter_toApiGateway(TestCase): + + def test_single_path_param(self): + path = "/" + + flask_path = PathConverter.convert_path_to_api_gateway(path) + + self.assertEquals(flask_path, "/{id}") + + def test_proxy_path(self): + path = "/" + + flask_path = PathConverter.convert_path_to_api_gateway(path) + + self.assertEquals(flask_path, "/{proxy+}") + + def test_proxy_with_path_param(self): + path = "/id//user/" + + flask_path = PathConverter.convert_path_to_api_gateway(path) + + self.assertEquals(flask_path, "/id/{id}/user/{proxy+}") + + def test_multiple_path_params(self): + path = "/id//user/" + + flask_path = PathConverter.convert_path_to_api_gateway(path) + + self.assertEquals(flask_path, "/id/{id}/user/{user}") + + def test_no_changes_to_path(self): + path = "/id/user" + + flask_path = PathConverter.convert_path_to_api_gateway(path) + + self.assertEquals(flask_path, "/id/user") diff --git a/tests/unit/local/apigw/test_service.py b/tests/unit/local/apigw/test_service.py new file mode 100644 index 0000000000..b898cec383 --- /dev/null +++ b/tests/unit/local/apigw/test_service.py @@ -0,0 +1,527 @@ +from unittest import TestCase +from mock import Mock, patch, MagicMock, ANY +import json +import base64 + +from parameterized import parameterized, param + +from samcli.local.apigw.service import Service, Route +from samcli.local.lambdafn.exceptions import FunctionNotFound + + +class TestApiGatewayService(TestCase): + + def setUp(self): + self.function_name = Mock() + self.api_gateway_route = Route(['GET'], self.function_name, '/') + self.list_of_routes = [self.api_gateway_route] + + self.lambda_runner = Mock() + + self.stderr = Mock() + self.service = Service(self.list_of_routes, self.lambda_runner, stderr=self.stderr) + + def test_request_must_invoke_lambda(self): + make_response_mock = Mock() + + self.service._service_response = make_response_mock + self.service._get_current_route = Mock() + self.service._construct_event = Mock() + + parse_output_mock = Mock() + parse_output_mock.return_value = ("status_code", "headers", "body") + self.service._parse_lambda_output = parse_output_mock + + service_response_mock = Mock() + service_response_mock.return_value = make_response_mock + self.service._service_response = service_response_mock + + result = self.service._request_handler() + + self.assertEquals(result, make_response_mock) + self.lambda_runner.invoke.assert_called_with(ANY, + ANY, + stdout=ANY, + stderr=self.stderr) + + def test_request_handler_returns_process_stdout_when_making_response(self): + make_response_mock = Mock() + + self.service._service_response = make_response_mock + self.service._get_current_route = Mock() + self.service._construct_event = Mock() + + parse_output_mock = Mock() + parse_output_mock.return_value = ("status_code", "headers", "body") + self.service._parse_lambda_output = parse_output_mock + + lambda_logs = "logs" + lambda_response = "response" + self.service._get_lambda_output = Mock() + self.service._get_lambda_output.return_value = lambda_response, lambda_logs + + service_response_mock = Mock() + service_response_mock.return_value = make_response_mock + self.service._service_response = service_response_mock + + result = self.service._request_handler() + + self.assertEquals(result, make_response_mock) + self.service._get_lambda_output.assert_called_with(ANY) + + # Make sure the parse method is called only on the returned response and not on the raw data from stdout + parse_output_mock.assert_called_with(lambda_response, ANY, ANY) + # Make sure the logs are written to stderr + self.stderr.write.assert_called_with(lambda_logs) + + def test_request_handler_returns_make_response(self): + make_response_mock = Mock() + + self.service._service_response = make_response_mock + self.service._get_current_route = Mock() + self.service._construct_event = Mock() + + parse_output_mock = Mock() + parse_output_mock.return_value = ("status_code", "headers", "body") + self.service._parse_lambda_output = parse_output_mock + + service_response_mock = Mock() + service_response_mock.return_value = make_response_mock + self.service._service_response = service_response_mock + + result = self.service._request_handler() + + self.assertEquals(result, make_response_mock) + + def test_runtime_error_raised_when_app_not_created(self): + with self.assertRaises(RuntimeError): + self.service.run() + + def test_run_starts_service_multithreaded(self): + self.service._app = Mock() + app_run_mock = Mock() + self.service._app.run = app_run_mock + + self.lambda_runner.is_debugging.return_value = False # multithreaded + self.service.run() + + app_run_mock.assert_called_once_with(threaded=True, host='127.0.0.1', port=3000) + + def test_run_starts_service_singlethreaded(self): + self.service._app = Mock() + app_run_mock = Mock() + self.service._app.run = app_run_mock + + self.lambda_runner.is_debugging.return_value = True # single threaded + self.service.run() + + app_run_mock.assert_called_once_with(threaded=False, host='127.0.0.1', port=3000) + + def test_create_creates_dict_of_routes(self): + function_name_1 = Mock() + function_name_2 = Mock() + api_gateway_route_1 = Route(['GET'], function_name_1, '/') + api_gateway_route_2 = Route(['POST'], function_name_2, '/') + + list_of_routes = [api_gateway_route_1, api_gateway_route_2] + + lambda_runner = Mock() + + service = Service(list_of_routes, lambda_runner) + + service.create() + + self.assertEquals(service._dict_of_routes, {'/:GET': api_gateway_route_1, + '/:POST': api_gateway_route_2 + }) + + @patch('samcli.local.apigw.service.Flask') + def test_create_creates_flask_app_with_url_rules(self, flask): + app_mock = Mock() + flask.return_value = app_mock + + self.service._construct_error_handling = Mock() + + self.service.create() + + app_mock.add_url_rule.assert_called_once_with('/', + endpoint='/', + view_func=self.service._request_handler, + methods=['GET']) + + def test_initalize_creates_default_values(self): + self.assertEquals(self.service.port, 3000) + self.assertEquals(self.service.host, '127.0.0.1') + self.assertEquals(self.service.routing_list, self.list_of_routes) + self.assertIsNone(self.service.static_dir) + self.assertEquals(self.service.lambda_runner, self.lambda_runner) + + def test_initalize_with_values(self): + lambda_runner = Mock() + local_service = Service([], lambda_runner, static_dir='dir/static', port=5000, host='129.0.0.0') + self.assertEquals(local_service.port, 5000) + self.assertEquals(local_service.host, '129.0.0.0') + self.assertEquals(local_service.routing_list, []) + self.assertEquals(local_service.static_dir, 'dir/static') + self.assertEquals(local_service.lambda_runner, lambda_runner) + + @patch('samcli.local.apigw.service.ServiceErrorResponses') + def test_request_handles_error_when_invoke_cant_find_function(self, service_error_responses_patch): + + not_found_response_mock = Mock() + self.service._construct_event = Mock() + self.service._get_current_route = Mock() + service_error_responses_patch.lambda_not_found_response.return_value = not_found_response_mock + + self.lambda_runner.invoke.side_effect = FunctionNotFound() + + response = self.service._request_handler() + + self.assertEquals(response, not_found_response_mock) + + def test_request_throws_when_invoke_fails(self): + self.lambda_runner.invoke.side_effect = Exception() + + self.service._construct_event = Mock() + self.service._get_current_route = Mock() + + with self.assertRaises(Exception): + self.service._request_handler() + + @patch('samcli.local.apigw.service.ServiceErrorResponses') + def test_request_handler_errors_when_parse_lambda_output_raises_keyerror(self, service_error_responses_patch): + parse_output_mock = Mock() + parse_output_mock.side_effect = KeyError() + self.service._parse_lambda_output = parse_output_mock + + failure_response_mock = Mock() + + service_error_responses_patch.lambda_failure_response.return_value = failure_response_mock + + self.service._construct_event = Mock() + self.service._get_current_route = Mock() + + result = self.service._request_handler() + + self.assertEquals(result, failure_response_mock) + + @patch('samcli.local.apigw.service.ServiceErrorResponses') + def test_request_handler_errors_when_get_current_route_fails(self, service_error_responses_patch): + get_current_route = Mock() + get_current_route.side_effect = KeyError() + self.service._get_current_route = get_current_route + + with self.assertRaises(KeyError): + self.service._request_handler() + + @patch('samcli.local.apigw.service.ServiceErrorResponses') + def test_request_handler_errors_when_unable_to_read_binary_data(self, service_error_responses_patch): + _construct_event = Mock() + _construct_event.side_effect = UnicodeDecodeError("utf8", "obj", 1, 2, "reason") + self.service._get_current_route = Mock() + self.service._construct_event = _construct_event + + failure_mock = Mock() + service_error_responses_patch.lambda_failure_response.return_value = failure_mock + + result = self.service._request_handler() + self.assertEquals(result, failure_mock) + + @patch('samcli.local.apigw.service.request') + def test_get_current_route(self, request_patch): + + request_mock = Mock() + request_mock.endpoint = "path" + request_mock.method = "method" + + request_patch.return_value = request_mock + + route_key_method_mock = Mock() + route_key_method_mock.return_value = "method:path" + self.service._route_key = route_key_method_mock + self.service._dict_of_routes = {"method:path": "function"} + + self.assertEquals(self.service._get_current_route(request_mock), "function") + + @patch('samcli.local.apigw.service.request') + def test_get_current_route_keyerror(self, request_patch): + """ + When the a HTTP request for given method+path combination is allowed by Flask but not in the list of routes, + something is messed up. Flask should be configured only from the list of routes. + """ + + request_mock = Mock() + request_mock.endpoint = "path" + request_mock.method = "method" + + request_patch.return_value = request_mock + + route_key_method_mock = Mock() + route_key_method_mock.return_value = "method:path" + self.service._route_key = route_key_method_mock + self.service._dict_of_routes = {"a": "b"} + + with self.assertRaises(KeyError): + self.service._get_current_route(request_mock) + + @parameterized.expand([ + param( + "with both logs and response", + 'this\nis\nlog\ndata\n{"a": "b"}', 'this\nis\nlog\ndata', '{"a": "b"}' + ), + param( + "with response as string", + "logs\nresponse", "logs", "response" + ), + param( + "with response only", + '{"a": "b"}', None, '{"a": "b"}' + ), + param( + "with response only as string", + 'this is the response line', None, 'this is the response line' + ), + param( + "with whitespaces", + 'log\ndata\n{"a": "b"} \n\n\n', "log\ndata", '{"a": "b"}' + ), + param( + "with empty data", + '', None, '' + ), + param( + "with just new lines", + '\n\n', None, '' + ), + param( + "with no data but with whitespaces", + '\n \n \n', '\n ', '' # Log data with whitespaces will be in the output unchanged + ) + ]) + def test_get_lambda_output_extracts_response(self, test_case_name, stdout_data, expected_logs, expected_response): + stdout = Mock() + stdout.getvalue.return_value = stdout_data + + response, logs = self.service._get_lambda_output(stdout) + self.assertEquals(logs, expected_logs) + self.assertEquals(response, expected_response) + + +class TestApiGatewayModel(TestCase): + + def setUp(self): + self.function_name = "name" + self.api_gateway = Route(['POST'], self.function_name, '/') + + def test_class_initialization(self): + self.assertEquals(self.api_gateway.methods, ['POST']) + self.assertEquals(self.api_gateway.function_name, self.function_name) + self.assertEquals(self.api_gateway.path, '/') + + +class TestServiceParsingLambdaOutput(TestCase): + + def test_default_content_type_header_added_with_no_headers(self): + lambda_output = '{"statusCode": 200, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false}' + + (_, headers, _) = Service._parse_lambda_output(lambda_output, binary_types=[], flask_request=Mock()) + + self.assertIn("Content-Type", headers) + self.assertEquals(headers["Content-Type"], "application/json") + + def test_default_content_type_header_added_with_empty_headers(self): + lambda_output = '{"statusCode": 200, "headers":{}, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false}' + + (_, headers, _) = Service._parse_lambda_output(lambda_output, binary_types=[], flask_request=Mock()) + + self.assertIn("Content-Type", headers) + self.assertEquals(headers["Content-Type"], "application/json") + + def test_custom_content_type_header_is_not_modified(self): + lambda_output = '{"statusCode": 200, "headers":{"Content-Type": "text/xml"}, "body": "{}", ' \ + '"isBase64Encoded": false}' + + (_, headers, _) = Service._parse_lambda_output(lambda_output, binary_types=[], flask_request=Mock()) + + self.assertIn("Content-Type", headers) + self.assertEquals(headers["Content-Type"], "text/xml") + + def test_extra_values_ignored(self): + lambda_output = '{"statusCode": 200, "headers": {}, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false, "another_key": "some value"}' + + (status_code, headers, body) = Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + self.assertEquals(status_code, 200) + self.assertEquals(headers, {"Content-Type": "application/json"}) + self.assertEquals(body, '{"message":"Hello from Lambda"}') + + def test_parse_returns_correct_tuple(self): + lambda_output = '{"statusCode": 200, "headers": {}, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false}' + + (status_code, headers, body) = Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + self.assertEquals(status_code, 200) + self.assertEquals(headers, {"Content-Type": "application/json"}) + self.assertEquals(body, '{"message":"Hello from Lambda"}') + + @patch('samcli.local.apigw.service.Service._should_base64_decode_body') + def test_parse_returns_decodes_base64_to_binary(self, should_decode_body_patch): + should_decode_body_patch.return_value = True + binary_body = "011000100110100101101110011000010111001001111001" # binary in binary + base64_body = base64.b64encode(binary_body) + lambda_output = {"statusCode": 200, + "headers": {"Content-Type": "application/octet-stream"}, + "body": base64_body, + "isBase64Encoded": False} + + (status_code, headers, body) = Service._parse_lambda_output(json.dumps(lambda_output), + binary_types=['*/*'], + flask_request=Mock()) + + self.assertEquals(status_code, 200) + self.assertEquals(headers, {"Content-Type": "application/octet-stream"}) + self.assertEquals(body, binary_body) + + def test_status_code_not_int(self): + lambda_output = '{"statusCode": "str", "headers": {}, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false}' + + with self.assertRaises(TypeError): + Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + def test_status_code_negative_int(self): + lambda_output = '{"statusCode": -1, "headers": {}, "body": "{\\"message\\":\\"Hello from Lambda\\"}", ' \ + '"isBase64Encoded": false}' + + with self.assertRaises(TypeError): + Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + def test_lambda_output_list_not_dict(self): + lambda_output = '[]' + + with self.assertRaises(TypeError): + Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + def test_lambda_output_not_json_serializable(self): + lambda_output = 'some str' + + with self.assertRaises(ValueError): + Service._parse_lambda_output(lambda_output, binary_types=[], flask_request=Mock()) + + def test_properties_are_null(self): + lambda_output = '{"statusCode": 0, "headers": null, "body": null, ' \ + '"isBase64Encoded": null}' + + (status_code, headers, body) = Service._parse_lambda_output(lambda_output, + binary_types=[], + flask_request=Mock()) + + self.assertEquals(status_code, 200) + self.assertEquals(headers, {"Content-Type": "application/json"}) + self.assertEquals(body, "no data") + + +class TestService_construct_event(TestCase): + + def setUp(self): + self.request_mock = Mock() + self.request_mock.endpoint = "endpoint" + self.request_mock.path = "path" + self.request_mock.method = "GET" + self.request_mock.remote_addr = "190.0.0.0" + self.request_mock.data = b"DATA!!!!" + self.request_mock.args = {"query": "params"} + self.request_mock.headers = {"Content-Type": "application/json", "X-Test": "Value"} + self.request_mock.view_args = {"path": "params"} + self.request_mock.scheme = "http" + + expected = '{"body": "DATA!!!!", "httpMethod": "GET", ' \ + '"queryStringParameters": {"query": "params"}, "resource": ' \ + '"endpoint", "requestContext": {"httpMethod": "GET", "requestId": ' \ + '"c6af9ac6-7b61-11e6-9a41-93e8deadbeef", "path": "endpoint", "extendedRequestId": null, ' \ + '"resourceId": "123456", "apiId": "1234567890", "stage": "prod", "resourcePath": "endpoint", ' \ + '"identity": {"accountId": null, "apiKey": null, "userArn": null, ' \ + '"cognitoAuthenticationProvider": null, "cognitoIdentityPoolId": null, "userAgent": ' \ + '"Custom User Agent String", "caller": null, "cognitoAuthenticationType": null, "sourceIp": ' \ + '"190.0.0.0", "user": null}, "accountId": "123456789012"}, "headers": {"Content-Type": ' \ + '"application/json", "X-Test": "Value", "X-Forwarded-Port": "3000", "X-Forwarded-Proto": "http"}, ' \ + '"stageVariables": null, "path": "path", "pathParameters": {"path": "params"}, ' \ + '"isBase64Encoded": false}' + + self.expected_dict = json.loads(expected) + + def test_construct_event_with_data(self): + actual_event_str = Service._construct_event(self.request_mock, 3000, binary_types=[]) + self.assertEquals(json.loads(actual_event_str), self.expected_dict) + + def test_construct_event_no_data(self): + self.request_mock.data = None + self.expected_dict["body"] = None + + actual_event_str = Service._construct_event(self.request_mock, 3000, binary_types=[]) + self.assertEquals(json.loads(actual_event_str), self.expected_dict) + + @patch('samcli.local.apigw.service.Service._should_base64_encode') + def test_construct_event_with_binary_data(self, should_base64_encode_patch): + should_base64_encode_patch.return_value = True + + binary_body = "011000100110100101101110011000010111001001111001" # binary in binary + base64_body = base64.b64encode(binary_body) + + self.request_mock.data = binary_body + self.expected_dict["body"] = base64_body + self.expected_dict["isBase64Encoded"] = True + + actual_event_str = Service._construct_event(self.request_mock, 3000, binary_types=[]) + self.assertEquals(json.loads(actual_event_str), self.expected_dict) + + +class TestService_service_response(TestCase): + + @patch('samcli.local.apigw.service.Response') + def test_service_response(self, flask_response_patch): + flask_response_mock = MagicMock() + + flask_response_patch.return_value = flask_response_mock + + body = "this is the body" + status_code = 200 + headers = {"Content-Type": "application/json"} + + actual_response = Service._service_response(body, headers, status_code) + + flask_response_patch.assert_called_once_with("this is the body") + + self.assertEquals(actual_response.status_code, 200) + self.assertEquals(actual_response.headers, {"Content-Type": "application/json"}) + + +class TestService_should_base64_encode(TestCase): + + @parameterized.expand([ + param("Mimeyype is in binary types", ['image/gif'], 'image/gif'), + param("Mimetype defined and binary types has */*", ['*/*'], 'image/gif'), + param("*/* is in binary types with no mimetype defined", ['*/*'], None) + ]) + def test_should_base64_encode_returns_true(self, test_case_name, binary_types, mimetype): + self.assertTrue(Service._should_base64_encode(binary_types, mimetype)) + + @parameterized.expand([ + param("Mimetype is not in binary types", ['image/gif'], "application/octet-stream") + ]) + def test_should_base64_encode_returns_false(self, test_case_name, binary_types, mimetype): + self.assertFalse(Service._should_base64_encode(binary_types, mimetype)) diff --git a/tests/unit/local/apigw/test_service_error_responses.py b/tests/unit/local/apigw/test_service_error_responses.py new file mode 100644 index 0000000000..5716edd147 --- /dev/null +++ b/tests/unit/local/apigw/test_service_error_responses.py @@ -0,0 +1,48 @@ +from unittest import TestCase +from mock import patch, Mock + +from samcli.local.apigw.service_error_responses import ServiceErrorResponses + + +class TestServiceErrorResponses(TestCase): + + @patch('samcli.local.apigw.service_error_responses.make_response') + @patch('samcli.local.apigw.service_error_responses.jsonify') + def test_lambda_failure_response(self, jsonify_patch, make_response_patch): + jsonify_patch.return_value = {"json": "Response"} + make_response_patch.return_value = {"Some Response"} + + response = ServiceErrorResponses.lambda_failure_response() + + self.assertEquals(response, {"Some Response"}) + + jsonify_patch.assert_called_with({"message": "Internal server error"}) + make_response_patch.assert_called_with({"json": "Response"}, 502) + + @patch('samcli.local.apigw.service_error_responses.make_response') + @patch('samcli.local.apigw.service_error_responses.jsonify') + def test_lambda_not_found_response(self, jsonify_patch, make_response_patch): + jsonify_patch.return_value = {"json": "Response"} + make_response_patch.return_value = {"Some Response"} + error_mock = Mock() + + response = ServiceErrorResponses.lambda_not_found_response(error_mock) + + self.assertEquals(response, {"Some Response"}) + + jsonify_patch.assert_called_with({"message": "No function defined for resource method"}) + make_response_patch.assert_called_with({"json": "Response"}, 502) + + @patch('samcli.local.apigw.service_error_responses.make_response') + @patch('samcli.local.apigw.service_error_responses.jsonify') + def test_route_not_found(self, jsonify_patch, make_response_patch): + jsonify_patch.return_value = {"json": "Response"} + make_response_patch.return_value = {"Some Response"} + error_mock = Mock() + + response = ServiceErrorResponses.route_not_found(error_mock) + + self.assertEquals(response, {"Some Response"}) + + jsonify_patch.assert_called_with({"message": "Missing Authentication Token"}) + make_response_patch.assert_called_with({"json": "Response"}, 403) diff --git a/tests/unit/local/docker/__init__.py b/tests/unit/local/docker/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/docker/test_container.py b/tests/unit/local/docker/test_container.py new file mode 100644 index 0000000000..b652588a05 --- /dev/null +++ b/tests/unit/local/docker/test_container.py @@ -0,0 +1,438 @@ +""" +Unit test for Container class +""" +from docker.errors import NotFound, APIError +from unittest import TestCase +from mock import Mock, call, patch + +from samcli.local.docker.container import Container + + +class TestContainer_init(TestCase): + + def setUp(self): + self.image = "image" + self.cmd = "cmd" + self.working_dir = "working_dir" + self.host_dir = "host_dir" + self.memory_mb = 123 + self.exposed_ports = {123: 123} + self.entrypoint = ["a", "b", "c"] + self.env_vars = {"key": "value"} + + self.mock_docker_client = Mock() + + def test_init_must_store_all_values(self): + + container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + self.memory_mb, + self.exposed_ports, + self.entrypoint, + self.env_vars, + self.mock_docker_client) + + self.assertEquals(self.image, container._image) + self.assertEquals(self.cmd, container._cmd) + self.assertEquals(self.working_dir, container._working_dir) + self.assertEquals(self.host_dir, container._host_dir) + self.assertEquals(self.exposed_ports, container._exposed_ports) + self.assertEquals(self.entrypoint, container._entrypoint) + self.assertEquals(self.env_vars, container._env_vars) + self.assertEquals(self.memory_mb, container._memory_limit_mb) + self.assertEquals(None, container._network_id) + self.assertEquals(None, container.id) + self.assertEquals(self.mock_docker_client, container.docker_client) + + +class TestContainer_create(TestCase): + + def setUp(self): + self.image = "image" + self.cmd = "cmd" + self.working_dir = "working_dir" + self.host_dir = "host_dir" + self.memory_mb = 123 + self.exposed_ports = {123: 123} + self.entrypoint = ["a", "b", "c"] + self.env_vars = {"key": "value"} + + self.mock_docker_client = Mock() + self.mock_docker_client.containers = Mock() + self.mock_docker_client.containers.create = Mock() + self.mock_docker_client.networks = Mock() + self.mock_docker_client.networks.get = Mock() + + def test_must_create_container_with_required_values(self): + """ + Create a container with only required values. Optional values are not provided + :return: + """ + + expected_volumes = { + self.host_dir: { + "bind": self.working_dir, + "mode": "ro" + } + } + generated_id = "fooobar" + self.mock_docker_client.containers.create.return_value = Mock() + self.mock_docker_client.containers.create.return_value.id = generated_id + + container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + + container_id = container.create() + self.assertEquals(container_id, generated_id) + self.assertEquals(container.id, generated_id) + + self.mock_docker_client.containers.create.assert_called_with(self.image, + command=self.cmd, + working_dir=self.working_dir, + volumes=expected_volumes, + tty=False) + self.mock_docker_client.networks.get.assert_not_called() + + def test_must_create_container_including_all_optional_values(self): + """ + Create a container with only required values. Optional values are not provided + :return: + """ + + expected_volumes = { + self.host_dir: { + "bind": self.working_dir, + "mode": "ro" + } + } + expected_memory = "{}m".format(self.memory_mb) + + generated_id = "fooobar" + self.mock_docker_client.containers.create.return_value = Mock() + self.mock_docker_client.containers.create.return_value.id = generated_id + + container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + memory_limit_mb=self.memory_mb, + exposed_ports=self.exposed_ports, + entrypoint=self.entrypoint, + env_vars=self.env_vars, + docker_client=self.mock_docker_client) + + container_id = container.create() + self.assertEquals(container_id, generated_id) + self.assertEquals(container.id, generated_id) + + self.mock_docker_client.containers.create.assert_called_with(self.image, + command=self.cmd, + working_dir=self.working_dir, + volumes=expected_volumes, + tty=False, + environment=self.env_vars, + ports=self.exposed_ports, + entrypoint=self.entrypoint, + mem_limit=expected_memory) + self.mock_docker_client.networks.get.assert_not_called() + + def test_must_connect_to_network_on_create(self): + """ + Create a container with only required values. Optional values are not provided + :return: + """ + + network_id = "some id" + generated_id = "fooobar" + self.mock_docker_client.containers.create.return_value = Mock() + self.mock_docker_client.containers.create.return_value.id = generated_id + + network_mock = Mock() + self.mock_docker_client.networks.get.return_value = network_mock + network_mock.connect = Mock() + + container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + + container.network_id = network_id + + container_id = container.create() + self.assertEquals(container_id, generated_id) + + self.mock_docker_client.networks.get.assert_called_with(network_id) + network_mock.connect.assert_called_with(container_id) + + def test_must_fail_if_already_created(self): + + container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + + container.is_created = Mock() + container.is_created.return_value = True + + with self.assertRaises(RuntimeError): + container.create() + + +class TestContainer_delete(TestCase): + + def setUp(self): + self.image = "image" + self.cmd = "cmd" + self.working_dir = "working_dir" + self.host_dir = "host_dir" + + self.mock_docker_client = Mock() + self.mock_docker_client.containers = Mock() + self.mock_docker_client.containers.get = Mock() + + self.container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + self.container.id = "someid" + + self.container.is_created = Mock() + + def test_must_delete(self): + + self.container.is_created.return_value = True + real_container_mock = Mock() + self.mock_docker_client.containers.get.return_value = real_container_mock + real_container_mock.remove = Mock() + + self.container.delete() + + self.mock_docker_client.containers.get.assert_called_with("someid") + real_container_mock.remove.assert_called_with(force=True) + + # Must reset ID to None because container is now gone + self.assertIsNone(self.container.id) + + def test_must_work_when_container_is_not_found(self): + self.container.is_created.return_value = True + real_container_mock = Mock() + self.mock_docker_client.containers.get.side_effect = NotFound("msg") + real_container_mock.remove = Mock() + + self.container.delete() + + self.mock_docker_client.containers.get.assert_called_with("someid") + real_container_mock.remove.assert_not_called() + + # Must reset ID to None because container is now gone + self.assertIsNone(self.container.id) + + def test_must_work_if_container_delete_is_in_progress(self): + self.container.is_created.return_value = True + real_container_mock = Mock() + self.mock_docker_client.containers.get.return_value = real_container_mock + real_container_mock.remove = Mock() + real_container_mock.remove.side_effect = APIError("removal of container is already in progress") + + self.container.delete() + + self.mock_docker_client.containers.get.assert_called_with("someid") + real_container_mock.remove.assert_called_with(force=True) + + # Must reset ID to None because container is now gone + self.assertIsNone(self.container.id) + + def test_must_raise_unknown_docker_api_errors(self): + self.container.is_created.return_value = True + real_container_mock = Mock() + self.mock_docker_client.containers.get.return_value = real_container_mock + real_container_mock.remove = Mock() + real_container_mock.remove.side_effect = APIError("some error") + + with self.assertRaises(APIError): + self.container.delete() + + # Must *NOT* reset ID because Docker API raised an exception + self.assertIsNotNone(self.container.id) + + def test_must_skip_if_container_is_not_created(self): + + self.container.is_created.return_value = False + self.container.delete() + self.mock_docker_client.containers.get.assert_not_called() + + +class TestContainer_start(TestCase): + + def setUp(self): + self.image = "image" + self.cmd = "cmd" + self.working_dir = "working_dir" + self.host_dir = "host_dir" + + self.mock_docker_client = Mock() + self.mock_docker_client.containers = Mock() + self.mock_docker_client.containers.get = Mock() + + self.container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + self.container.id = "someid" + + self.container.is_created = Mock() + + def test_must_start_container(self): + + self.container.is_created.return_value = True + + container_mock = Mock() + self.mock_docker_client.containers.get.return_value = container_mock + container_mock.start = Mock() + + self.container.start() + + self.mock_docker_client.containers.get.assert_called_with(self.container.id) + container_mock.start.assert_called_with() + + def test_must_not_start_if_container_is_not_created(self): + + self.container.is_created.return_value = False + + with self.assertRaises(RuntimeError): + self.container.start() + + def test_must_not_support_input_data(self): + + self.container.is_created.return_value = True + + with self.assertRaises(ValueError): + self.container.start(input_data="some input data") + + +class TestContainer_wait_for_logs(TestCase): + + def setUp(self): + self.image = "image" + self.cmd = ["cmd"] + self.working_dir = "working_dir" + self.host_dir = "host_dir" + + self.mock_docker_client = Mock() + self.mock_docker_client.containers = Mock() + self.mock_docker_client.containers.get = Mock() + + self.container = Container(self.image, + self.cmd, + self.working_dir, + self.host_dir, + docker_client=self.mock_docker_client) + self.container.id = "someid" + + self.container.is_created = Mock() + + @patch("samcli.local.docker.container.attach") + def test_must_fetch_stdout_and_stderr_data(self, attach_mock): + + self.container.is_created.return_value = True + + real_container_mock = Mock() + self.mock_docker_client.containers.get.return_value = real_container_mock + + output_itr = Mock() + attach_mock.return_value = output_itr + self.container._write_container_output = Mock() + + stdout_mock = Mock() + stderr_mock = Mock() + + self.container.wait_for_logs(stdout=stdout_mock, stderr=stderr_mock) + + attach_mock.assert_called_with(self.mock_docker_client, container=real_container_mock, + stdout=True, stderr=True, logs=True) + self.container._write_container_output.assert_called_with(output_itr, stdout=stdout_mock, stderr=stderr_mock) + + def test_must_skip_if_no_stdout_and_stderr(self): + + self.container.wait_for_logs() + self.mock_docker_client.containers.get.assert_not_called() + + def test_must_raise_if_container_is_not_created(self): + + self.container.is_created.return_value = False + + with self.assertRaises(RuntimeError): + self.container.wait_for_logs(stdout=Mock()) + + +class TestContainer_write_container_output(TestCase): + + def setUp(self): + self.output_itr = [ + (Container._STDOUT_FRAME_TYPE, "stdout1"), + (Container._STDERR_FRAME_TYPE, "stderr1"), + (30, "invalid1"), + + (Container._STDOUT_FRAME_TYPE, "stdout2"), + (Container._STDERR_FRAME_TYPE, "stderr2"), + (30, "invalid2"), + + (Container._STDOUT_FRAME_TYPE, "stdout3"), + (Container._STDERR_FRAME_TYPE, "stderr3"), + (30, "invalid3"), + ] + + self.stdout_mock = Mock() + self.stderr_mock = Mock() + + def test_must_write_stdout_and_stderr_data(self): + # All the invalid frames must be ignored + + Container._write_container_output(self.output_itr, stdout=self.stdout_mock, stderr=self.stderr_mock) + + self.stdout_mock.write.assert_has_calls([ + call("stdout1"), call("stdout2"), call("stdout3") + ]) + + self.stderr_mock.write.assert_has_calls([ + call("stderr1"), call("stderr2"), call("stderr3") + ]) + + def test_must_write_only_stdout(self): + + Container._write_container_output(self.output_itr, stdout=self.stdout_mock, stderr=None) + + self.stdout_mock.write.assert_has_calls([ + call("stdout1"), call("stdout2"), call("stdout3") + ]) + + self.stderr_mock.write.assert_not_called() # stderr must never be called + + def test_must_write_only_stderr(self): + # All the invalid frames must be ignored + + Container._write_container_output(self.output_itr, stdout=None, stderr=self.stderr_mock) + + self.stdout_mock.write.assert_not_called() + + self.stderr_mock.write.assert_has_calls([ + call("stderr1"), call("stderr2"), call("stderr3") + ]) + + +class TestContainer_image(TestCase): + + def test_must_return_image_value(self): + image = "myimage" + container = Container(image, "cmd", "dir", "dir") + + self.assertEquals(image, container.image) diff --git a/tests/unit/local/docker/test_lambda_container.py b/tests/unit/local/docker/test_lambda_container.py new file mode 100644 index 0000000000..0fbaed363d --- /dev/null +++ b/tests/unit/local/docker/test_lambda_container.py @@ -0,0 +1,143 @@ +""" +Unit test for Lambda container management +""" + +from unittest import TestCase +from mock import patch +from parameterized import parameterized, param + +from samcli.local.docker.lambda_container import LambdaContainer, Runtime + +RUNTIMES_WITH_ENTRYPOINT = [Runtime.java8.value, + Runtime.nodejs.value, + Runtime.nodejs43.value, + Runtime.nodejs610.value, + Runtime.nodejs810.value, + Runtime.python36.value, + Runtime.python27.value] + +ALL_RUNTIMES = [r for r in Runtime] + + +class TestLambdaContainer_init(TestCase): + + def setUp(self): + self.runtime = "nodejs4.3" + self.handler = "handler" + self.code_dir = "codedir" + self.env_var = {"var": "value"} + self.memory_mb = 1024 + self.debug_port = 1235 + self.debug_arg = "a=b c=d e=f" + + @patch.object(LambdaContainer, "_get_image") + @patch.object(LambdaContainer, "_get_exposed_ports") + @patch.object(LambdaContainer, "_get_entry_point") + def test_must_configure_container_properly(self, + get_entry_point_mock, + get_exposed_ports_mock, + get_image_mock): + + image = "image" + ports = {"a": "b"} + entry = [1, 2, 3] + expected_cmd = [self.handler] + + get_image_mock.return_value = image + get_exposed_ports_mock.return_value = ports + get_entry_point_mock.return_value = entry + + container = LambdaContainer(self.runtime, + self.handler, + self.code_dir, + env_vars=self.env_var, + memory_mb=self.memory_mb, + debug_port=self.debug_port, + debug_args=self.debug_arg) + + self.assertEquals(image, container._image) + self.assertEquals(expected_cmd, container._cmd) + self.assertEquals("/var/task", container._working_dir) + self.assertEquals(self.code_dir, container._host_dir) + self.assertEquals(ports, container._exposed_ports) + self.assertEquals(entry, container._entrypoint) + self.assertEquals(self.env_var, container._env_vars) + self.assertEquals(self.memory_mb, container._memory_limit_mb) + + get_image_mock.assert_called_with(self.runtime) + get_exposed_ports_mock.assert_called_with(self.debug_port) + get_entry_point_mock.assert_called_with(self.runtime, self.debug_port, self.debug_arg) + + def test_must_fail_for_unsupported_runtime(self): + + runtime = "foo" + + with self.assertRaises(ValueError) as context: + LambdaContainer(runtime, self.handler, self.code_dir) + + self.assertEquals(str(context.exception), "Unsupported Lambda runtime foo") + + +class TestLambdaContainer_get_exposed_ports(TestCase): + + def test_must_map_same_port_on_host_and_container(self): + + port = 12345 + expected = {port: port} + result = LambdaContainer._get_exposed_ports(port) + + self.assertEquals(expected, result) + + def test_must_skip_if_port_is_not_given(self): + + self.assertIsNone(LambdaContainer._get_exposed_ports(None), "No ports should be exposed") + + +class TestLambdaContainer_get_image(TestCase): + + def test_must_return_lambci_image(self): + + runtime = "foo" + expected = "lambci/lambda:foo" + + self.assertEquals(LambdaContainer._get_image(runtime), expected) + + +class TestLambdaContainer_get_entry_point(TestCase): + + def setUp(self): + + self.debug_port = 1235 + self.debug_args = "a=b c=d e=f" + + def test_must_skip_if_debug_port_is_not_specified(self): + self.assertIsNone(LambdaContainer._get_entry_point("runtime", None, self.debug_args), + "Must not provide entrypoint if debug port is not given") + + @parameterized.expand([param(r) for r in ALL_RUNTIMES]) + def test_must_provide_entrypoint_for_certain_runtimes_only(self, runtime): + + result = LambdaContainer._get_entry_point(runtime, self.debug_port, self.debug_args) + + if runtime in RUNTIMES_WITH_ENTRYPOINT: + self.assertIsNotNone(result, "{} runtime must provide entrypoint".format(runtime)) + else: + self.assertIsNone(result, "{} runtime must NOT provide entrypoint".format(runtime)) + + @parameterized.expand([param(r) for r in RUNTIMES_WITH_ENTRYPOINT]) + def test_debug_arg_must_be_split_by_spaces_and_appended_to_entrypoint(self, runtime): + """ + Debug args list is appended starting at second position in the array + """ + expected_debug_args = ["a=b", "c=d", "e=f"] + result = LambdaContainer._get_entry_point(runtime, self.debug_port, self.debug_args) + actual = result[1:4] + + self.assertEquals(actual, expected_debug_args) + + @parameterized.expand([param(r) for r in RUNTIMES_WITH_ENTRYPOINT]) + def test_must_provide_entrypoint_even_without_debug_args(self, runtime): + + result = LambdaContainer._get_entry_point(runtime, self.debug_port) + + self.assertIsNotNone(result) diff --git a/tests/unit/local/docker/test_manager.py b/tests/unit/local/docker/test_manager.py new file mode 100644 index 0000000000..c82fb0fbee --- /dev/null +++ b/tests/unit/local/docker/test_manager.py @@ -0,0 +1,185 @@ +""" +Tests container manager +""" + +import io + +from unittest import TestCase +from mock import Mock +from docker.errors import ImageNotFound +from samcli.local.docker.manager import ContainerManager, DockerImageNotFoundException + + +class TestContainerManager_init(TestCase): + + def test_must_initialize_with_default_value(self): + + manager = ContainerManager() + self.assertFalse(manager.skip_pull_image) + + +class TestContainerManager_run(TestCase): + + def setUp(self): + self.mock_docker_client = Mock() + self.manager = ContainerManager(docker_client=self.mock_docker_client) + + self.image_name = "image name" + self.container_mock = Mock() + self.container_mock.image = self.image_name + self.container_mock.start = Mock() + self.container_mock.create = Mock() + self.container_mock.is_created = Mock() + + def test_must_error_with_warm(self): + + with self.assertRaises(ValueError): + self.manager.run(self.container_mock, warm=True) + + def test_must_pull_image_and_run_container(self): + input_data = "input data" + + self.manager.has_image = Mock() + self.manager.pull_image = Mock() + + # Assume the image doesn't exist. + self.manager.has_image.return_value = False + + self.manager.run(self.container_mock, input_data) + + self.manager.has_image.assert_called_with(self.image_name) + self.manager.pull_image.assert_called_with(self.image_name) + self.container_mock.start.assert_called_with(input_data=input_data) + + def test_must_pull_image_if_image_exist_and_no_skip(self): + input_data = "input data" + + self.manager.has_image = Mock() + self.manager.pull_image = Mock() + + # Assume the image exist. + self.manager.has_image.return_value = True + # And, don't skip pulling => Pull again + self.manager.skip_pull_image = False + + self.manager.run(self.container_mock, input_data) + + self.manager.has_image.assert_called_with(self.image_name) + self.manager.pull_image.assert_called_with(self.image_name) + self.container_mock.start.assert_called_with(input_data=input_data) + + def test_must_not_pull_image_if_asked_to_skip(self): + input_data = "input data" + + self.manager.has_image = Mock() + self.manager.pull_image = Mock() + + # Assume the image exist. + self.manager.has_image.return_value = True + # And, skip pulling + self.manager.skip_pull_image = True + + self.manager.run(self.container_mock, input_data) + + self.manager.has_image.assert_called_with(self.image_name) + # Must not call pull_image + self.manager.pull_image.assert_not_called() + self.container_mock.start.assert_called_with(input_data=input_data) + + def test_must_create_container_if_not_exists(self): + input_data = "input data" + self.manager.has_image = Mock() + self.manager.pull_image = Mock() + + # Assume container does NOT exist + self.container_mock.is_created.return_value = False + + self.manager.run(self.container_mock, input_data) + + # Container should be created + self.container_mock.create.assert_called_with() + + def test_must_not_create_container_if_it_already_exists(self): + input_data = "input data" + self.manager.has_image = Mock() + self.manager.pull_image = Mock() + + # Assume container does NOT exist + self.container_mock.is_created.return_value = True + + self.manager.run(self.container_mock, input_data) + + # Container should be created + self.container_mock.create.assert_not_called() + + +class TestContainerManager_pull_image(TestCase): + + def setUp(self): + self.image_name = "image name" + + self.mock_docker_client = Mock() + self.mock_docker_client.api = Mock() + self.mock_docker_client.api.pull = Mock() + + self.manager = ContainerManager(docker_client=self.mock_docker_client) + + def test_must_pull_and_print_progress_dots(self): + + stream = io.StringIO() + pull_result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] + self.mock_docker_client.api.pull.return_value = pull_result + expected_stream_output = "\nFetching {} Docker container image...{}\n".format( + self.image_name, + '.' * len(pull_result) # Progress bar will print one dot per response from pull API + ) + + self.manager.pull_image(self.image_name, stream=stream) + + self.mock_docker_client.api.pull.assert_called_with(self.image_name, + stream=True, + decode=True) + self.assertEquals(stream.getvalue(), expected_stream_output) + + def test_must_raise_if_image_not_found(self): + msg = "some error" + self.mock_docker_client.api.pull.side_effect = ImageNotFound(msg) + + with self.assertRaises(DockerImageNotFoundException) as context: + self.manager.pull_image("imagename") + + ex = context.exception + self.assertEquals(str(ex), msg) + + +class TestContainerManager_has_image(TestCase): + + def setUp(self): + self.image_name = "image name" + + self.mock_docker_client = Mock() + self.mock_docker_client.images = Mock() + self.mock_docker_client.images.get = Mock() + + self.manager = ContainerManager(docker_client=self.mock_docker_client) + + def test_must_find_an_image(self): + + self.assertTrue(self.manager.has_image(self.image_name)) + + def test_must_not_find_image(self): + + self.mock_docker_client.images.get.side_effect = ImageNotFound("test") + self.assertFalse(self.manager.has_image(self.image_name)) + + +class TestContainerManager_stop(TestCase): + + def test_must_call_delete_on_container(self): + + manager = ContainerManager() + container = Mock() + container.delete = Mock() + + manager.stop(container) + container.delete.assert_called_with() diff --git a/tests/unit/local/events/__init__.py b/tests/unit/local/events/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/events/test_api_event.py b/tests/unit/local/events/test_api_event.py new file mode 100644 index 0000000000..e47c9e48c2 --- /dev/null +++ b/tests/unit/local/events/test_api_event.py @@ -0,0 +1,282 @@ +from unittest import TestCase +from mock import Mock + +from samcli.local.events.api_event import ContextIdentity, RequestContext, ApiGatewayLambdaEvent + + +class TestContextIdentity(TestCase): + + def test_class_initialized(self): + identity = ContextIdentity('api_key', + 'user_arn', + 'cognito_authentication_type', + 'caller', + 'user_agent', + 'user', + 'cognito_identity_pool_id', + 'cognito_authentication_provider', + 'source_ip', + 'account_id' + ) + + self.assertEquals(identity.api_key, 'api_key') + self.assertEquals(identity.user_arn, 'user_arn') + self.assertEquals(identity.cognito_authentication_type, 'cognito_authentication_type') + self.assertEquals(identity.caller, 'caller') + self.assertEquals(identity.user_agent, 'user_agent') + self.assertEquals(identity.user, 'user') + self.assertEquals(identity.cognito_identity_pool_id, 'cognito_identity_pool_id') + self.assertEquals(identity.cognito_authentication_provider, 'cognito_authentication_provider') + self.assertEquals(identity.source_ip, 'source_ip') + self.assertEquals(identity.account_id, 'account_id') + + def test_to_dict(self): + identity = ContextIdentity('api_key', + 'user_arn', + 'cognito_authentication_type', + 'caller', + 'user_agent', + 'user', + 'cognito_identity_pool_id', + 'cognito_authentication_provider', + 'source_ip', + 'account_id' + ) + + expected = {"apiKey": "api_key", + "userArn": "user_arn", + "cognitoAuthenticationType": "cognito_authentication_type", + "caller": "caller", + "userAgent": "user_agent", + "user": "user", + "cognitoIdentityPoolId": "cognito_identity_pool_id", + "cognitoAuthenticationProvider": "cognito_authentication_provider", + "sourceIp": "source_ip", + "accountId": "account_id" + } + + self.assertEquals(identity.to_dict(), expected) + + def test_to_dict_with_defaults(self): + identity = ContextIdentity() + + expected = {"apiKey": None, + "userArn": None, + "cognitoAuthenticationType": None, + "caller": None, + "userAgent": "Custom User Agent String", + "user": None, + "cognitoIdentityPoolId": None, + "cognitoAuthenticationProvider": None, + "sourceIp": "127.0.0.1", + "accountId": None + } + + self.assertEquals(identity.to_dict(), expected) + + +class TestRequestContext(TestCase): + + def test_class_initialized(self): + identity_mock = Mock() + + request_context = RequestContext('resource_id', + 'api_id', + 'request_path', + 'request_method', + 'request_id', + 'account_id', + 'prod', + identity_mock, + 'extended_request_id', + 'path' + ) + + self.assertEquals(request_context.resource_id, 'resource_id') + self.assertEquals(request_context.api_id, 'api_id') + self.assertEquals(request_context.resource_path, 'request_path') + self.assertEquals(request_context.http_method, 'request_method') + self.assertEquals(request_context.request_id, 'request_id') + self.assertEquals(request_context.account_id, 'account_id') + self.assertEquals(request_context.stage, 'prod') + self.assertEquals(request_context.identity, identity_mock) + self.assertEquals(request_context.extended_request_id, 'extended_request_id') + self.assertEquals(request_context.path, 'path') + + def test_to_dict(self): + identity_mock = Mock() + identity_mock.to_dict.return_value = {"identity": "the identity"} + + request_context = RequestContext('resource_id', + 'api_id', + 'request_path', + 'request_method', + 'request_id', + 'account_id', + 'prod', + identity_mock, + 'extended_request_id', + 'path' + ) + + expected = {"resourceId": "resource_id", + "apiId": "api_id", + "resourcePath": "request_path", + "httpMethod": "request_method", + "requestId": "request_id", + "accountId": "account_id", + "stage": "prod", + "identity": {"identity": "the identity"}, + "extendedRequestId": "extended_request_id", + "path": "path" + } + + self.assertEquals(request_context.to_dict(), expected) + + def test_to_dict_with_defaults(self): + request_context = RequestContext() + + expected = {"resourceId": "123456", + "apiId": "1234567890", + "resourcePath": None, + "httpMethod": None, + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "accountId": "123456789012", + "stage": None, + "identity": {}, + "extendedRequestId": None, + "path": None + } + + self.assertEquals(request_context.to_dict(), expected) + + +class TestApiGatewayLambdaEvent(TestCase): + + def test_class_initialized(self): + event = ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + 'request_context', + {"query": "some query"}, + {"header_key": "value"}, + {"param": "some param"}, + {"stage_vars": "some vars"}, + 'request_path', + False + ) + + self.assertEquals(event.http_method, 'request_method') + self.assertEquals(event.body, 'request_data') + self.assertEquals(event.resource, 'resource') + self.assertEquals(event.request_context, 'request_context') + self.assertEquals(event.query_string_params, {"query": "some query"}) + self.assertEquals(event.headers, {"header_key": "value"}) + self.assertEquals(event.path_parameters, {"param": "some param"}) + self.assertEquals(event.stage_variables, {"stage_vars": "some vars"}) + self.assertEquals(event.path, 'request_path') + self.assertEquals(event.is_base_64_encoded, False) + + def test_to_dict(self): + request_context_mock = Mock() + request_context_mock.to_dict.return_value = {"request_context": "the request context"} + + event = ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + request_context_mock, + {"query": "some query"}, + {"header_key": "value"}, + {"param": "some param"}, + {"stagevars": "some vars"}, + 'request_path', + False + ) + + expected = {"httpMethod": "request_method", + "body": "request_data", + "resource": "resource", + "requestContext": {"request_context": "the request context"}, + "queryStringParameters": {"query": "some query"}, + "headers": {"header_key": "value"}, + "pathParameters": {"param": "some param"}, + "stageVariables": {"stagevars": "some vars"}, + "path": "request_path", + "isBase64Encoded": False + } + + self.assertEquals(event.to_dict(), expected) + + def test_to_dict_with_defaults(self): + event = ApiGatewayLambdaEvent() + + expected = {"httpMethod": None, + "body": None, + "resource": None, + "requestContext": {}, + "queryStringParameters": None, + "headers": None, + "pathParameters": None, + "stageVariables": None, + "path": None, + "isBase64Encoded": False + } + + self.assertEquals(event.to_dict(), expected) + + def test_init_with_invalid_query_string_params(self): + with self.assertRaises(TypeError): + ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + 'request_context', + "not a dict", + {"header_key": "value"}, + {"param": "some param"}, + {"stage_vars": "some vars"}, + 'request_path', + False + ) + + def test_init_with_invalid_headers(self): + with self.assertRaises(TypeError): + ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + 'request_context', + {"query": "some query"}, + "not EnvironHeaders", + {"param": "some param"}, + {"stage_vars": "some vars"}, + 'request_path', + False + ) + + def test_init_with_invalid_path_parameters(self): + with self.assertRaises(TypeError): + ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + 'request_context', + {"query": "some query"}, + {"header_key": "value"}, + "Not a dict", + {"stage_vars": "some vars"}, + 'request_path', + False + ) + + def test_init_with_invalid_stage_variables(self): + with self.assertRaises(TypeError): + + ApiGatewayLambdaEvent('request_method', + 'request_data', + 'resource', + 'request_context', + {"query": "some query"}, + {"header_key": "value"}, + {"param": "some param"}, + "Not a dict", + 'request_path', + False + ) diff --git a/tests/unit/local/init/__init__.py b/tests/unit/local/init/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/init/test_init.py b/tests/unit/local/init/test_init.py new file mode 100644 index 0000000000..4e79db081e --- /dev/null +++ b/tests/unit/local/init/test_init.py @@ -0,0 +1,77 @@ +from unittest import TestCase +from mock import patch + +from cookiecutter.exceptions import CookiecutterException +from samcli.local.init import generate_project +from samcli.local.init import GenerateProjectFailedError +from samcli.local.init import RUNTIME_TEMPLATE_MAPPING + + +class TestInit(TestCase): + + def setUp(self): + self.location = None + self.runtime = "python3.6" + self.output_dir = "." + self.name = "testing project" + self.no_input = True + self.extra_context = {'project_name': 'testing project', "runtime": self.runtime} + self.template = RUNTIME_TEMPLATE_MAPPING[self.runtime] + + @patch("samcli.local.init.cookiecutter") + def test_init_successful(self, cookiecutter_patch): + # GIVEN generate_project successfully created a project + # WHEN a project name has been passed + generate_project( + location=self.location, runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=self.no_input) + + # THEN we should receive no errors + cookiecutter_patch.assert_called_once_with( + extra_context=self.extra_context, no_input=self.no_input, + output_dir=self.output_dir, template=self.template) + + @patch("samcli.local.init.cookiecutter") + def test_when_generate_project_returns_error(self, cookiecutter_patch): + + # GIVEN generate_project fails to create a project + ex = CookiecutterException("something is wrong") + cookiecutter_patch.side_effect = ex + + expected_msg = str(GenerateProjectFailedError(project=self.name, provider_error=ex)) + + # WHEN generate_project returns an error + # THEN we should receive a GenerateProjectFailedError Exception + with self.assertRaises(GenerateProjectFailedError) as ctx: + generate_project( + location=self.location, runtime=self.runtime, + output_dir=self.output_dir, name=self.name, no_input=self.no_input) + + self.assertEquals(expected_msg, str(ctx.exception)) + + @patch("samcli.local.init.cookiecutter") + def test_must_not_set_name_when_location_is_given(self, cookiecutter_patch): + generate_project(runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=False) + + expected_extra_content = { + "project_name": self.name, + "runtime": self.runtime + } + # THEN we should receive no errors + cookiecutter_patch.assert_called_once_with( + template=self.template, + extra_context=expected_extra_content, no_input=True, + output_dir=self.output_dir) + + @patch("samcli.local.init.cookiecutter") + def test_must_not_set_extra_content(self, cookiecutter_patch): + custom_location = "mylocation" + generate_project(location=custom_location, + runtime=self.runtime, output_dir=self.output_dir, + name=self.name, no_input=False) + + # THEN we should receive no errors + cookiecutter_patch.assert_called_once_with( + template=custom_location, no_input=False, + output_dir=self.output_dir) diff --git a/tests/unit/local/lambdafn/__init__.py b/tests/unit/local/lambdafn/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/local/lambdafn/test_config.py b/tests/unit/local/lambdafn/test_config.py new file mode 100644 index 0000000000..f52b5d45eb --- /dev/null +++ b/tests/unit/local/lambdafn/test_config.py @@ -0,0 +1,51 @@ + +from unittest import TestCase +from mock import Mock + +from samcli.local.lambdafn.config import FunctionConfig + + +class TestFunctionConfig(TestCase): + + DEFAULT_MEMORY = 128 + DEFAULT_TIMEOUT = 3 + + def setUp(self): + self.name = "name" + self.runtime = "runtime" + self.handler = "handler" + self.code_path = "codepath" + self.memory = 1234 + self.timeout = 34 + self.env_vars_mock = Mock() + + def test_init_with_env_vars(self): + config = FunctionConfig(self.name, self.runtime, self.handler, self.code_path, + memory=self.memory, timeout=self.timeout, env_vars=self.env_vars_mock) + + self.assertEquals(config.name, self.name) + self.assertEquals(config.runtime, self.runtime) + self.assertEquals(config.handler, self.handler) + self.assertEquals(config.code_abs_path, self.code_path) + self.assertEquals(config.memory, self.memory) + self.assertEquals(config.timeout, self.timeout) + self.assertEquals(config.env_vars, self.env_vars_mock) + + self.assertEquals(self.env_vars_mock.handler, self.handler) + self.assertEquals(self.env_vars_mock.memory, self.memory) + self.assertEquals(self.env_vars_mock.timeout, self.timeout) + + def test_init_without_optional_values(self): + config = FunctionConfig(self.name, self.runtime, self.handler, self.code_path) + + self.assertEquals(config.name, self.name) + self.assertEquals(config.runtime, self.runtime) + self.assertEquals(config.handler, self.handler) + self.assertEquals(config.code_abs_path, self.code_path) + self.assertEquals(config.memory, self.DEFAULT_MEMORY) + self.assertEquals(config.timeout, self.DEFAULT_TIMEOUT) + self.assertIsNotNone(config.env_vars) + + self.assertEquals(config.env_vars.handler, self.handler) + self.assertEquals(config.env_vars.memory, self.DEFAULT_MEMORY) + self.assertEquals(config.env_vars.timeout, self.DEFAULT_TIMEOUT) diff --git a/tests/unit/local/lambdafn/test_env_vars.py b/tests/unit/local/lambdafn/test_env_vars.py new file mode 100644 index 0000000000..0b67355bc7 --- /dev/null +++ b/tests/unit/local/lambdafn/test_env_vars.py @@ -0,0 +1,343 @@ +""" +Test for environment variable handling +""" + +from parameterized import parameterized, param +from unittest import TestCase +from samcli.local.lambdafn.env_vars import EnvironmentVariables + + +class TestEnvironmentVariables_init(TestCase): + + def test_must_initialize_with_empty_values(self): + + memory = 123 + timeout = 10 + handler = "handler" + + environ = EnvironmentVariables() + environ.memory = memory + environ.timeout = timeout + environ.handler = handler + + self.assertEquals(environ.memory, memory) + self.assertEquals(environ.timeout, timeout) + self.assertEquals(environ.handler, handler) + + def test_must_initialize_values_with_required_values(self): + memory = 123 + timeout = 10 + handler = "handler" + + environ = EnvironmentVariables(memory, timeout, handler) + self.assertEquals(environ.memory, memory) + self.assertEquals(environ.timeout, timeout) + self.assertEquals(environ.handler, handler) + self.assertEquals(environ.variables, {}) + self.assertEquals(environ.shell_env_values, {}) + self.assertEquals(environ.override_values, {}) + self.assertEquals(environ.aws_creds, {}) + + def test_must_initialize_with_optional_values(self): + memory = 123 + timeout = 10 + handler = "handler" + variables = {"a": "b"} + shell_values = {"c": "d"} + overrides = {"e": "f"} + aws_creds = {"g": "h"} + + environ = EnvironmentVariables(memory, timeout, handler, + variables=variables, + shell_env_values=shell_values, + override_values=overrides, + aws_creds=aws_creds) + + self.assertEquals(environ.variables, {"a": "b"}) + self.assertEquals(environ.shell_env_values, {"c": "d"}) + self.assertEquals(environ.override_values, {"e": "f"}) + self.assertEquals(environ.aws_creds, {"g": "h"}) + + +class TestEnvironmentVariables_resolve(TestCase): + + def setUp(self): + self.memory = 1024 + self.timeout = 123 + self.handler = "handler" + + self.aws_creds = { + "region": "some region", + "key": "some key", + "secret": "some other secret", + "sessiontoken": "some other token" + } + + self.variables = { + "variable1": 1, + "variable2": "mystring", + + "list_var": [1, 2, 3], + "dict_var": {"a": {"b": "c"}}, + "none_var": None, + "true_var": True, + "false_var": False, + + # We should be able to override AWS_* values + "AWS_DEFAULT_REGION": "user-specified-region" + } + + self.shell_env = { + # This variable is not defined in self.variables. So won't show up in resutlt + "myothervar": "somevalue", + + "variable1": "variable1 value from shell_env" + } + + self.override = { + # This variable is not defined in self.variables. So won't show up in resutlt + "unknown_var": "newvalue", + + "variable1": "variable1 value from overrides", + "list_var": "list value coming from overrides" + } + + def test_with_no_additional_variables(self): + """ + Test assuming user has *not* passed any environment variables. Only AWS variables should be setup + """ + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + "AWS_REGION": "some region", + "AWS_DEFAULT_REGION": "some region", + "AWS_ACCESS_KEY_ID": "some key", + "AWS_SECRET_ACCESS_KEY": "some other secret", + "AWS_SESSION_TOKEN": "some other token" + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, aws_creds=self.aws_creds) + + result = environ.resolve() + + # With no additional environment variables, resolve() should just return all AWS variables + self.assertEquals(result, expected) + + def test_with_only_default_values_for_variables(self): + """ + Given only environment variable values, without any shell env values or overridden values + """ + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + "AWS_REGION": "us-east-1", + "AWS_ACCESS_KEY_ID": "defaultkey", + "AWS_SECRET_ACCESS_KEY": "defaultsecret", + + # This value is coming from user passed environment variable + "AWS_DEFAULT_REGION": "user-specified-region", + "variable1": "1", + "variable2": "mystring", + + "list_var": "", + "dict_var": "", + "none_var": "", + "true_var": "true", + "false_var": "false" + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, + variables=self.variables) + + self.assertEquals(environ.resolve(), expected) + + def test_with_shell_env_value(self): + """ + Given values for the variables from shell environment + """ + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + "AWS_REGION": "us-east-1", + "AWS_ACCESS_KEY_ID": "defaultkey", + "AWS_SECRET_ACCESS_KEY": "defaultsecret", + + # This value is coming from user passed environment variable + "AWS_DEFAULT_REGION": "user-specified-region", + + # Value coming from the shell + "variable1": "variable1 value from shell_env", + "variable2": "mystring", + + "list_var": "", + "dict_var": "", + "none_var": "", + "true_var": "true", + "false_var": "false" + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, + variables=self.variables, + shell_env_values=self.shell_env) + + self.assertEquals(environ.resolve(), expected) + + def test_with_overrides_value(self): + """ + Given values for the variables from user specified overrides + """ + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + "AWS_REGION": "us-east-1", + "AWS_ACCESS_KEY_ID": "defaultkey", + "AWS_SECRET_ACCESS_KEY": "defaultsecret", + + # This value is coming from user passed environment variable + "AWS_DEFAULT_REGION": "user-specified-region", + + "variable2": "mystring", + + # Value coming from the overrides + "variable1": "variable1 value from overrides", + "list_var": "list value coming from overrides", + + "dict_var": "", + "none_var": "", + "true_var": "true", + "false_var": "false" + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, + variables=self.variables, + shell_env_values=self.shell_env, + override_values=self.override) + + self.assertEquals(environ.resolve(), expected) + + +class TestEnvironmentVariables_get_aws_variables(TestCase): + + def setUp(self): + self.memory = 1024 + self.timeout = 123 + self.handler = "handler" + + self.aws_creds = { + "region": "some region", + "key": "some key", + "secret": "some other secret", + "sessiontoken": "some other token" + } + + def test_must_work_with_overridden_aws_creds(self): + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + "AWS_REGION": "some region", + "AWS_DEFAULT_REGION": "some region", + "AWS_ACCESS_KEY_ID": "some key", + "AWS_SECRET_ACCESS_KEY": "some other secret", + "AWS_SESSION_TOKEN": "some other token" + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, aws_creds=self.aws_creds) + + self.assertEquals(expected, environ._get_aws_variables()) + + def test_must_work_without_any_aws_creds(self): + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + + # Default values assigned to these variables + "AWS_REGION": "us-east-1", + "AWS_DEFAULT_REGION": "us-east-1", + "AWS_ACCESS_KEY_ID": "defaultkey", + "AWS_SECRET_ACCESS_KEY": "defaultsecret", + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler) + self.assertEquals(expected, environ._get_aws_variables()) + + def test_must_work_with_partial_aws_creds(self): + + creds = { + "region": "some other region", + "sessiontoken": "my awesome token" + } + + expected = { + "AWS_SAM_LOCAL": "true", + "AWS_LAMBDA_FUNCTION_MEMORY_SIZE": "1024", + "AWS_LAMBDA_FUNCTION_TIMEOUT": "123", + "AWS_LAMBDA_FUNCTION_HANDLER": "handler", + + # Values from the input creds + "AWS_REGION": "some other region", + "AWS_DEFAULT_REGION": "some other region", + "AWS_SESSION_TOKEN": "my awesome token", + + # These variables still get the default value + "AWS_ACCESS_KEY_ID": "defaultkey", + "AWS_SECRET_ACCESS_KEY": "defaultsecret", + } + + environ = EnvironmentVariables(self.memory, self.timeout, self.handler, aws_creds=creds) + self.assertEquals(expected, environ._get_aws_variables()) + + +class TestEnvironmentVariables_stringify_value(TestCase): + + def setUp(self): + + self.environ = EnvironmentVariables(1024, 10, "handler") + + @parameterized.expand([ + param([1, 2, 3]), + param({"a": {"b": "c"}}), + param(("this", "is", "tuple")), + param(None) + ]) + def test_must_replace_non_scalar_with_blank_values(self, input): + self.assertEquals("", self.environ._stringify_value(input)) + + @parameterized.expand([ + (True, "true"), + (False, "false"), + (1234, "1234"), + (3.14, "3.14"), + ("mystring", "mystring"), + ]) + def test_must_stringify(self, input, expected): + self.assertEquals(expected, self.environ._stringify_value(input)) + + +class TestEnvironmentVariables_add_lambda_event_body(TestCase): + + def test_must_add_proper_variable(self): + + value = "foobar" + + environ = EnvironmentVariables() + environ.add_lambda_event_body(value) + + self.assertEquals(environ.variables.get("AWS_LAMBDA_EVENT_BODY"), value) diff --git a/tests/unit/local/lambdafn/test_runtime.py b/tests/unit/local/lambdafn/test_runtime.py new file mode 100644 index 0000000000..f77716c8c2 --- /dev/null +++ b/tests/unit/local/lambdafn/test_runtime.py @@ -0,0 +1,358 @@ +""" +Unit tests for Lambda runtime +""" + +from unittest import TestCase +from mock import Mock, patch, MagicMock, ANY +from parameterized import parameterized + +from samcli.local.lambdafn.runtime import LambdaRuntime, _unzip_file +from samcli.local.lambdafn.config import FunctionConfig + + +class LambdaRuntime_invoke(TestCase): + + DEFAULT_MEMORY = 128 + DEFAULT_TIMEOUT = 3 + + def setUp(self): + + self.manager_mock = Mock() + + self.name = "name" + self.lang = "runtime" + self.handler = "handler" + self.code_path = "code-path" + self.func_config = FunctionConfig(self.name, self.lang, self.handler, self.code_path) + + self.env_vars = Mock() + self.func_config.env_vars = self.env_vars + self.env_var_value = {"a": "b"} + self.env_vars.resolve.return_value = self.env_var_value + + @patch("samcli.local.lambdafn.runtime.LambdaContainer") + def test_must_run_container_and_wait_for_logs(self, LambdaContainerMock): + event = "event" + debug_port = 123 + debug_arg = "abc" + code_dir = "some code dir" + stdout = "stdout" + stderr = "stderr" + container = Mock() + timer = Mock() + + self.runtime = LambdaRuntime(self.manager_mock) + + # Using MagicMock to mock the context manager + self.runtime._get_code_dir = MagicMock() + self.runtime._get_code_dir(self.code_path).__enter__.return_value = code_dir + + # Configure interrupt handler + self.runtime._configure_interrupt = Mock() + self.runtime._configure_interrupt.return_value = timer + + LambdaContainerMock.return_value = container + + self.runtime.invoke(self.func_config, + event, + debug_port=debug_port, + debug_args=debug_arg, + stdout=stdout, + stderr=stderr) + + # Verify if Lambda Event data is set + self.env_vars.add_lambda_event_body.assert_called_with(event) + + # Make sure env-vars get resolved + self.env_vars.resolve.assert_called_with() + + # Make sure the context manager is called to return the code directory + self.runtime._get_code_dir.assert_called_with(self.code_path) + + # Make sure the container is created with proper values + LambdaContainerMock.assert_called_with(self.lang, self.handler, code_dir, + memory_mb=self.DEFAULT_MEMORY, env_vars=self.env_var_value, + debug_port=debug_port, debug_args=debug_arg) + + # Run the container and get results + self.manager_mock.run.assert_called_with(container) + self.runtime._configure_interrupt.assert_called_with(self.name, self.DEFAULT_TIMEOUT, container, True) + container.wait_for_logs.assert_called_with(stdout=stdout, stderr=stderr) + + # Finally block + timer.cancel.assert_called_with() + self.manager_mock.stop.assert_called_with(container) + + @patch("samcli.local.lambdafn.runtime.LambdaContainer") + def test_exception_from_run_must_trigger_cleanup(self, LambdaContainerMock): + event = "event" + debug_port = 123 + debug_arg = "abc" + code_dir = "some code dir" + stdout = "stdout" + stderr = "stderr" + container = Mock() + timer = Mock() + + self.runtime = LambdaRuntime(self.manager_mock) + + # Using MagicMock to mock the context manager + self.runtime._get_code_dir = MagicMock() + self.runtime._get_code_dir(self.code_path).__enter__.return_value = code_dir + self.runtime._configure_interrupt = Mock() + self.runtime._configure_interrupt.return_value = timer + + LambdaContainerMock.return_value = container + + self.manager_mock.run.side_effect = ValueError("some exception") + + with self.assertRaises(ValueError): + self.runtime.invoke(self.func_config, + event, + debug_port=debug_port, + debug_args=debug_arg, + stdout=stdout, + stderr=stderr) + + # Run the container and get results + self.manager_mock.run.assert_called_with(container) + + self.runtime._configure_interrupt.assert_not_called() + + # Finally block must be called + # But timer was not yet created. It should not be called + timer.cancel.assert_not_called() + # In any case, stop the container + self.manager_mock.stop.assert_called_with(container) + + @patch("samcli.local.lambdafn.runtime.LambdaContainer") + def test_exception_from_wait_for_logs_must_trigger_cleanup(self, LambdaContainerMock): + event = "event" + debug_port = 123 + debug_arg = "abc" + code_dir = "some code dir" + stdout = "stdout" + stderr = "stderr" + container = Mock() + timer = Mock() + + self.runtime = LambdaRuntime(self.manager_mock) + + # Using MagicMock to mock the context manager + self.runtime._get_code_dir = MagicMock() + self.runtime._get_code_dir(self.code_path).__enter__.return_value = code_dir + self.runtime._configure_interrupt = Mock() + self.runtime._configure_interrupt.return_value = timer + + LambdaContainerMock.return_value = container + + container.wait_for_logs.side_effect = ValueError("some exception") + + with self.assertRaises(ValueError): + self.runtime.invoke(self.func_config, + event, + debug_port=debug_port, + debug_args=debug_arg, + stdout=stdout, + stderr=stderr) + + # Run the container and get results + self.manager_mock.run.assert_called_with(container) + + self.runtime._configure_interrupt.assert_called_with(self.name, self.DEFAULT_TIMEOUT, container, True) + + # Finally block must be called + # Timer was created. So it must be cancelled + timer.cancel.assert_called_with() + # In any case, stop the container + self.manager_mock.stop.assert_called_with(container) + + @patch("samcli.local.lambdafn.runtime.LambdaContainer") + def test_keyboard_interrupt_must_not_raise(self, LambdaContainerMock): + event = "event" + debug_port = 123 + debug_arg = "abc" + code_dir = "some code dir" + stdout = "stdout" + stderr = "stderr" + container = Mock() + + self.runtime = LambdaRuntime(self.manager_mock) + + # Using MagicMock to mock the context manager + self.runtime._get_code_dir = MagicMock() + self.runtime._get_code_dir(self.code_path).__enter__.return_value = code_dir + self.runtime._configure_interrupt = Mock() + + LambdaContainerMock.return_value = container + + self.manager_mock.run.side_effect = KeyboardInterrupt("some exception") + + self.runtime.invoke(self.func_config, + event, + debug_port=debug_port, + debug_args=debug_arg, + stdout=stdout, + stderr=stderr) + + # Run the container and get results + self.manager_mock.run.assert_called_with(container) + + self.runtime._configure_interrupt.assert_not_called() + + # Finally block must be called + self.manager_mock.stop.assert_called_with(container) + + +class TestLambdaRuntime_configure_interrupt(TestCase): + + def setUp(self): + self.name = "name" + self.timeout = 123 + self.container = Mock() + + self.manager_mock = Mock() + self.runtime = LambdaRuntime(self.manager_mock) + + @patch("samcli.local.lambdafn.runtime.threading") + @patch("samcli.local.lambdafn.runtime.signal") + def test_must_setup_timer(self, SignalMock, ThreadingMock): + is_debugging = False # We are not debugging. So setup timer + timer_obj = Mock() + ThreadingMock.Timer.return_value = timer_obj + + result = self.runtime._configure_interrupt(self.name, self.timeout, self.container, is_debugging) + + self.assertEquals(result, timer_obj) + + ThreadingMock.Timer.assert_called_with(self.timeout, ANY, ()) + timer_obj.start.assert_called_with() + + SignalMock.signal.assert_not_called() # must not setup signal handler + + @patch("samcli.local.lambdafn.runtime.threading") + @patch("samcli.local.lambdafn.runtime.signal") + def test_must_setup_signal_handler(self, SignalMock, ThreadingMock): + is_debugging = True # We are debugging. So setup signal + SignalMock.SIGTERM = sigterm = "sigterm" + + result = self.runtime._configure_interrupt(self.name, self.timeout, self.container, is_debugging) + + self.assertIsNone(result, "There are no return values when setting up signal handler") + + SignalMock.signal.assert_called_with(sigterm, ANY) + ThreadingMock.Timer.signal.assert_not_called() # must not setup timer + + @patch("samcli.local.lambdafn.runtime.threading") + @patch("samcli.local.lambdafn.runtime.signal") + def test_verify_signal_handler(self, SignalMock, ThreadingMock): + """ + Verify the internal implementation of the Signal Handler + """ + is_debugging = True # We are debugging. So setup signal + SignalMock.SIGTERM = "sigterm" + + # Fake the real method with a Lambda. Also run the handler immediately. + SignalMock.signal = lambda term, handler: handler("a", "b") + + self.runtime._configure_interrupt(self.name, self.timeout, self.container, is_debugging) + + # This method should be called from within the Signal Handler + self.manager_mock.stop.assert_called_with(self.container) + + @patch("samcli.local.lambdafn.runtime.threading") + @patch("samcli.local.lambdafn.runtime.signal") + def test_verify_timer_handler(self, SignalMock, ThreadingMock): + """ + Verify the internal implementation of the Signal Handler + """ + is_debugging = False + + def fake_timer(timeout, handler, args): + handler() + return Mock() + + # Fake the real method with a Lambda. Also run the handler immediately. + ThreadingMock.Timer = fake_timer + + self.runtime._configure_interrupt(self.name, self.timeout, self.container, is_debugging) + + # This method should be called from within the Timer Handler + self.manager_mock.stop.assert_called_with(self.container) + + +class TestLambdaRuntime_get_code_dir(TestCase): + + def setUp(self): + self.manager_mock = Mock() + self.runtime = LambdaRuntime(self.manager_mock) + + @parameterized.expand([ + (".zip"), + (".ZIP"), + (".JAR"), + (".jar") + ]) + @patch("samcli.local.lambdafn.runtime.os") + @patch("samcli.local.lambdafn.runtime.shutil") + @patch("samcli.local.lambdafn.runtime._unzip_file") + def test_must_uncompress_zip_files(self, extension, unzip_file_mock, shutil_mock, os_mock): + code_path = "foo" + extension + decompressed_dir = "decompressed-dir" + + unzip_file_mock.return_value = decompressed_dir + os_mock.path.isfile.return_value = True + + with self.runtime._get_code_dir(code_path) as result: + self.assertEquals(result, decompressed_dir) + + unzip_file_mock.assert_called_with(code_path) + os_mock.path.isfile.assert_called_with(code_path) + + # Finally block must call this after the context manager exists + shutil_mock.rmtree.assert_called_with(decompressed_dir) + + @patch("samcli.local.lambdafn.runtime.os") + @patch("samcli.local.lambdafn.runtime.shutil") + @patch("samcli.local.lambdafn.runtime._unzip_file") + def test_must_return_a_valid_file(self, unzip_file_mock, shutil_mock, os_mock): + """ + Input is a file that exists, but is not a zip/jar file + """ + code_path = "foo.exe" + + os_mock.path.isfile.return_value = True + + with self.runtime._get_code_dir(code_path) as result: + # code path must be returned. No decompression + self.assertEquals(result, code_path) + + unzip_file_mock.assert_not_called() # Unzip must not be called + os_mock.path.isfile.assert_called_with(code_path) + + # Because we never unzipped anything, we should never delete + shutil_mock.rmtree.assert_not_called() + + +class TestUnzipFile(TestCase): + + @patch("samcli.local.lambdafn.runtime.tempfile") + @patch("samcli.local.lambdafn.runtime.zipfile") + @patch("samcli.local.lambdafn.runtime.os") + def test_must_unzip(self, os_mock, zipfile_mock, tempfile_mock): + inputpath = "somepath" + tmpdir = "/tmp/dir" + realpath = "/foo/bar/tmp/dir/code.zip" + zipref = Mock() + + tempfile_mock.mkdtemp.return_value = tmpdir + zipfile_mock.ZipFile.return_value = zipref + os_mock.path.realpath.return_value = realpath + + output = _unzip_file(inputpath) + self.assertEquals(output, realpath) + + tempfile_mock.mkdtemp.assert_called_with() + zipfile_mock.ZipFile.assert_called_with(inputpath, 'r') # Open file for reading + zipref.extractall.assert_called_with(tmpdir) # unzip files to temporary directory + os_mock.path.realpath(tmpdir) # Return the real path of temporary directory diff --git a/tests/unit/test_yamlhelper.py b/tests/unit/test_yamlhelper.py new file mode 100644 index 0000000000..32adb6c72a --- /dev/null +++ b/tests/unit/test_yamlhelper.py @@ -0,0 +1,80 @@ +""" +Helper to be able to parse/dump YAML files +""" + +from unittest import TestCase +from samcli.yamlhelper import yaml_parse, yaml_dump + + +class TestYaml(TestCase): + + yaml_with_tags = """ + Resource: + Key1: !Ref Something + Key2: !GetAtt Another.Arn + Key3: !FooBar [!Baz YetAnother, "hello"] + Key4: !SomeTag {"a": "1"} + Key5: !GetAtt OneMore.Outputs.Arn + Key6: !Condition OtherCondition + """ + + parsed_yaml_dict = { + "Resource": { + "Key1": { + "Ref": "Something" + }, + "Key2": { + "Fn::GetAtt": ["Another", "Arn"] + }, + "Key3": { + "Fn::FooBar": [ + {"Fn::Baz": "YetAnother"}, + "hello" + ] + }, + "Key4": { + "Fn::SomeTag": { + "a": "1" + } + }, + "Key5": { + "Fn::GetAtt": ["OneMore", "Outputs.Arn"] + }, + "Key6": { + "Condition": "OtherCondition" + } + } + } + + def test_yaml_with_tags(self): + output = yaml_parse(self.yaml_with_tags) + self.assertEquals(self.parsed_yaml_dict, output) + + # Make sure formatter and parser work well with each other + formatted_str = yaml_dump(output) + output_again = yaml_parse(formatted_str) + self.assertEquals(output, output_again) + + def test_yaml_getatt(self): + # This is an invalid syntax for !GetAtt. But make sure the code does not crash when we encouter this syntax + # Let CloudFormation interpret this value at runtime + input = """ + Resource: + Key: !GetAtt ["a", "b"] + """ + + output = { + "Resource": { + "Key": { + "Fn::GetAtt": ["a", "b"] + } + } + } + + actual_output = yaml_parse(input) + self.assertEquals(actual_output, output) + + def test_parse_json_with_tabs(self): + template = '{\n\t"foo": "bar"\n}' + output = yaml_parse(template) + self.assertEqual(output, {'foo': 'bar'}) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000000..079492e903 --- /dev/null +++ b/tox.ini @@ -0,0 +1,11 @@ +# tox (https://tox.readthedocs.io/) is a tool for running tests +# in multiple virtualenvs. This configuration file will run the +# test suite on all supported python versions. To use it, "pip install tox" +# and then run "tox" from this directory. + +[tox] +envlist = py27 + +[testenv] +whitelist_externals = make +commands = make pr diff --git a/validate.go b/validate.go deleted file mode 100644 index 9123e6925d..0000000000 --- a/validate.go +++ /dev/null @@ -1,23 +0,0 @@ -package main - -import ( - "fmt" - "os" - - "github.com/awslabs/goformation" - "github.com/codegangsta/cli" -) - -func validate(c *cli.Context) { - - _, err := goformation.Open(getTemplateFilename(c.String("template"))) - - if err != nil { - fmt.Fprintf(os.Stderr, "%s\n", err) - os.Exit(1) - } - - fmt.Fprintf(os.Stderr, "Valid!\n") - os.Exit(0) - -} diff --git a/validate_test.go b/validate_test.go deleted file mode 100644 index 91940327ce..0000000000 --- a/validate_test.go +++ /dev/null @@ -1,232 +0,0 @@ -package main - -import ( - "github.com/awslabs/goformation" - . "github.com/onsi/ginkgo" - . "github.com/onsi/gomega" - . "github.com/onsi/gomega/gstruct" -) - -var _ = Describe("sam", func() { - Describe("validate", func() { - - Context("with the official AWS SAM example templates", func() { - - inputs := []string{ - "test/templates/sam-official-samples/alexa_skill/template.yaml", - "test/templates/sam-official-samples/api_backend/template.yaml", - "test/templates/sam-official-samples/api_swagger_cors/template.yaml", - "test/templates/sam-official-samples/encryption_proxy/template.yaml", - "test/templates/sam-official-samples/hello_world/template.yaml", - "test/templates/sam-official-samples/inline_swagger/template.yaml", - "test/templates/sam-official-samples/iot_backend/template.yaml", - "test/templates/sam-official-samples/s3_processor/template.yaml", - "test/templates/sam-official-samples/schedule/template.yaml", - "test/templates/sam-official-samples/stream_processor/template.yaml", - } - - for _, filename := range inputs { - Context("including "+filename, func() { - template, err := goformation.Open(filename) - It("should successfully validate the SAM template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - }) - } - - }) - - Context("with the default AWS CodeStar templates", func() { - - inputs := []string{ - "test/templates/codestar/nodejs.yml", - "test/templates/codestar/python.yml", - "test/templates/codestar/java.yml", - } - - for _, filename := range inputs { - Context("including "+filename, func() { - template, err := goformation.Open(filename) - It("should successfully validate the SAM template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - }) - } - }) - - Context("with a Serverless template containing different CodeUri formats", func() { - - template, err := goformation.Open("test/templates/aws-common-string-or-s3-location.yaml") - It("should successfully parse the template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - - functions := template.GetAllAWSServerlessFunctionResources() - - It("should have exactly three functions", func() { - Expect(functions).To(HaveLen(3)) - Expect(functions).To(HaveKey("CodeUriWithS3LocationSpecifiedAsString")) - Expect(functions).To(HaveKey("CodeUriWithS3LocationSpecifiedAsObject")) - Expect(functions).To(HaveKey("CodeUriWithString")) - }) - - f1 := functions["CodeUriWithS3LocationSpecifiedAsString"] - It("should parse a CodeUri property with an S3 location specified as a string", func() { - Expect(f1.CodeUri.String).To(PointTo(Equal("s3://testbucket/testkey.zip"))) - }) - - f2 := functions["CodeUriWithS3LocationSpecifiedAsObject"] - It("should parse a CodeUri property with an S3 location specified as an object", func() { - Expect(f2.CodeUri.S3Location.Bucket).To(Equal("testbucket")) - Expect(f2.CodeUri.S3Location.Key).To(Equal("testkey.zip")) - Expect(f2.CodeUri.S3Location.Version).To(Equal(5)) - }) - - f3 := functions["CodeUriWithString"] - It("should parse a CodeUri property with a string", func() { - Expect(f3.CodeUri.String).To(PointTo(Equal("./testfolder"))) - }) - - }) - - Context("with a Serverless template containing function environment variables", func() { - - template, err := goformation.Open("test/templates/function-environment-variables.yaml") - It("should successfully parse the template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - - functions := template.GetAllAWSServerlessFunctionResources() - - It("should have exactly one function", func() { - Expect(functions).To(HaveLen(5)) - Expect(functions).To(HaveKey("EnvironmentVariableTestFunction")) - Expect(functions).To(HaveKey("IntrinsicEnvironmentVariableTestFunction")) - Expect(functions).To(HaveKey("NoValueEnvironmentVariableTestFunction")) - Expect(functions).To(HaveKey("SubEnvironmentVariableTestFunction")) - Expect(functions).To(HaveKey("NonExistSubEnvironmentVariableTestFunction")) - }) - - f1 := functions["EnvironmentVariableTestFunction"] - Context("with a simple string based variable", func() { - It("should have an environment variable named STRING_ENV_VAR", func() { - Expect(f1.Environment).ToNot(BeNil()) - Expect(f1.Environment.Variables).ToNot(BeNil()) - Expect(f1.Environment.Variables).To(HaveLen(1)) - Expect(f1.Environment.Variables).To(HaveKeyWithValue("STRING_ENV_VAR", "test123")) - }) - }) - - f2 := functions["NoValueEnvironmentVariableTestFunction"] - Context("with an empty variable value", func() { - It("should have an environment variable named EMPTY_ENV_VAR", func() { - Expect(f2.Environment).ToNot(BeNil()) - Expect(f2.Environment.Variables).ToNot(BeNil()) - Expect(f2.Environment.Variables).To(HaveLen(1)) - Expect(f2.Environment.Variables).To(HaveKeyWithValue("EMPTY_ENV_VAR", "")) - }) - }) - - f3 := functions["IntrinsicEnvironmentVariableTestFunction"] - Context("with a !Ref lookup variable", func() { - It("should have an environment variable named REF_ENV_VAR", func() { - Expect(f3.Environment).ToNot(BeNil()) - Expect(f3.Environment.Variables).ToNot(BeNil()) - Expect(f3.Environment.Variables).To(HaveLen(1)) - Expect(f3.Environment.Variables).To(HaveKeyWithValue("REF_ENV_VAR", "SomeValue")) - }) - }) - - f4 := functions["SubEnvironmentVariableTestFunction"] - Context("with a !Sub variable value", func() { - It("should have an environment variable named SUB_ENV_VAR", func() { - Expect(f4.Environment).ToNot(BeNil()) - Expect(f4.Environment.Variables).ToNot(BeNil()) - Expect(f4.Environment.Variables).To(HaveLen(1)) - Expect(f4.Environment.Variables).To(HaveKeyWithValue("SUB_ENV_VAR", "Hello")) - }) - }) - - f5 := functions["NonExistSubEnvironmentVariableTestFunction"] - Context("with a !Sub variable value that contains a non-existant reference", func() { - It("should have an environment variable named SUB_REF_ENV_VAR", func() { - Expect(f5.Environment).ToNot(BeNil()) - Expect(f5.Environment.Variables).ToNot(BeNil()) - Expect(f5.Environment.Variables).To(HaveLen(1)) - Expect(f5.Environment.Variables).To(HaveKeyWithValue("SUB_REF_ENV_VAR", "Hello-")) - }) - }) - - }) - - Context("with a Serverless function matching 2016-10-31 specification", func() { - - template, err := goformation.Open("test/templates/function-2016-10-31.yaml") - It("should successfully validate the SAM template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - - functions := template.GetAllAWSServerlessFunctionResources() - - It("should have exactly one function", func() { - Expect(functions).To(HaveLen(1)) - Expect(functions).To(HaveKey("Function20161031")) - }) - - f := functions["Function20161031"] - - It("should correctly parse all of the function properties", func() { - - Expect(f.Handler).To(Equal("file.method")) - Expect(f.Runtime).To(Equal("nodejs")) - Expect(f.FunctionName).To(Equal("functionname")) - Expect(f.Description).To(Equal("description")) - Expect(f.MemorySize).To(Equal(128)) - Expect(f.Timeout).To(Equal(30)) - Expect(f.Role).To(Equal("aws::arn::123456789012::some/role")) - Expect(f.Policies.StringArray).To(PointTo(ContainElement("AmazonDynamoDBFullAccess"))) - Expect(f.Environment).ToNot(BeNil()) - Expect(f.Environment.Variables).To(HaveKeyWithValue("NAME", "VALUE")) - - }) - - It("should correctly parse all of the function API event sources/endpoints", func() { - - Expect(f.Events).ToNot(BeNil()) - Expect(f.Events).To(HaveKey("TestApi")) - Expect(f.Events["TestApi"].Type).To(Equal("Api")) - Expect(f.Events["TestApi"].Properties.ApiEvent).ToNot(BeNil()) - - event := f.Events["TestApi"].Properties.ApiEvent - Expect(event.Method).To(Equal("any")) - Expect(event.Path).To(Equal("/testing")) - - }) - - }) - - Context("with non-resource sections in CloudFormation template", func() { - - inputs := []string{ - "test/templates/output_section.yaml", - } - - for _, filename := range inputs { - Context("including "+filename, func() { - template, err := goformation.Open(filename) - It("should successfully validate the SAM template", func() { - Expect(err).To(BeNil()) - Expect(template).ShouldNot(BeNil()) - }) - }) - } - - }) - - }) -}) diff --git a/vendor/github.com/Azure/go-ansiterm/LICENSE b/vendor/github.com/Azure/go-ansiterm/LICENSE deleted file mode 100644 index e3d9a64d1d..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft Corporation - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/Azure/go-ansiterm/README.md b/vendor/github.com/Azure/go-ansiterm/README.md deleted file mode 100644 index 261c041e7a..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# go-ansiterm - -This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent. - -For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position. - -The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go). - -See parser_test.go for examples exercising the state machine and generating appropriate function calls. - ------ -This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/vendor/github.com/Azure/go-ansiterm/constants.go b/vendor/github.com/Azure/go-ansiterm/constants.go deleted file mode 100644 index 96504a33bc..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/constants.go +++ /dev/null @@ -1,188 +0,0 @@ -package ansiterm - -const LogEnv = "DEBUG_TERMINAL" - -// ANSI constants -// References: -// -- http://www.ecma-international.org/publications/standards/Ecma-048.htm -// -- http://man7.org/linux/man-pages/man4/console_codes.4.html -// -- http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html -// -- http://en.wikipedia.org/wiki/ANSI_escape_code -// -- http://vt100.net/emu/dec_ansi_parser -// -- http://vt100.net/emu/vt500_parser.svg -// -- http://invisible-island.net/xterm/ctlseqs/ctlseqs.html -// -- http://www.inwap.com/pdp10/ansicode.txt -const ( - // ECMA-48 Set Graphics Rendition - // Note: - // -- Constants leading with an underscore (e.g., _ANSI_xxx) are unsupported or reserved - // -- Fonts could possibly be supported via SetCurrentConsoleFontEx - // -- Windows does not expose the per-window cursor (i.e., caret) blink times - ANSI_SGR_RESET = 0 - ANSI_SGR_BOLD = 1 - ANSI_SGR_DIM = 2 - _ANSI_SGR_ITALIC = 3 - ANSI_SGR_UNDERLINE = 4 - _ANSI_SGR_BLINKSLOW = 5 - _ANSI_SGR_BLINKFAST = 6 - ANSI_SGR_REVERSE = 7 - _ANSI_SGR_INVISIBLE = 8 - _ANSI_SGR_LINETHROUGH = 9 - _ANSI_SGR_FONT_00 = 10 - _ANSI_SGR_FONT_01 = 11 - _ANSI_SGR_FONT_02 = 12 - _ANSI_SGR_FONT_03 = 13 - _ANSI_SGR_FONT_04 = 14 - _ANSI_SGR_FONT_05 = 15 - _ANSI_SGR_FONT_06 = 16 - _ANSI_SGR_FONT_07 = 17 - _ANSI_SGR_FONT_08 = 18 - _ANSI_SGR_FONT_09 = 19 - _ANSI_SGR_FONT_10 = 20 - _ANSI_SGR_DOUBLEUNDERLINE = 21 - ANSI_SGR_BOLD_DIM_OFF = 22 - _ANSI_SGR_ITALIC_OFF = 23 - ANSI_SGR_UNDERLINE_OFF = 24 - _ANSI_SGR_BLINK_OFF = 25 - _ANSI_SGR_RESERVED_00 = 26 - ANSI_SGR_REVERSE_OFF = 27 - _ANSI_SGR_INVISIBLE_OFF = 28 - _ANSI_SGR_LINETHROUGH_OFF = 29 - ANSI_SGR_FOREGROUND_BLACK = 30 - ANSI_SGR_FOREGROUND_RED = 31 - ANSI_SGR_FOREGROUND_GREEN = 32 - ANSI_SGR_FOREGROUND_YELLOW = 33 - ANSI_SGR_FOREGROUND_BLUE = 34 - ANSI_SGR_FOREGROUND_MAGENTA = 35 - ANSI_SGR_FOREGROUND_CYAN = 36 - ANSI_SGR_FOREGROUND_WHITE = 37 - _ANSI_SGR_RESERVED_01 = 38 - ANSI_SGR_FOREGROUND_DEFAULT = 39 - ANSI_SGR_BACKGROUND_BLACK = 40 - ANSI_SGR_BACKGROUND_RED = 41 - ANSI_SGR_BACKGROUND_GREEN = 42 - ANSI_SGR_BACKGROUND_YELLOW = 43 - ANSI_SGR_BACKGROUND_BLUE = 44 - ANSI_SGR_BACKGROUND_MAGENTA = 45 - ANSI_SGR_BACKGROUND_CYAN = 46 - ANSI_SGR_BACKGROUND_WHITE = 47 - _ANSI_SGR_RESERVED_02 = 48 - ANSI_SGR_BACKGROUND_DEFAULT = 49 - // 50 - 65: Unsupported - - ANSI_MAX_CMD_LENGTH = 4096 - - MAX_INPUT_EVENTS = 128 - DEFAULT_WIDTH = 80 - DEFAULT_HEIGHT = 24 - - ANSI_BEL = 0x07 - ANSI_BACKSPACE = 0x08 - ANSI_TAB = 0x09 - ANSI_LINE_FEED = 0x0A - ANSI_VERTICAL_TAB = 0x0B - ANSI_FORM_FEED = 0x0C - ANSI_CARRIAGE_RETURN = 0x0D - ANSI_ESCAPE_PRIMARY = 0x1B - ANSI_ESCAPE_SECONDARY = 0x5B - ANSI_OSC_STRING_ENTRY = 0x5D - ANSI_COMMAND_FIRST = 0x40 - ANSI_COMMAND_LAST = 0x7E - DCS_ENTRY = 0x90 - CSI_ENTRY = 0x9B - OSC_STRING = 0x9D - ANSI_PARAMETER_SEP = ";" - ANSI_CMD_G0 = '(' - ANSI_CMD_G1 = ')' - ANSI_CMD_G2 = '*' - ANSI_CMD_G3 = '+' - ANSI_CMD_DECPNM = '>' - ANSI_CMD_DECPAM = '=' - ANSI_CMD_OSC = ']' - ANSI_CMD_STR_TERM = '\\' - - KEY_CONTROL_PARAM_2 = ";2" - KEY_CONTROL_PARAM_3 = ";3" - KEY_CONTROL_PARAM_4 = ";4" - KEY_CONTROL_PARAM_5 = ";5" - KEY_CONTROL_PARAM_6 = ";6" - KEY_CONTROL_PARAM_7 = ";7" - KEY_CONTROL_PARAM_8 = ";8" - KEY_ESC_CSI = "\x1B[" - KEY_ESC_N = "\x1BN" - KEY_ESC_O = "\x1BO" - - FILL_CHARACTER = ' ' -) - -func getByteRange(start byte, end byte) []byte { - bytes := make([]byte, 0, 32) - for i := start; i <= end; i++ { - bytes = append(bytes, byte(i)) - } - - return bytes -} - -var toGroundBytes = getToGroundBytes() -var executors = getExecuteBytes() - -// SPACE 20+A0 hex Always and everywhere a blank space -// Intermediate 20-2F hex !"#$%&'()*+,-./ -var intermeds = getByteRange(0x20, 0x2F) - -// Parameters 30-3F hex 0123456789:;<=>? -// CSI Parameters 30-39, 3B hex 0123456789; -var csiParams = getByteRange(0x30, 0x3F) - -var csiCollectables = append(getByteRange(0x30, 0x39), getByteRange(0x3B, 0x3F)...) - -// Uppercase 40-5F hex @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_ -var upperCase = getByteRange(0x40, 0x5F) - -// Lowercase 60-7E hex `abcdefghijlkmnopqrstuvwxyz{|}~ -var lowerCase = getByteRange(0x60, 0x7E) - -// Alphabetics 40-7E hex (all of upper and lower case) -var alphabetics = append(upperCase, lowerCase...) - -var printables = getByteRange(0x20, 0x7F) - -var escapeIntermediateToGroundBytes = getByteRange(0x30, 0x7E) -var escapeToGroundBytes = getEscapeToGroundBytes() - -// See http://www.vt100.net/emu/vt500_parser.png for description of the complex -// byte ranges below - -func getEscapeToGroundBytes() []byte { - escapeToGroundBytes := getByteRange(0x30, 0x4F) - escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x51, 0x57)...) - escapeToGroundBytes = append(escapeToGroundBytes, 0x59) - escapeToGroundBytes = append(escapeToGroundBytes, 0x5A) - escapeToGroundBytes = append(escapeToGroundBytes, 0x5C) - escapeToGroundBytes = append(escapeToGroundBytes, getByteRange(0x60, 0x7E)...) - return escapeToGroundBytes -} - -func getExecuteBytes() []byte { - executeBytes := getByteRange(0x00, 0x17) - executeBytes = append(executeBytes, 0x19) - executeBytes = append(executeBytes, getByteRange(0x1C, 0x1F)...) - return executeBytes -} - -func getToGroundBytes() []byte { - groundBytes := []byte{0x18} - groundBytes = append(groundBytes, 0x1A) - groundBytes = append(groundBytes, getByteRange(0x80, 0x8F)...) - groundBytes = append(groundBytes, getByteRange(0x91, 0x97)...) - groundBytes = append(groundBytes, 0x99) - groundBytes = append(groundBytes, 0x9A) - groundBytes = append(groundBytes, 0x9C) - return groundBytes -} - -// Delete 7F hex Always and everywhere ignored -// C1 Control 80-9F hex 32 additional control characters -// G1 Displayable A1-FE hex 94 additional displayable characters -// Special A0+FF hex Same as SPACE and DELETE diff --git a/vendor/github.com/Azure/go-ansiterm/context.go b/vendor/github.com/Azure/go-ansiterm/context.go deleted file mode 100644 index 8d66e777c0..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/context.go +++ /dev/null @@ -1,7 +0,0 @@ -package ansiterm - -type ansiContext struct { - currentChar byte - paramBuffer []byte - interBuffer []byte -} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go b/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go deleted file mode 100644 index 1bd6057da8..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/csi_entry_state.go +++ /dev/null @@ -1,49 +0,0 @@ -package ansiterm - -type csiEntryState struct { - baseState -} - -func (csiState csiEntryState) Handle(b byte) (s state, e error) { - logger.Infof("CsiEntry::Handle %#x", b) - - nextState, err := csiState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(alphabetics, b): - return csiState.parser.ground, nil - case sliceContains(csiCollectables, b): - return csiState.parser.csiParam, nil - case sliceContains(executors, b): - return csiState, csiState.parser.execute() - } - - return csiState, nil -} - -func (csiState csiEntryState) Transition(s state) error { - logger.Infof("CsiEntry::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) - - switch s { - case csiState.parser.ground: - return csiState.parser.csiDispatch() - case csiState.parser.csiParam: - switch { - case sliceContains(csiParams, csiState.parser.context.currentChar): - csiState.parser.collectParam() - case sliceContains(intermeds, csiState.parser.context.currentChar): - csiState.parser.collectInter() - } - } - - return nil -} - -func (csiState csiEntryState) Enter() error { - csiState.parser.clear() - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go b/vendor/github.com/Azure/go-ansiterm/csi_param_state.go deleted file mode 100644 index 4be35c5fd2..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/csi_param_state.go +++ /dev/null @@ -1,38 +0,0 @@ -package ansiterm - -type csiParamState struct { - baseState -} - -func (csiState csiParamState) Handle(b byte) (s state, e error) { - logger.Infof("CsiParam::Handle %#x", b) - - nextState, err := csiState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(alphabetics, b): - return csiState.parser.ground, nil - case sliceContains(csiCollectables, b): - csiState.parser.collectParam() - return csiState, nil - case sliceContains(executors, b): - return csiState, csiState.parser.execute() - } - - return csiState, nil -} - -func (csiState csiParamState) Transition(s state) error { - logger.Infof("CsiParam::Transition %s --> %s", csiState.Name(), s.Name()) - csiState.baseState.Transition(s) - - switch s { - case csiState.parser.ground: - return csiState.parser.csiDispatch() - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go b/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go deleted file mode 100644 index 2189eb6b6b..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/escape_intermediate_state.go +++ /dev/null @@ -1,36 +0,0 @@ -package ansiterm - -type escapeIntermediateState struct { - baseState -} - -func (escState escapeIntermediateState) Handle(b byte) (s state, e error) { - logger.Infof("escapeIntermediateState::Handle %#x", b) - nextState, err := escState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(intermeds, b): - return escState, escState.parser.collectInter() - case sliceContains(executors, b): - return escState, escState.parser.execute() - case sliceContains(escapeIntermediateToGroundBytes, b): - return escState.parser.ground, nil - } - - return escState, nil -} - -func (escState escapeIntermediateState) Transition(s state) error { - logger.Infof("escapeIntermediateState::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) - - switch s { - case escState.parser.ground: - return escState.parser.escDispatch() - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/escape_state.go b/vendor/github.com/Azure/go-ansiterm/escape_state.go deleted file mode 100644 index 7b1b9ad3f1..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/escape_state.go +++ /dev/null @@ -1,47 +0,0 @@ -package ansiterm - -type escapeState struct { - baseState -} - -func (escState escapeState) Handle(b byte) (s state, e error) { - logger.Infof("escapeState::Handle %#x", b) - nextState, err := escState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case b == ANSI_ESCAPE_SECONDARY: - return escState.parser.csiEntry, nil - case b == ANSI_OSC_STRING_ENTRY: - return escState.parser.oscString, nil - case sliceContains(executors, b): - return escState, escState.parser.execute() - case sliceContains(escapeToGroundBytes, b): - return escState.parser.ground, nil - case sliceContains(intermeds, b): - return escState.parser.escapeIntermediate, nil - } - - return escState, nil -} - -func (escState escapeState) Transition(s state) error { - logger.Infof("Escape::Transition %s --> %s", escState.Name(), s.Name()) - escState.baseState.Transition(s) - - switch s { - case escState.parser.ground: - return escState.parser.escDispatch() - case escState.parser.escapeIntermediate: - return escState.parser.collectInter() - } - - return nil -} - -func (escState escapeState) Enter() error { - escState.parser.clear() - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/event_handler.go b/vendor/github.com/Azure/go-ansiterm/event_handler.go deleted file mode 100644 index 98087b38c2..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/event_handler.go +++ /dev/null @@ -1,90 +0,0 @@ -package ansiterm - -type AnsiEventHandler interface { - // Print - Print(b byte) error - - // Execute C0 commands - Execute(b byte) error - - // CUrsor Up - CUU(int) error - - // CUrsor Down - CUD(int) error - - // CUrsor Forward - CUF(int) error - - // CUrsor Backward - CUB(int) error - - // Cursor to Next Line - CNL(int) error - - // Cursor to Previous Line - CPL(int) error - - // Cursor Horizontal position Absolute - CHA(int) error - - // Vertical line Position Absolute - VPA(int) error - - // CUrsor Position - CUP(int, int) error - - // Horizontal and Vertical Position (depends on PUM) - HVP(int, int) error - - // Text Cursor Enable Mode - DECTCEM(bool) error - - // Origin Mode - DECOM(bool) error - - // 132 Column Mode - DECCOLM(bool) error - - // Erase in Display - ED(int) error - - // Erase in Line - EL(int) error - - // Insert Line - IL(int) error - - // Delete Line - DL(int) error - - // Insert Character - ICH(int) error - - // Delete Character - DCH(int) error - - // Set Graphics Rendition - SGR([]int) error - - // Pan Down - SU(int) error - - // Pan Up - SD(int) error - - // Device Attributes - DA([]string) error - - // Set Top and Bottom Margins - DECSTBM(int, int) error - - // Index - IND() error - - // Reverse Index - RI() error - - // Flush updates from previous commands - Flush() error -} diff --git a/vendor/github.com/Azure/go-ansiterm/ground_state.go b/vendor/github.com/Azure/go-ansiterm/ground_state.go deleted file mode 100644 index 52451e9469..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/ground_state.go +++ /dev/null @@ -1,24 +0,0 @@ -package ansiterm - -type groundState struct { - baseState -} - -func (gs groundState) Handle(b byte) (s state, e error) { - gs.parser.context.currentChar = b - - nextState, err := gs.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case sliceContains(printables, b): - return gs, gs.parser.print() - - case sliceContains(executors, b): - return gs, gs.parser.execute() - } - - return gs, nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go b/vendor/github.com/Azure/go-ansiterm/osc_string_state.go deleted file mode 100644 index 24062d420e..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/osc_string_state.go +++ /dev/null @@ -1,31 +0,0 @@ -package ansiterm - -type oscStringState struct { - baseState -} - -func (oscState oscStringState) Handle(b byte) (s state, e error) { - logger.Infof("OscString::Handle %#x", b) - nextState, err := oscState.baseState.Handle(b) - if nextState != nil || err != nil { - return nextState, err - } - - switch { - case isOscStringTerminator(b): - return oscState.parser.ground, nil - } - - return oscState, nil -} - -// See below for OSC string terminators for linux -// http://man7.org/linux/man-pages/man4/console_codes.4.html -func isOscStringTerminator(b byte) bool { - - if b == ANSI_BEL || b == 0x5C { - return true - } - - return false -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser.go b/vendor/github.com/Azure/go-ansiterm/parser.go deleted file mode 100644 index 169f68dbef..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser.go +++ /dev/null @@ -1,136 +0,0 @@ -package ansiterm - -import ( - "errors" - "io/ioutil" - "os" - - "github.com/Sirupsen/logrus" -) - -var logger *logrus.Logger - -type AnsiParser struct { - currState state - eventHandler AnsiEventHandler - context *ansiContext - csiEntry state - csiParam state - dcsEntry state - escape state - escapeIntermediate state - error state - ground state - oscString state - stateMap []state -} - -func CreateParser(initialState string, evtHandler AnsiEventHandler) *AnsiParser { - logFile := ioutil.Discard - - if isDebugEnv := os.Getenv(LogEnv); isDebugEnv == "1" { - logFile, _ = os.Create("ansiParser.log") - } - - logger = &logrus.Logger{ - Out: logFile, - Formatter: new(logrus.TextFormatter), - Level: logrus.InfoLevel, - } - - parser := &AnsiParser{ - eventHandler: evtHandler, - context: &ansiContext{}, - } - - parser.csiEntry = csiEntryState{baseState{name: "CsiEntry", parser: parser}} - parser.csiParam = csiParamState{baseState{name: "CsiParam", parser: parser}} - parser.dcsEntry = dcsEntryState{baseState{name: "DcsEntry", parser: parser}} - parser.escape = escapeState{baseState{name: "Escape", parser: parser}} - parser.escapeIntermediate = escapeIntermediateState{baseState{name: "EscapeIntermediate", parser: parser}} - parser.error = errorState{baseState{name: "Error", parser: parser}} - parser.ground = groundState{baseState{name: "Ground", parser: parser}} - parser.oscString = oscStringState{baseState{name: "OscString", parser: parser}} - - parser.stateMap = []state{ - parser.csiEntry, - parser.csiParam, - parser.dcsEntry, - parser.escape, - parser.escapeIntermediate, - parser.error, - parser.ground, - parser.oscString, - } - - parser.currState = getState(initialState, parser.stateMap) - - logger.Infof("CreateParser: parser %p", parser) - return parser -} - -func getState(name string, states []state) state { - for _, el := range states { - if el.Name() == name { - return el - } - } - - return nil -} - -func (ap *AnsiParser) Parse(bytes []byte) (int, error) { - for i, b := range bytes { - if err := ap.handle(b); err != nil { - return i, err - } - } - - return len(bytes), ap.eventHandler.Flush() -} - -func (ap *AnsiParser) handle(b byte) error { - ap.context.currentChar = b - newState, err := ap.currState.Handle(b) - if err != nil { - return err - } - - if newState == nil { - logger.Warning("newState is nil") - return errors.New("New state of 'nil' is invalid.") - } - - if newState != ap.currState { - if err := ap.changeState(newState); err != nil { - return err - } - } - - return nil -} - -func (ap *AnsiParser) changeState(newState state) error { - logger.Infof("ChangeState %s --> %s", ap.currState.Name(), newState.Name()) - - // Exit old state - if err := ap.currState.Exit(); err != nil { - logger.Infof("Exit state '%s' failed with : '%v'", ap.currState.Name(), err) - return err - } - - // Perform transition action - if err := ap.currState.Transition(newState); err != nil { - logger.Infof("Transition from '%s' to '%s' failed with: '%v'", ap.currState.Name(), newState.Name, err) - return err - } - - // Enter new state - if err := newState.Enter(); err != nil { - logger.Infof("Enter state '%s' failed with: '%v'", newState.Name(), err) - return err - } - - ap.currState = newState - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go b/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go deleted file mode 100644 index 8b69a67a5a..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_action_helpers.go +++ /dev/null @@ -1,103 +0,0 @@ -package ansiterm - -import ( - "strconv" -) - -func parseParams(bytes []byte) ([]string, error) { - paramBuff := make([]byte, 0, 0) - params := []string{} - - for _, v := range bytes { - if v == ';' { - if len(paramBuff) > 0 { - // Completed parameter, append it to the list - s := string(paramBuff) - params = append(params, s) - paramBuff = make([]byte, 0, 0) - } - } else { - paramBuff = append(paramBuff, v) - } - } - - // Last parameter may not be terminated with ';' - if len(paramBuff) > 0 { - s := string(paramBuff) - params = append(params, s) - } - - logger.Infof("Parsed params: %v with length: %d", params, len(params)) - return params, nil -} - -func parseCmd(context ansiContext) (string, error) { - return string(context.currentChar), nil -} - -func getInt(params []string, dflt int) int { - i := getInts(params, 1, dflt)[0] - logger.Infof("getInt: %v", i) - return i -} - -func getInts(params []string, minCount int, dflt int) []int { - ints := []int{} - - for _, v := range params { - i, _ := strconv.Atoi(v) - // Zero is mapped to the default value in VT100. - if i == 0 { - i = dflt - } - ints = append(ints, i) - } - - if len(ints) < minCount { - remaining := minCount - len(ints) - for i := 0; i < remaining; i++ { - ints = append(ints, dflt) - } - } - - logger.Infof("getInts: %v", ints) - - return ints -} - -func (ap *AnsiParser) modeDispatch(param string, set bool) error { - switch param { - case "?3": - return ap.eventHandler.DECCOLM(set) - case "?6": - return ap.eventHandler.DECOM(set) - case "?25": - return ap.eventHandler.DECTCEM(set) - } - return nil -} - -func (ap *AnsiParser) hDispatch(params []string) error { - if len(params) == 1 { - return ap.modeDispatch(params[0], true) - } - - return nil -} - -func (ap *AnsiParser) lDispatch(params []string) error { - if len(params) == 1 { - return ap.modeDispatch(params[0], false) - } - - return nil -} - -func getEraseParam(params []string) int { - param := getInt(params, 0) - if param < 0 || 3 < param { - param = 0 - } - - return param -} diff --git a/vendor/github.com/Azure/go-ansiterm/parser_actions.go b/vendor/github.com/Azure/go-ansiterm/parser_actions.go deleted file mode 100644 index 58750a2d2b..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/parser_actions.go +++ /dev/null @@ -1,122 +0,0 @@ -package ansiterm - -import ( - "fmt" -) - -func (ap *AnsiParser) collectParam() error { - currChar := ap.context.currentChar - logger.Infof("collectParam %#x", currChar) - ap.context.paramBuffer = append(ap.context.paramBuffer, currChar) - return nil -} - -func (ap *AnsiParser) collectInter() error { - currChar := ap.context.currentChar - logger.Infof("collectInter %#x", currChar) - ap.context.paramBuffer = append(ap.context.interBuffer, currChar) - return nil -} - -func (ap *AnsiParser) escDispatch() error { - cmd, _ := parseCmd(*ap.context) - intermeds := ap.context.interBuffer - logger.Infof("escDispatch currentChar: %#x", ap.context.currentChar) - logger.Infof("escDispatch: %v(%v)", cmd, intermeds) - - switch cmd { - case "D": // IND - return ap.eventHandler.IND() - case "E": // NEL, equivalent to CRLF - err := ap.eventHandler.Execute(ANSI_CARRIAGE_RETURN) - if err == nil { - err = ap.eventHandler.Execute(ANSI_LINE_FEED) - } - return err - case "M": // RI - return ap.eventHandler.RI() - } - - return nil -} - -func (ap *AnsiParser) csiDispatch() error { - cmd, _ := parseCmd(*ap.context) - params, _ := parseParams(ap.context.paramBuffer) - - logger.Infof("csiDispatch: %v(%v)", cmd, params) - - switch cmd { - case "@": - return ap.eventHandler.ICH(getInt(params, 1)) - case "A": - return ap.eventHandler.CUU(getInt(params, 1)) - case "B": - return ap.eventHandler.CUD(getInt(params, 1)) - case "C": - return ap.eventHandler.CUF(getInt(params, 1)) - case "D": - return ap.eventHandler.CUB(getInt(params, 1)) - case "E": - return ap.eventHandler.CNL(getInt(params, 1)) - case "F": - return ap.eventHandler.CPL(getInt(params, 1)) - case "G": - return ap.eventHandler.CHA(getInt(params, 1)) - case "H": - ints := getInts(params, 2, 1) - x, y := ints[0], ints[1] - return ap.eventHandler.CUP(x, y) - case "J": - param := getEraseParam(params) - return ap.eventHandler.ED(param) - case "K": - param := getEraseParam(params) - return ap.eventHandler.EL(param) - case "L": - return ap.eventHandler.IL(getInt(params, 1)) - case "M": - return ap.eventHandler.DL(getInt(params, 1)) - case "P": - return ap.eventHandler.DCH(getInt(params, 1)) - case "S": - return ap.eventHandler.SU(getInt(params, 1)) - case "T": - return ap.eventHandler.SD(getInt(params, 1)) - case "c": - return ap.eventHandler.DA(params) - case "d": - return ap.eventHandler.VPA(getInt(params, 1)) - case "f": - ints := getInts(params, 2, 1) - x, y := ints[0], ints[1] - return ap.eventHandler.HVP(x, y) - case "h": - return ap.hDispatch(params) - case "l": - return ap.lDispatch(params) - case "m": - return ap.eventHandler.SGR(getInts(params, 1, 0)) - case "r": - ints := getInts(params, 2, 1) - top, bottom := ints[0], ints[1] - return ap.eventHandler.DECSTBM(top, bottom) - default: - logger.Errorf(fmt.Sprintf("Unsupported CSI command: '%s', with full context: %v", cmd, ap.context)) - return nil - } - -} - -func (ap *AnsiParser) print() error { - return ap.eventHandler.Print(ap.context.currentChar) -} - -func (ap *AnsiParser) clear() error { - ap.context = &ansiContext{} - return nil -} - -func (ap *AnsiParser) execute() error { - return ap.eventHandler.Execute(ap.context.currentChar) -} diff --git a/vendor/github.com/Azure/go-ansiterm/states.go b/vendor/github.com/Azure/go-ansiterm/states.go deleted file mode 100644 index f2ea1fcd12..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/states.go +++ /dev/null @@ -1,71 +0,0 @@ -package ansiterm - -type stateID int - -type state interface { - Enter() error - Exit() error - Handle(byte) (state, error) - Name() string - Transition(state) error -} - -type baseState struct { - name string - parser *AnsiParser -} - -func (base baseState) Enter() error { - return nil -} - -func (base baseState) Exit() error { - return nil -} - -func (base baseState) Handle(b byte) (s state, e error) { - - switch { - case b == CSI_ENTRY: - return base.parser.csiEntry, nil - case b == DCS_ENTRY: - return base.parser.dcsEntry, nil - case b == ANSI_ESCAPE_PRIMARY: - return base.parser.escape, nil - case b == OSC_STRING: - return base.parser.oscString, nil - case sliceContains(toGroundBytes, b): - return base.parser.ground, nil - } - - return nil, nil -} - -func (base baseState) Name() string { - return base.name -} - -func (base baseState) Transition(s state) error { - if s == base.parser.ground { - execBytes := []byte{0x18} - execBytes = append(execBytes, 0x1A) - execBytes = append(execBytes, getByteRange(0x80, 0x8F)...) - execBytes = append(execBytes, getByteRange(0x91, 0x97)...) - execBytes = append(execBytes, 0x99) - execBytes = append(execBytes, 0x9A) - - if sliceContains(execBytes, base.parser.context.currentChar) { - return base.parser.execute() - } - } - - return nil -} - -type dcsEntryState struct { - baseState -} - -type errorState struct { - baseState -} diff --git a/vendor/github.com/Azure/go-ansiterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/utilities.go deleted file mode 100644 index 392114493a..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/utilities.go +++ /dev/null @@ -1,21 +0,0 @@ -package ansiterm - -import ( - "strconv" -) - -func sliceContains(bytes []byte, b byte) bool { - for _, v := range bytes { - if v == b { - return true - } - } - - return false -} - -func convertBytesToInteger(bytes []byte) int { - s := string(bytes) - i, _ := strconv.Atoi(s) - return i -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go deleted file mode 100644 index daf2f06961..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ /dev/null @@ -1,182 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "os" - "strconv" - "strings" - "syscall" - - "github.com/Azure/go-ansiterm" -) - -// Windows keyboard constants -// See https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx. -const ( - VK_PRIOR = 0x21 // PAGE UP key - VK_NEXT = 0x22 // PAGE DOWN key - VK_END = 0x23 // END key - VK_HOME = 0x24 // HOME key - VK_LEFT = 0x25 // LEFT ARROW key - VK_UP = 0x26 // UP ARROW key - VK_RIGHT = 0x27 // RIGHT ARROW key - VK_DOWN = 0x28 // DOWN ARROW key - VK_SELECT = 0x29 // SELECT key - VK_PRINT = 0x2A // PRINT key - VK_EXECUTE = 0x2B // EXECUTE key - VK_SNAPSHOT = 0x2C // PRINT SCREEN key - VK_INSERT = 0x2D // INS key - VK_DELETE = 0x2E // DEL key - VK_HELP = 0x2F // HELP key - VK_F1 = 0x70 // F1 key - VK_F2 = 0x71 // F2 key - VK_F3 = 0x72 // F3 key - VK_F4 = 0x73 // F4 key - VK_F5 = 0x74 // F5 key - VK_F6 = 0x75 // F6 key - VK_F7 = 0x76 // F7 key - VK_F8 = 0x77 // F8 key - VK_F9 = 0x78 // F9 key - VK_F10 = 0x79 // F10 key - VK_F11 = 0x7A // F11 key - VK_F12 = 0x7B // F12 key - - RIGHT_ALT_PRESSED = 0x0001 - LEFT_ALT_PRESSED = 0x0002 - RIGHT_CTRL_PRESSED = 0x0004 - LEFT_CTRL_PRESSED = 0x0008 - SHIFT_PRESSED = 0x0010 - NUMLOCK_ON = 0x0020 - SCROLLLOCK_ON = 0x0040 - CAPSLOCK_ON = 0x0080 - ENHANCED_KEY = 0x0100 -) - -type ansiCommand struct { - CommandBytes []byte - Command string - Parameters []string - IsSpecial bool -} - -func newAnsiCommand(command []byte) *ansiCommand { - - if isCharacterSelectionCmdChar(command[1]) { - // Is Character Set Selection commands - return &ansiCommand{ - CommandBytes: command, - Command: string(command), - IsSpecial: true, - } - } - - // last char is command character - lastCharIndex := len(command) - 1 - - ac := &ansiCommand{ - CommandBytes: command, - Command: string(command[lastCharIndex]), - IsSpecial: false, - } - - // more than a single escape - if lastCharIndex != 0 { - start := 1 - // skip if double char escape sequence - if command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_ESCAPE_SECONDARY { - start++ - } - // convert this to GetNextParam method - ac.Parameters = strings.Split(string(command[start:lastCharIndex]), ansiterm.ANSI_PARAMETER_SEP) - } - - return ac -} - -func (ac *ansiCommand) paramAsSHORT(index int, defaultValue int16) int16 { - if index < 0 || index >= len(ac.Parameters) { - return defaultValue - } - - param, err := strconv.ParseInt(ac.Parameters[index], 10, 16) - if err != nil { - return defaultValue - } - - return int16(param) -} - -func (ac *ansiCommand) String() string { - return fmt.Sprintf("0x%v \"%v\" (\"%v\")", - bytesToHex(ac.CommandBytes), - ac.Command, - strings.Join(ac.Parameters, "\",\"")) -} - -// isAnsiCommandChar returns true if the passed byte falls within the range of ANSI commands. -// See http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html. -func isAnsiCommandChar(b byte) bool { - switch { - case ansiterm.ANSI_COMMAND_FIRST <= b && b <= ansiterm.ANSI_COMMAND_LAST && b != ansiterm.ANSI_ESCAPE_SECONDARY: - return true - case b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_OSC || b == ansiterm.ANSI_CMD_DECPAM || b == ansiterm.ANSI_CMD_DECPNM: - // non-CSI escape sequence terminator - return true - case b == ansiterm.ANSI_CMD_STR_TERM || b == ansiterm.ANSI_BEL: - // String escape sequence terminator - return true - } - return false -} - -func isXtermOscSequence(command []byte, current byte) bool { - return (len(command) >= 2 && command[0] == ansiterm.ANSI_ESCAPE_PRIMARY && command[1] == ansiterm.ANSI_CMD_OSC && current != ansiterm.ANSI_BEL) -} - -func isCharacterSelectionCmdChar(b byte) bool { - return (b == ansiterm.ANSI_CMD_G0 || b == ansiterm.ANSI_CMD_G1 || b == ansiterm.ANSI_CMD_G2 || b == ansiterm.ANSI_CMD_G3) -} - -// bytesToHex converts a slice of bytes to a human-readable string. -func bytesToHex(b []byte) string { - hex := make([]string, len(b)) - for i, ch := range b { - hex[i] = fmt.Sprintf("%X", ch) - } - return strings.Join(hex, "") -} - -// ensureInRange adjusts the passed value, if necessary, to ensure it is within -// the passed min / max range. -func ensureInRange(n int16, min int16, max int16) int16 { - if n < min { - return min - } else if n > max { - return max - } else { - return n - } -} - -func GetStdFile(nFile int) (*os.File, uintptr) { - var file *os.File - switch nFile { - case syscall.STD_INPUT_HANDLE: - file = os.Stdin - case syscall.STD_OUTPUT_HANDLE: - file = os.Stdout - case syscall.STD_ERROR_HANDLE: - file = os.Stderr - default: - panic(fmt.Errorf("Invalid standard handle identifier: %v", nFile)) - } - - fd, err := syscall.GetStdHandle(nFile) - if err != nil { - panic(fmt.Errorf("Invalid standard handle indentifier: %v -- %v", nFile, err)) - } - - return file, uintptr(fd) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go deleted file mode 100644 index 462d92f8ef..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ /dev/null @@ -1,322 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "syscall" - "unsafe" -) - -//=========================================================================================================== -// IMPORTANT NOTE: -// -// The methods below make extensive use of the "unsafe" package to obtain the required pointers. -// Beginning in Go 1.3, the garbage collector may release local variables (e.g., incoming arguments, stack -// variables) the pointers reference *before* the API completes. -// -// As a result, in those cases, the code must hint that the variables remain in active by invoking the -// dummy method "use" (see below). Newer versions of Go are planned to change the mechanism to no longer -// require unsafe pointers. -// -// If you add or modify methods, ENSURE protection of local variables through the "use" builtin to inform -// the garbage collector the variables remain in use if: -// -// -- The value is not a pointer (e.g., int32, struct) -// -- The value is not referenced by the method after passing the pointer to Windows -// -// See http://golang.org/doc/go1.3. -//=========================================================================================================== - -var ( - kernel32DLL = syscall.NewLazyDLL("kernel32.dll") - - getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") - setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") - setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") - setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") - getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") - setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") - scrollConsoleScreenBufferProc = kernel32DLL.NewProc("ScrollConsoleScreenBufferA") - setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") - setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") - writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") - readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") - waitForSingleObjectProc = kernel32DLL.NewProc("WaitForSingleObject") -) - -// Windows Console constants -const ( - // Console modes - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. - ENABLE_PROCESSED_INPUT = 0x0001 - ENABLE_LINE_INPUT = 0x0002 - ENABLE_ECHO_INPUT = 0x0004 - ENABLE_WINDOW_INPUT = 0x0008 - ENABLE_MOUSE_INPUT = 0x0010 - ENABLE_INSERT_MODE = 0x0020 - ENABLE_QUICK_EDIT_MODE = 0x0040 - ENABLE_EXTENDED_FLAGS = 0x0080 - - ENABLE_PROCESSED_OUTPUT = 0x0001 - ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 - - // Character attributes - // Note: - // -- The attributes are combined to produce various colors (e.g., Blue + Green will create Cyan). - // Clearing all foreground or background colors results in black; setting all creates white. - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes. - FOREGROUND_BLUE uint16 = 0x0001 - FOREGROUND_GREEN uint16 = 0x0002 - FOREGROUND_RED uint16 = 0x0004 - FOREGROUND_INTENSITY uint16 = 0x0008 - FOREGROUND_MASK uint16 = 0x000F - - BACKGROUND_BLUE uint16 = 0x0010 - BACKGROUND_GREEN uint16 = 0x0020 - BACKGROUND_RED uint16 = 0x0040 - BACKGROUND_INTENSITY uint16 = 0x0080 - BACKGROUND_MASK uint16 = 0x00F0 - - COMMON_LVB_MASK uint16 = 0xFF00 - COMMON_LVB_REVERSE_VIDEO uint16 = 0x4000 - COMMON_LVB_UNDERSCORE uint16 = 0x8000 - - // Input event types - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. - KEY_EVENT = 0x0001 - MOUSE_EVENT = 0x0002 - WINDOW_BUFFER_SIZE_EVENT = 0x0004 - MENU_EVENT = 0x0008 - FOCUS_EVENT = 0x0010 - - // WaitForSingleObject return codes - WAIT_ABANDONED = 0x00000080 - WAIT_FAILED = 0xFFFFFFFF - WAIT_SIGNALED = 0x0000000 - WAIT_TIMEOUT = 0x00000102 - - // WaitForSingleObject wait duration - WAIT_INFINITE = 0xFFFFFFFF - WAIT_ONE_SECOND = 1000 - WAIT_HALF_SECOND = 500 - WAIT_QUARTER_SECOND = 250 -) - -// Windows API Console types -// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms682101(v=vs.85).aspx for Console specific types (e.g., COORD) -// -- See https://msdn.microsoft.com/en-us/library/aa296569(v=vs.60).aspx for comments on alignment -type ( - CHAR_INFO struct { - UnicodeChar uint16 - Attributes uint16 - } - - CONSOLE_CURSOR_INFO struct { - Size uint32 - Visible int32 - } - - CONSOLE_SCREEN_BUFFER_INFO struct { - Size COORD - CursorPosition COORD - Attributes uint16 - Window SMALL_RECT - MaximumWindowSize COORD - } - - COORD struct { - X int16 - Y int16 - } - - SMALL_RECT struct { - Left int16 - Top int16 - Right int16 - Bottom int16 - } - - // INPUT_RECORD is a C/C++ union of which KEY_EVENT_RECORD is one case, it is also the largest - // See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683499(v=vs.85).aspx. - INPUT_RECORD struct { - EventType uint16 - KeyEvent KEY_EVENT_RECORD - } - - KEY_EVENT_RECORD struct { - KeyDown int32 - RepeatCount uint16 - VirtualKeyCode uint16 - VirtualScanCode uint16 - UnicodeChar uint16 - ControlKeyState uint32 - } - - WINDOW_BUFFER_SIZE struct { - Size COORD - } -) - -// boolToBOOL converts a Go bool into a Windows int32. -func boolToBOOL(f bool) int32 { - if f { - return int32(1) - } else { - return int32(0) - } -} - -// GetConsoleCursorInfo retrieves information about the size and visiblity of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683163(v=vs.85).aspx. -func GetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { - r1, r2, err := getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) - return checkError(r1, r2, err) -} - -// SetConsoleCursorInfo sets the size and visiblity of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx. -func SetConsoleCursorInfo(handle uintptr, cursorInfo *CONSOLE_CURSOR_INFO) error { - r1, r2, err := setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0) - return checkError(r1, r2, err) -} - -// SetConsoleCursorPosition location of the console cursor. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686025(v=vs.85).aspx. -func SetConsoleCursorPosition(handle uintptr, coord COORD) error { - r1, r2, err := setConsoleCursorPositionProc.Call(handle, coordToPointer(coord)) - use(coord) - return checkError(r1, r2, err) -} - -// GetConsoleMode gets the console mode for given file descriptor -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx. -func GetConsoleMode(handle uintptr) (mode uint32, err error) { - err = syscall.GetConsoleMode(syscall.Handle(handle), &mode) - return mode, err -} - -// SetConsoleMode sets the console mode for given file descriptor -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx. -func SetConsoleMode(handle uintptr, mode uint32) error { - r1, r2, err := setConsoleModeProc.Call(handle, uintptr(mode), 0) - use(mode) - return checkError(r1, r2, err) -} - -// GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx. -func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { - info := CONSOLE_SCREEN_BUFFER_INFO{} - err := checkError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)) - if err != nil { - return nil, err - } - return &info, nil -} - -func ScrollConsoleScreenBuffer(handle uintptr, scrollRect SMALL_RECT, clipRect SMALL_RECT, destOrigin COORD, char CHAR_INFO) error { - r1, r2, err := scrollConsoleScreenBufferProc.Call(handle, uintptr(unsafe.Pointer(&scrollRect)), uintptr(unsafe.Pointer(&clipRect)), coordToPointer(destOrigin), uintptr(unsafe.Pointer(&char))) - use(scrollRect) - use(clipRect) - use(destOrigin) - use(char) - return checkError(r1, r2, err) -} - -// SetConsoleScreenBufferSize sets the size of the console screen buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686044(v=vs.85).aspx. -func SetConsoleScreenBufferSize(handle uintptr, coord COORD) error { - r1, r2, err := setConsoleScreenBufferSizeProc.Call(handle, coordToPointer(coord)) - use(coord) - return checkError(r1, r2, err) -} - -// SetConsoleTextAttribute sets the attributes of characters written to the -// console screen buffer by the WriteFile or WriteConsole function. -// See http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx. -func SetConsoleTextAttribute(handle uintptr, attribute uint16) error { - r1, r2, err := setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0) - use(attribute) - return checkError(r1, r2, err) -} - -// SetConsoleWindowInfo sets the size and position of the console screen buffer's window. -// Note that the size and location must be within and no larger than the backing console screen buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms686125(v=vs.85).aspx. -func SetConsoleWindowInfo(handle uintptr, isAbsolute bool, rect SMALL_RECT) error { - r1, r2, err := setConsoleWindowInfoProc.Call(handle, uintptr(boolToBOOL(isAbsolute)), uintptr(unsafe.Pointer(&rect))) - use(isAbsolute) - use(rect) - return checkError(r1, r2, err) -} - -// WriteConsoleOutput writes the CHAR_INFOs from the provided buffer to the active console buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687404(v=vs.85).aspx. -func WriteConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) error { - r1, r2, err := writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), coordToPointer(bufferSize), coordToPointer(bufferCoord), uintptr(unsafe.Pointer(writeRegion))) - use(buffer) - use(bufferSize) - use(bufferCoord) - return checkError(r1, r2, err) -} - -// ReadConsoleInput reads (and removes) data from the console input buffer. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx. -func ReadConsoleInput(handle uintptr, buffer []INPUT_RECORD, count *uint32) error { - r1, r2, err := readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), uintptr(len(buffer)), uintptr(unsafe.Pointer(count))) - use(buffer) - return checkError(r1, r2, err) -} - -// WaitForSingleObject waits for the passed handle to be signaled. -// It returns true if the handle was signaled; false otherwise. -// See https://msdn.microsoft.com/en-us/library/windows/desktop/ms687032(v=vs.85).aspx. -func WaitForSingleObject(handle uintptr, msWait uint32) (bool, error) { - r1, _, err := waitForSingleObjectProc.Call(handle, uintptr(uint32(msWait))) - switch r1 { - case WAIT_ABANDONED, WAIT_TIMEOUT: - return false, nil - case WAIT_SIGNALED: - return true, nil - } - use(msWait) - return false, err -} - -// String helpers -func (info CONSOLE_SCREEN_BUFFER_INFO) String() string { - return fmt.Sprintf("Size(%v) Cursor(%v) Window(%v) Max(%v)", info.Size, info.CursorPosition, info.Window, info.MaximumWindowSize) -} - -func (coord COORD) String() string { - return fmt.Sprintf("%v,%v", coord.X, coord.Y) -} - -func (rect SMALL_RECT) String() string { - return fmt.Sprintf("(%v,%v),(%v,%v)", rect.Left, rect.Top, rect.Right, rect.Bottom) -} - -// checkError evaluates the results of a Windows API call and returns the error if it failed. -func checkError(r1, r2 uintptr, err error) error { - // Windows APIs return non-zero to indicate success - if r1 != 0 { - return nil - } - - // Return the error if provided, otherwise default to EINVAL - if err != nil { - return err - } - return syscall.EINVAL -} - -// coordToPointer converts a COORD into a uintptr (by fooling the type system). -func coordToPointer(c COORD) uintptr { - // Note: This code assumes the two SHORTs are correctly laid out; the "cast" to uint32 is just to get a pointer to pass. - return uintptr(*((*uint32)(unsafe.Pointer(&c)))) -} - -// use is a no-op, but the compiler cannot see that it is. -// Calling use(p) ensures that p is kept live until that point. -func use(p interface{}) {} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go deleted file mode 100644 index cbec8f728f..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ /dev/null @@ -1,100 +0,0 @@ -// +build windows - -package winterm - -import "github.com/Azure/go-ansiterm" - -const ( - FOREGROUND_COLOR_MASK = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE - BACKGROUND_COLOR_MASK = BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE -) - -// collectAnsiIntoWindowsAttributes modifies the passed Windows text mode flags to reflect the -// request represented by the passed ANSI mode. -func collectAnsiIntoWindowsAttributes(windowsMode uint16, inverted bool, baseMode uint16, ansiMode int16) (uint16, bool) { - switch ansiMode { - - // Mode styles - case ansiterm.ANSI_SGR_BOLD: - windowsMode = windowsMode | FOREGROUND_INTENSITY - - case ansiterm.ANSI_SGR_DIM, ansiterm.ANSI_SGR_BOLD_DIM_OFF: - windowsMode &^= FOREGROUND_INTENSITY - - case ansiterm.ANSI_SGR_UNDERLINE: - windowsMode = windowsMode | COMMON_LVB_UNDERSCORE - - case ansiterm.ANSI_SGR_REVERSE: - inverted = true - - case ansiterm.ANSI_SGR_REVERSE_OFF: - inverted = false - - case ansiterm.ANSI_SGR_UNDERLINE_OFF: - windowsMode &^= COMMON_LVB_UNDERSCORE - - // Foreground colors - case ansiterm.ANSI_SGR_FOREGROUND_DEFAULT: - windowsMode = (windowsMode &^ FOREGROUND_MASK) | (baseMode & FOREGROUND_MASK) - - case ansiterm.ANSI_SGR_FOREGROUND_BLACK: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) - - case ansiterm.ANSI_SGR_FOREGROUND_RED: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED - - case ansiterm.ANSI_SGR_FOREGROUND_GREEN: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN - - case ansiterm.ANSI_SGR_FOREGROUND_YELLOW: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN - - case ansiterm.ANSI_SGR_FOREGROUND_BLUE: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_MAGENTA: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_CYAN: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_GREEN | FOREGROUND_BLUE - - case ansiterm.ANSI_SGR_FOREGROUND_WHITE: - windowsMode = (windowsMode &^ FOREGROUND_COLOR_MASK) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE - - // Background colors - case ansiterm.ANSI_SGR_BACKGROUND_DEFAULT: - // Black with no intensity - windowsMode = (windowsMode &^ BACKGROUND_MASK) | (baseMode & BACKGROUND_MASK) - - case ansiterm.ANSI_SGR_BACKGROUND_BLACK: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) - - case ansiterm.ANSI_SGR_BACKGROUND_RED: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED - - case ansiterm.ANSI_SGR_BACKGROUND_GREEN: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN - - case ansiterm.ANSI_SGR_BACKGROUND_YELLOW: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN - - case ansiterm.ANSI_SGR_BACKGROUND_BLUE: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_MAGENTA: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_CYAN: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_GREEN | BACKGROUND_BLUE - - case ansiterm.ANSI_SGR_BACKGROUND_WHITE: - windowsMode = (windowsMode &^ BACKGROUND_COLOR_MASK) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE - } - - return windowsMode, inverted -} - -// invertAttributes inverts the foreground and background colors of a Windows attributes value -func invertAttributes(windowsMode uint16) uint16 { - return (COMMON_LVB_MASK & windowsMode) | ((FOREGROUND_MASK & windowsMode) << 4) | ((BACKGROUND_MASK & windowsMode) >> 4) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go deleted file mode 100644 index f015723ade..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ /dev/null @@ -1,101 +0,0 @@ -// +build windows - -package winterm - -const ( - horizontal = iota - vertical -) - -func (h *windowsAnsiEventHandler) getCursorWindow(info *CONSOLE_SCREEN_BUFFER_INFO) SMALL_RECT { - if h.originMode { - sr := h.effectiveSr(info.Window) - return SMALL_RECT{ - Top: sr.top, - Bottom: sr.bottom, - Left: 0, - Right: info.Size.X - 1, - } - } else { - return SMALL_RECT{ - Top: info.Window.Top, - Bottom: info.Window.Bottom, - Left: 0, - Right: info.Size.X - 1, - } - } -} - -// setCursorPosition sets the cursor to the specified position, bounded to the screen size -func (h *windowsAnsiEventHandler) setCursorPosition(position COORD, window SMALL_RECT) error { - position.X = ensureInRange(position.X, window.Left, window.Right) - position.Y = ensureInRange(position.Y, window.Top, window.Bottom) - err := SetConsoleCursorPosition(h.fd, position) - if err != nil { - return err - } - logger.Infof("Cursor position set: (%d, %d)", position.X, position.Y) - return err -} - -func (h *windowsAnsiEventHandler) moveCursorVertical(param int) error { - return h.moveCursor(vertical, param) -} - -func (h *windowsAnsiEventHandler) moveCursorHorizontal(param int) error { - return h.moveCursor(horizontal, param) -} - -func (h *windowsAnsiEventHandler) moveCursor(moveMode int, param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - switch moveMode { - case horizontal: - position.X += int16(param) - case vertical: - position.Y += int16(param) - } - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) moveCursorLine(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - position.X = 0 - position.Y += int16(param) - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) moveCursorColumn(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - position := info.CursorPosition - position.X = int16(param) - 1 - - if err = h.setCursorPosition(position, h.getCursorWindow(info)); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go deleted file mode 100644 index 244b5fa25e..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ /dev/null @@ -1,84 +0,0 @@ -// +build windows - -package winterm - -import "github.com/Azure/go-ansiterm" - -func (h *windowsAnsiEventHandler) clearRange(attributes uint16, fromCoord COORD, toCoord COORD) error { - // Ignore an invalid (negative area) request - if toCoord.Y < fromCoord.Y { - return nil - } - - var err error - - var coordStart = COORD{} - var coordEnd = COORD{} - - xCurrent, yCurrent := fromCoord.X, fromCoord.Y - xEnd, yEnd := toCoord.X, toCoord.Y - - // Clear any partial initial line - if xCurrent > 0 { - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yCurrent - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - xCurrent = 0 - yCurrent += 1 - } - - // Clear intervening rectangular section - if yCurrent < yEnd { - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yEnd-1 - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - xCurrent = 0 - yCurrent = yEnd - } - - // Clear remaining partial ending line - coordStart.X, coordStart.Y = xCurrent, yCurrent - coordEnd.X, coordEnd.Y = xEnd, yEnd - - err = h.clearRect(attributes, coordStart, coordEnd) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) clearRect(attributes uint16, fromCoord COORD, toCoord COORD) error { - region := SMALL_RECT{Top: fromCoord.Y, Left: fromCoord.X, Bottom: toCoord.Y, Right: toCoord.X} - width := toCoord.X - fromCoord.X + 1 - height := toCoord.Y - fromCoord.Y + 1 - size := uint32(width) * uint32(height) - - if size <= 0 { - return nil - } - - buffer := make([]CHAR_INFO, size) - - char := CHAR_INFO{ansiterm.FILL_CHARACTER, attributes} - for i := 0; i < int(size); i++ { - buffer[i] = char - } - - err := WriteConsoleOutput(h.fd, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, ®ion) - if err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go deleted file mode 100644 index 706d270577..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ /dev/null @@ -1,118 +0,0 @@ -// +build windows - -package winterm - -// effectiveSr gets the current effective scroll region in buffer coordinates -func (h *windowsAnsiEventHandler) effectiveSr(window SMALL_RECT) scrollRegion { - top := addInRange(window.Top, h.sr.top, window.Top, window.Bottom) - bottom := addInRange(window.Top, h.sr.bottom, window.Top, window.Bottom) - if top >= bottom { - top = window.Top - bottom = window.Bottom - } - return scrollRegion{top: top, bottom: bottom} -} - -func (h *windowsAnsiEventHandler) scrollUp(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - sr := h.effectiveSr(info.Window) - return h.scroll(param, sr, info) -} - -func (h *windowsAnsiEventHandler) scrollDown(param int) error { - return h.scrollUp(-param) -} - -func (h *windowsAnsiEventHandler) deleteLines(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - start := info.CursorPosition.Y - sr := h.effectiveSr(info.Window) - // Lines cannot be inserted or deleted outside the scrolling region. - if start >= sr.top && start <= sr.bottom { - sr.top = start - return h.scroll(param, sr, info) - } else { - return nil - } -} - -func (h *windowsAnsiEventHandler) insertLines(param int) error { - return h.deleteLines(-param) -} - -// scroll scrolls the provided scroll region by param lines. The scroll region is in buffer coordinates. -func (h *windowsAnsiEventHandler) scroll(param int, sr scrollRegion, info *CONSOLE_SCREEN_BUFFER_INFO) error { - logger.Infof("scroll: scrollTop: %d, scrollBottom: %d", sr.top, sr.bottom) - logger.Infof("scroll: windowTop: %d, windowBottom: %d", info.Window.Top, info.Window.Bottom) - - // Copy from and clip to the scroll region (full buffer width) - scrollRect := SMALL_RECT{ - Top: sr.top, - Bottom: sr.bottom, - Left: 0, - Right: info.Size.X - 1, - } - - // Origin to which area should be copied - destOrigin := COORD{ - X: 0, - Y: sr.top - int16(param), - } - - char := CHAR_INFO{ - UnicodeChar: ' ', - Attributes: h.attributes, - } - - if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { - return err - } - return nil -} - -func (h *windowsAnsiEventHandler) deleteCharacters(param int) error { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - return h.scrollLine(param, info.CursorPosition, info) -} - -func (h *windowsAnsiEventHandler) insertCharacters(param int) error { - return h.deleteCharacters(-param) -} - -// scrollLine scrolls a line horizontally starting at the provided position by a number of columns. -func (h *windowsAnsiEventHandler) scrollLine(columns int, position COORD, info *CONSOLE_SCREEN_BUFFER_INFO) error { - // Copy from and clip to the scroll region (full buffer width) - scrollRect := SMALL_RECT{ - Top: position.Y, - Bottom: position.Y, - Left: position.X, - Right: info.Size.X - 1, - } - - // Origin to which area should be copied - destOrigin := COORD{ - X: position.X - int16(columns), - Y: position.Y, - } - - char := CHAR_INFO{ - UnicodeChar: ' ', - Attributes: h.attributes, - } - - if err := ScrollConsoleScreenBuffer(h.fd, scrollRect, scrollRect, destOrigin, char); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go deleted file mode 100644 index afa7635d77..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package winterm - -// AddInRange increments a value by the passed quantity while ensuring the values -// always remain within the supplied min / max range. -func addInRange(n int16, increment int16, min int16, max int16) int16 { - return ensureInRange(n+increment, min, max) -} diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go deleted file mode 100644 index 4d858ed611..0000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ /dev/null @@ -1,726 +0,0 @@ -// +build windows - -package winterm - -import ( - "bytes" - "io/ioutil" - "os" - "strconv" - - "github.com/Azure/go-ansiterm" - "github.com/Sirupsen/logrus" -) - -var logger *logrus.Logger - -type windowsAnsiEventHandler struct { - fd uintptr - file *os.File - infoReset *CONSOLE_SCREEN_BUFFER_INFO - sr scrollRegion - buffer bytes.Buffer - attributes uint16 - inverted bool - wrapNext bool - drewMarginByte bool - originMode bool - marginByte byte - curInfo *CONSOLE_SCREEN_BUFFER_INFO - curPos COORD -} - -func CreateWinEventHandler(fd uintptr, file *os.File) ansiterm.AnsiEventHandler { - logFile := ioutil.Discard - - if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { - logFile, _ = os.Create("winEventHandler.log") - } - - logger = &logrus.Logger{ - Out: logFile, - Formatter: new(logrus.TextFormatter), - Level: logrus.DebugLevel, - } - - infoReset, err := GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil - } - - return &windowsAnsiEventHandler{ - fd: fd, - file: file, - infoReset: infoReset, - attributes: infoReset.Attributes, - } -} - -type scrollRegion struct { - top int16 - bottom int16 -} - -// simulateLF simulates a LF or CR+LF by scrolling if necessary to handle the -// current cursor position and scroll region settings, in which case it returns -// true. If no special handling is necessary, then it does nothing and returns -// false. -// -// In the false case, the caller should ensure that a carriage return -// and line feed are inserted or that the text is otherwise wrapped. -func (h *windowsAnsiEventHandler) simulateLF(includeCR bool) (bool, error) { - if h.wrapNext { - if err := h.Flush(); err != nil { - return false, err - } - h.clearWrap() - } - pos, info, err := h.getCurrentInfo() - if err != nil { - return false, err - } - sr := h.effectiveSr(info.Window) - if pos.Y == sr.bottom { - // Scrolling is necessary. Let Windows automatically scroll if the scrolling region - // is the full window. - if sr.top == info.Window.Top && sr.bottom == info.Window.Bottom { - if includeCR { - pos.X = 0 - h.updatePos(pos) - } - return false, nil - } - - // A custom scroll region is active. Scroll the window manually to simulate - // the LF. - if err := h.Flush(); err != nil { - return false, err - } - logger.Info("Simulating LF inside scroll region") - if err := h.scrollUp(1); err != nil { - return false, err - } - if includeCR { - pos.X = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return false, err - } - } - return true, nil - - } else if pos.Y < info.Window.Bottom { - // Let Windows handle the LF. - pos.Y++ - if includeCR { - pos.X = 0 - } - h.updatePos(pos) - return false, nil - } else { - // The cursor is at the bottom of the screen but outside the scroll - // region. Skip the LF. - logger.Info("Simulating LF outside scroll region") - if includeCR { - if err := h.Flush(); err != nil { - return false, err - } - pos.X = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return false, err - } - } - return true, nil - } -} - -// executeLF executes a LF without a CR. -func (h *windowsAnsiEventHandler) executeLF() error { - handled, err := h.simulateLF(false) - if err != nil { - return err - } - if !handled { - // Windows LF will reset the cursor column position. Write the LF - // and restore the cursor position. - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) - if pos.X != 0 { - if err := h.Flush(); err != nil { - return err - } - logger.Info("Resetting cursor position for LF without CR") - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - } - } - return nil -} - -func (h *windowsAnsiEventHandler) Print(b byte) error { - if h.wrapNext { - h.buffer.WriteByte(h.marginByte) - h.clearWrap() - if _, err := h.simulateLF(true); err != nil { - return err - } - } - pos, info, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X == info.Size.X-1 { - h.wrapNext = true - h.marginByte = b - } else { - pos.X++ - h.updatePos(pos) - h.buffer.WriteByte(b) - } - return nil -} - -func (h *windowsAnsiEventHandler) Execute(b byte) error { - switch b { - case ansiterm.ANSI_TAB: - logger.Info("Execute(TAB)") - // Move to the next tab stop, but preserve auto-wrap if already set. - if !h.wrapNext { - pos, info, err := h.getCurrentInfo() - if err != nil { - return err - } - pos.X = (pos.X + 8) - pos.X%8 - if pos.X >= info.Size.X { - pos.X = info.Size.X - 1 - } - if err := h.Flush(); err != nil { - return err - } - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - } - return nil - - case ansiterm.ANSI_BEL: - h.buffer.WriteByte(ansiterm.ANSI_BEL) - return nil - - case ansiterm.ANSI_BACKSPACE: - if h.wrapNext { - if err := h.Flush(); err != nil { - return err - } - h.clearWrap() - } - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X > 0 { - pos.X-- - h.updatePos(pos) - h.buffer.WriteByte(ansiterm.ANSI_BACKSPACE) - } - return nil - - case ansiterm.ANSI_VERTICAL_TAB, ansiterm.ANSI_FORM_FEED: - // Treat as true LF. - return h.executeLF() - - case ansiterm.ANSI_LINE_FEED: - // Simulate a CR and LF for now since there is no way in go-ansiterm - // to tell if the LF should include CR (and more things break when it's - // missing than when it's incorrectly added). - handled, err := h.simulateLF(true) - if handled || err != nil { - return err - } - return h.buffer.WriteByte(ansiterm.ANSI_LINE_FEED) - - case ansiterm.ANSI_CARRIAGE_RETURN: - if h.wrapNext { - if err := h.Flush(); err != nil { - return err - } - h.clearWrap() - } - pos, _, err := h.getCurrentInfo() - if err != nil { - return err - } - if pos.X != 0 { - pos.X = 0 - h.updatePos(pos) - h.buffer.WriteByte(ansiterm.ANSI_CARRIAGE_RETURN) - } - return nil - - default: - return nil - } -} - -func (h *windowsAnsiEventHandler) CUU(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CUU: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorVertical(-param) -} - -func (h *windowsAnsiEventHandler) CUD(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CUD: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorVertical(param) -} - -func (h *windowsAnsiEventHandler) CUF(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CUF: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorHorizontal(param) -} - -func (h *windowsAnsiEventHandler) CUB(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CUB: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorHorizontal(-param) -} - -func (h *windowsAnsiEventHandler) CNL(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CNL: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorLine(param) -} - -func (h *windowsAnsiEventHandler) CPL(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CPL: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorLine(-param) -} - -func (h *windowsAnsiEventHandler) CHA(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CHA: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.moveCursorColumn(param) -} - -func (h *windowsAnsiEventHandler) VPA(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("VPA: [[%d]]", param) - h.clearWrap() - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - window := h.getCursorWindow(info) - position := info.CursorPosition - position.Y = window.Top + int16(param) - 1 - return h.setCursorPosition(position, window) -} - -func (h *windowsAnsiEventHandler) CUP(row int, col int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("CUP: [[%d %d]]", row, col) - h.clearWrap() - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - window := h.getCursorWindow(info) - position := COORD{window.Left + int16(col) - 1, window.Top + int16(row) - 1} - return h.setCursorPosition(position, window) -} - -func (h *windowsAnsiEventHandler) HVP(row int, col int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("HVP: [[%d %d]]", row, col) - h.clearWrap() - return h.CUP(row, col) -} - -func (h *windowsAnsiEventHandler) DECTCEM(visible bool) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DECTCEM: [%v]", []string{strconv.FormatBool(visible)}) - h.clearWrap() - return nil -} - -func (h *windowsAnsiEventHandler) DECOM(enable bool) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DECOM: [%v]", []string{strconv.FormatBool(enable)}) - h.clearWrap() - h.originMode = enable - return h.CUP(1, 1) -} - -func (h *windowsAnsiEventHandler) DECCOLM(use132 bool) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DECCOLM: [%v]", []string{strconv.FormatBool(use132)}) - h.clearWrap() - if err := h.ED(2); err != nil { - return err - } - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - targetWidth := int16(80) - if use132 { - targetWidth = 132 - } - if info.Size.X < targetWidth { - if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { - logger.Info("set buffer failed:", err) - return err - } - } - window := info.Window - window.Left = 0 - window.Right = targetWidth - 1 - if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { - logger.Info("set window failed:", err) - return err - } - if info.Size.X > targetWidth { - if err := SetConsoleScreenBufferSize(h.fd, COORD{targetWidth, info.Size.Y}); err != nil { - logger.Info("set buffer failed:", err) - return err - } - } - return SetConsoleCursorPosition(h.fd, COORD{0, 0}) -} - -func (h *windowsAnsiEventHandler) ED(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("ED: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - - // [J -- Erases from the cursor to the end of the screen, including the cursor position. - // [1J -- Erases from the beginning of the screen to the cursor, including the cursor position. - // [2J -- Erases the complete display. The cursor does not move. - // Notes: - // -- Clearing the entire buffer, versus just the Window, works best for Windows Consoles - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - var start COORD - var end COORD - - switch param { - case 0: - start = info.CursorPosition - end = COORD{info.Size.X - 1, info.Size.Y - 1} - - case 1: - start = COORD{0, 0} - end = info.CursorPosition - - case 2: - start = COORD{0, 0} - end = COORD{info.Size.X - 1, info.Size.Y - 1} - } - - err = h.clearRange(h.attributes, start, end) - if err != nil { - return err - } - - // If the whole buffer was cleared, move the window to the top while preserving - // the window-relative cursor position. - if param == 2 { - pos := info.CursorPosition - window := info.Window - pos.Y -= window.Top - window.Bottom -= window.Top - window.Top = 0 - if err := SetConsoleCursorPosition(h.fd, pos); err != nil { - return err - } - if err := SetConsoleWindowInfo(h.fd, true, window); err != nil { - return err - } - } - - return nil -} - -func (h *windowsAnsiEventHandler) EL(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("EL: [%v]", strconv.Itoa(param)) - h.clearWrap() - - // [K -- Erases from the cursor to the end of the line, including the cursor position. - // [1K -- Erases from the beginning of the line to the cursor, including the cursor position. - // [2K -- Erases the complete line. - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - var start COORD - var end COORD - - switch param { - case 0: - start = info.CursorPosition - end = COORD{info.Size.X, info.CursorPosition.Y} - - case 1: - start = COORD{0, info.CursorPosition.Y} - end = info.CursorPosition - - case 2: - start = COORD{0, info.CursorPosition.Y} - end = COORD{info.Size.X, info.CursorPosition.Y} - } - - err = h.clearRange(h.attributes, start, end) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) IL(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("IL: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.insertLines(param) -} - -func (h *windowsAnsiEventHandler) DL(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DL: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.deleteLines(param) -} - -func (h *windowsAnsiEventHandler) ICH(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("ICH: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.insertCharacters(param) -} - -func (h *windowsAnsiEventHandler) DCH(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DCH: [%v]", strconv.Itoa(param)) - h.clearWrap() - return h.deleteCharacters(param) -} - -func (h *windowsAnsiEventHandler) SGR(params []int) error { - if err := h.Flush(); err != nil { - return err - } - strings := []string{} - for _, v := range params { - strings = append(strings, strconv.Itoa(v)) - } - - logger.Infof("SGR: [%v]", strings) - - if len(params) <= 0 { - h.attributes = h.infoReset.Attributes - h.inverted = false - } else { - for _, attr := range params { - - if attr == ansiterm.ANSI_SGR_RESET { - h.attributes = h.infoReset.Attributes - h.inverted = false - continue - } - - h.attributes, h.inverted = collectAnsiIntoWindowsAttributes(h.attributes, h.inverted, h.infoReset.Attributes, int16(attr)) - } - } - - attributes := h.attributes - if h.inverted { - attributes = invertAttributes(attributes) - } - err := SetConsoleTextAttribute(h.fd, attributes) - if err != nil { - return err - } - - return nil -} - -func (h *windowsAnsiEventHandler) SU(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("SU: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.scrollUp(param) -} - -func (h *windowsAnsiEventHandler) SD(param int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("SD: [%v]", []string{strconv.Itoa(param)}) - h.clearWrap() - return h.scrollDown(param) -} - -func (h *windowsAnsiEventHandler) DA(params []string) error { - logger.Infof("DA: [%v]", params) - // DA cannot be implemented because it must send data on the VT100 input stream, - // which is not available to go-ansiterm. - return nil -} - -func (h *windowsAnsiEventHandler) DECSTBM(top int, bottom int) error { - if err := h.Flush(); err != nil { - return err - } - logger.Infof("DECSTBM: [%d, %d]", top, bottom) - - // Windows is 0 indexed, Linux is 1 indexed - h.sr.top = int16(top - 1) - h.sr.bottom = int16(bottom - 1) - - // This command also moves the cursor to the origin. - h.clearWrap() - return h.CUP(1, 1) -} - -func (h *windowsAnsiEventHandler) RI() error { - if err := h.Flush(); err != nil { - return err - } - logger.Info("RI: []") - h.clearWrap() - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - sr := h.effectiveSr(info.Window) - if info.CursorPosition.Y == sr.top { - return h.scrollDown(1) - } - - return h.moveCursorVertical(-1) -} - -func (h *windowsAnsiEventHandler) IND() error { - logger.Info("IND: []") - return h.executeLF() -} - -func (h *windowsAnsiEventHandler) Flush() error { - h.curInfo = nil - if h.buffer.Len() > 0 { - logger.Infof("Flush: [%s]", h.buffer.Bytes()) - if _, err := h.buffer.WriteTo(h.file); err != nil { - return err - } - } - - if h.wrapNext && !h.drewMarginByte { - logger.Infof("Flush: drawing margin byte '%c'", h.marginByte) - - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return err - } - - charInfo := []CHAR_INFO{{UnicodeChar: uint16(h.marginByte), Attributes: info.Attributes}} - size := COORD{1, 1} - position := COORD{0, 0} - region := SMALL_RECT{Left: info.CursorPosition.X, Top: info.CursorPosition.Y, Right: info.CursorPosition.X, Bottom: info.CursorPosition.Y} - if err := WriteConsoleOutput(h.fd, charInfo, size, position, ®ion); err != nil { - return err - } - h.drewMarginByte = true - } - return nil -} - -// cacheConsoleInfo ensures that the current console screen information has been queried -// since the last call to Flush(). It must be called before accessing h.curInfo or h.curPos. -func (h *windowsAnsiEventHandler) getCurrentInfo() (COORD, *CONSOLE_SCREEN_BUFFER_INFO, error) { - if h.curInfo == nil { - info, err := GetConsoleScreenBufferInfo(h.fd) - if err != nil { - return COORD{}, nil, err - } - h.curInfo = info - h.curPos = info.CursorPosition - } - return h.curPos, h.curInfo, nil -} - -func (h *windowsAnsiEventHandler) updatePos(pos COORD) { - if h.curInfo == nil { - panic("failed to call getCurrentInfo before calling updatePos") - } - h.curPos = pos -} - -// clearWrap clears the state where the cursor is in the margin -// waiting for the next character before wrapping the line. This must -// be done before most operations that act on the cursor. -func (h *windowsAnsiEventHandler) clearWrap() { - h.wrapNext = false - h.drewMarginByte = false -} diff --git a/vendor/github.com/Microsoft/go-winio/LICENSE b/vendor/github.com/Microsoft/go-winio/LICENSE deleted file mode 100644 index b8b569d774..0000000000 --- a/vendor/github.com/Microsoft/go-winio/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/Microsoft/go-winio/README.md b/vendor/github.com/Microsoft/go-winio/README.md deleted file mode 100644 index 5680010575..0000000000 --- a/vendor/github.com/Microsoft/go-winio/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# go-winio - -This repository contains utilities for efficiently performing Win32 IO operations in -Go. Currently, this is focused on accessing named pipes and other file handles, and -for using named pipes as a net transport. - -This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go -to reuse the thread to schedule another goroutine. This limits support to Windows Vista and -newer operating systems. This is similar to the implementation of network sockets in Go's net -package. - -Please see the LICENSE file for licensing information. - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. - -Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe -for another named pipe implementation. diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go deleted file mode 100644 index 2be34af431..0000000000 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ /dev/null @@ -1,280 +0,0 @@ -// +build windows - -package winio - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "syscall" - "unicode/utf16" -) - -//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead -//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite - -const ( - BackupData = uint32(iota + 1) - BackupEaData - BackupSecurity - BackupAlternateData - BackupLink - BackupPropertyData - BackupObjectId - BackupReparseData - BackupSparseBlock - BackupTxfsData -) - -const ( - StreamSparseAttributes = uint32(8) -) - -const ( - WRITE_DAC = 0x40000 - WRITE_OWNER = 0x80000 - ACCESS_SYSTEM_SECURITY = 0x1000000 -) - -// BackupHeader represents a backup stream of a file. -type BackupHeader struct { - Id uint32 // The backup stream ID - Attributes uint32 // Stream attributes - Size int64 // The size of the stream in bytes - Name string // The name of the stream (for BackupAlternateData only). - Offset int64 // The offset of the stream in the file (for BackupSparseBlock only). -} - -type win32StreamId struct { - StreamId uint32 - Attributes uint32 - Size uint64 - NameSize uint32 -} - -// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series -// of BackupHeader values. -type BackupStreamReader struct { - r io.Reader - bytesLeft int64 -} - -// NewBackupStreamReader produces a BackupStreamReader from any io.Reader. -func NewBackupStreamReader(r io.Reader) *BackupStreamReader { - return &BackupStreamReader{r, 0} -} - -// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if -// it was not completely read. -func (r *BackupStreamReader) Next() (*BackupHeader, error) { - if r.bytesLeft > 0 { - if s, ok := r.r.(io.Seeker); ok { - // Make sure Seek on io.SeekCurrent sometimes succeeds - // before trying the actual seek. - if _, err := s.Seek(0, io.SeekCurrent); err == nil { - if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil { - return nil, err - } - r.bytesLeft = 0 - } - } - if _, err := io.Copy(ioutil.Discard, r); err != nil { - return nil, err - } - } - var wsi win32StreamId - if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil { - return nil, err - } - hdr := &BackupHeader{ - Id: wsi.StreamId, - Attributes: wsi.Attributes, - Size: int64(wsi.Size), - } - if wsi.NameSize != 0 { - name := make([]uint16, int(wsi.NameSize/2)) - if err := binary.Read(r.r, binary.LittleEndian, name); err != nil { - return nil, err - } - hdr.Name = syscall.UTF16ToString(name) - } - if wsi.StreamId == BackupSparseBlock { - if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil { - return nil, err - } - hdr.Size -= 8 - } - r.bytesLeft = hdr.Size - return hdr, nil -} - -// Read reads from the current backup stream. -func (r *BackupStreamReader) Read(b []byte) (int, error) { - if r.bytesLeft == 0 { - return 0, io.EOF - } - if int64(len(b)) > r.bytesLeft { - b = b[:r.bytesLeft] - } - n, err := r.r.Read(b) - r.bytesLeft -= int64(n) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } else if r.bytesLeft == 0 && err == nil { - err = io.EOF - } - return n, err -} - -// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API. -type BackupStreamWriter struct { - w io.Writer - bytesLeft int64 -} - -// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer. -func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter { - return &BackupStreamWriter{w, 0} -} - -// WriteHeader writes the next backup stream header and prepares for calls to Write(). -func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error { - if w.bytesLeft != 0 { - return fmt.Errorf("missing %d bytes", w.bytesLeft) - } - name := utf16.Encode([]rune(hdr.Name)) - wsi := win32StreamId{ - StreamId: hdr.Id, - Attributes: hdr.Attributes, - Size: uint64(hdr.Size), - NameSize: uint32(len(name) * 2), - } - if hdr.Id == BackupSparseBlock { - // Include space for the int64 block offset - wsi.Size += 8 - } - if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil { - return err - } - if len(name) != 0 { - if err := binary.Write(w.w, binary.LittleEndian, name); err != nil { - return err - } - } - if hdr.Id == BackupSparseBlock { - if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil { - return err - } - } - w.bytesLeft = hdr.Size - return nil -} - -// Write writes to the current backup stream. -func (w *BackupStreamWriter) Write(b []byte) (int, error) { - if w.bytesLeft < int64(len(b)) { - return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft) - } - n, err := w.w.Write(b) - w.bytesLeft -= int64(n) - return n, err -} - -// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API. -type BackupFileReader struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true, -// Read will attempt to read the security descriptor of the file. -func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader { - r := &BackupFileReader{f, includeSecurity, 0} - return r -} - -// Read reads a backup stream from the file by calling the Win32 API BackupRead(). -func (r *BackupFileReader) Read(b []byte) (int, error) { - var bytesRead uint32 - err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx) - if err != nil { - return 0, &os.PathError{"BackupRead", r.f.Name(), err} - } - runtime.KeepAlive(r.f) - if bytesRead == 0 { - return 0, io.EOF - } - return int(bytesRead), nil -} - -// Close frees Win32 resources associated with the BackupFileReader. It does not close -// the underlying file. -func (r *BackupFileReader) Close() error { - if r.ctx != 0 { - backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx) - runtime.KeepAlive(r.f) - r.ctx = 0 - } - return nil -} - -// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API. -type BackupFileWriter struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true, -// Write() will attempt to restore the security descriptor from the stream. -func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter { - w := &BackupFileWriter{f, includeSecurity, 0} - return w -} - -// Write restores a portion of the file using the provided backup stream. -func (w *BackupFileWriter) Write(b []byte) (int, error) { - var bytesWritten uint32 - err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx) - if err != nil { - return 0, &os.PathError{"BackupWrite", w.f.Name(), err} - } - runtime.KeepAlive(w.f) - if int(bytesWritten) != len(b) { - return int(bytesWritten), errors.New("not all bytes could be written") - } - return len(b), nil -} - -// Close frees Win32 resources associated with the BackupFileWriter. It does not -// close the underlying file. -func (w *BackupFileWriter) Close() error { - if w.ctx != 0 { - backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx) - runtime.KeepAlive(w.f) - w.ctx = 0 - } - return nil -} - -// OpenForBackup opens a file or directory, potentially skipping access checks if the backup -// or restore privileges have been acquired. -// -// If the file opened was a directory, it cannot be used with Readdir(). -func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) { - winPath, err := syscall.UTF16FromString(path) - if err != nil { - return nil, err - } - h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0) - if err != nil { - err = &os.PathError{Op: "open", Path: path, Err: err} - return nil, err - } - return os.NewFile(uintptr(h), path), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/ea.go b/vendor/github.com/Microsoft/go-winio/ea.go deleted file mode 100644 index b37e930d6a..0000000000 --- a/vendor/github.com/Microsoft/go-winio/ea.go +++ /dev/null @@ -1,137 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "errors" -) - -type fileFullEaInformation struct { - NextEntryOffset uint32 - Flags uint8 - NameLength uint8 - ValueLength uint16 -} - -var ( - fileFullEaInformationSize = binary.Size(&fileFullEaInformation{}) - - errInvalidEaBuffer = errors.New("invalid extended attribute buffer") - errEaNameTooLarge = errors.New("extended attribute name too large") - errEaValueTooLarge = errors.New("extended attribute value too large") -) - -// ExtendedAttribute represents a single Windows EA. -type ExtendedAttribute struct { - Name string - Value []byte - Flags uint8 -} - -func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) { - var info fileFullEaInformation - err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info) - if err != nil { - err = errInvalidEaBuffer - return - } - - nameOffset := fileFullEaInformationSize - nameLen := int(info.NameLength) - valueOffset := nameOffset + int(info.NameLength) + 1 - valueLen := int(info.ValueLength) - nextOffset := int(info.NextEntryOffset) - if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) { - err = errInvalidEaBuffer - return - } - - ea.Name = string(b[nameOffset : nameOffset+nameLen]) - ea.Value = b[valueOffset : valueOffset+valueLen] - ea.Flags = info.Flags - if info.NextEntryOffset != 0 { - nb = b[info.NextEntryOffset:] - } - return -} - -// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION -// buffer retrieved from BackupRead, ZwQueryEaFile, etc. -func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) { - for len(b) != 0 { - ea, nb, err := parseEa(b) - if err != nil { - return nil, err - } - - eas = append(eas, ea) - b = nb - } - return -} - -func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { - if int(uint8(len(ea.Name))) != len(ea.Name) { - return errEaNameTooLarge - } - if int(uint16(len(ea.Value))) != len(ea.Value) { - return errEaValueTooLarge - } - entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value)) - withPadding := (entrySize + 3) &^ 3 - nextOffset := uint32(0) - if !last { - nextOffset = withPadding - } - info := fileFullEaInformation{ - NextEntryOffset: nextOffset, - Flags: ea.Flags, - NameLength: uint8(len(ea.Name)), - ValueLength: uint16(len(ea.Value)), - } - - err := binary.Write(buf, binary.LittleEndian, &info) - if err != nil { - return err - } - - _, err = buf.Write([]byte(ea.Name)) - if err != nil { - return err - } - - err = buf.WriteByte(0) - if err != nil { - return err - } - - _, err = buf.Write(ea.Value) - if err != nil { - return err - } - - _, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize]) - if err != nil { - return err - } - - return nil -} - -// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION -// buffer for use with BackupWrite, ZwSetEaFile, etc. -func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) { - var buf bytes.Buffer - for i := range eas { - last := false - if i == len(eas)-1 { - last = true - } - - err := writeEa(&buf, &eas[i], last) - if err != nil { - return nil, err - } - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go deleted file mode 100644 index 57ac3696a9..0000000000 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ /dev/null @@ -1,310 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "runtime" - "sync" - "sync/atomic" - "syscall" - "time" -) - -//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx -//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort -//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus -//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes -//sys timeBeginPeriod(period uint32) (n int32) = winmm.timeBeginPeriod - -type atomicBool int32 - -func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } -func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } -func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } -func (b *atomicBool) swap(new bool) bool { - var newInt int32 - if new { - newInt = 1 - } - return atomic.SwapInt32((*int32)(b), newInt) == 1 -} - -const ( - cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - cFILE_SKIP_SET_EVENT_ON_HANDLE = 2 -) - -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - -type timeoutError struct{} - -func (e *timeoutError) Error() string { return "i/o timeout" } -func (e *timeoutError) Timeout() bool { return true } -func (e *timeoutError) Temporary() bool { return true } - -type timeoutChan chan struct{} - -var ioInitOnce sync.Once -var ioCompletionPort syscall.Handle - -// ioResult contains the result of an asynchronous IO operation -type ioResult struct { - bytes uint32 - err error -} - -// ioOperation represents an outstanding asynchronous Win32 IO -type ioOperation struct { - o syscall.Overlapped - ch chan ioResult -} - -func initIo() { - h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff) - if err != nil { - panic(err) - } - ioCompletionPort = h - go ioCompletionProcessor(h) -} - -// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall. -// It takes ownership of this handle and will close it if it is garbage collected. -type win32File struct { - handle syscall.Handle - wg sync.WaitGroup - wgLock sync.RWMutex - closing atomicBool - readDeadline deadlineHandler - writeDeadline deadlineHandler -} - -type deadlineHandler struct { - setLock sync.Mutex - channel timeoutChan - channelLock sync.RWMutex - timer *time.Timer - timedout atomicBool -} - -// makeWin32File makes a new win32File from an existing file handle -func makeWin32File(h syscall.Handle) (*win32File, error) { - f := &win32File{handle: h} - ioInitOnce.Do(initIo) - _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff) - if err != nil { - return nil, err - } - err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE) - if err != nil { - return nil, err - } - f.readDeadline.channel = make(timeoutChan) - f.writeDeadline.channel = make(timeoutChan) - return f, nil -} - -func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) { - return makeWin32File(h) -} - -// closeHandle closes the resources associated with a Win32 handle -func (f *win32File) closeHandle() { - f.wgLock.Lock() - // Atomically set that we are closing, releasing the resources only once. - if !f.closing.swap(true) { - f.wgLock.Unlock() - // cancel all IO and wait for it to complete - cancelIoEx(f.handle, nil) - f.wg.Wait() - // at this point, no new IO can start - syscall.Close(f.handle) - f.handle = 0 - } else { - f.wgLock.Unlock() - } -} - -// Close closes a win32File. -func (f *win32File) Close() error { - f.closeHandle() - return nil -} - -// prepareIo prepares for a new IO operation. -// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning. -func (f *win32File) prepareIo() (*ioOperation, error) { - f.wgLock.RLock() - if f.closing.isSet() { - f.wgLock.RUnlock() - return nil, ErrFileClosed - } - f.wg.Add(1) - f.wgLock.RUnlock() - c := &ioOperation{} - c.ch = make(chan ioResult) - return c, nil -} - -// ioCompletionProcessor processes completed async IOs forever -func ioCompletionProcessor(h syscall.Handle) { - // Set the timer resolution to 1. This fixes a performance regression in golang 1.6. - timeBeginPeriod(1) - for { - var bytes uint32 - var key uintptr - var op *ioOperation - err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE) - if op == nil { - panic(err) - } - op.ch <- ioResult{bytes, err} - } -} - -// asyncIo processes the return value from ReadFile or WriteFile, blocking until -// the operation has actually completed. -func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) { - if err != syscall.ERROR_IO_PENDING { - return int(bytes), err - } - - if f.closing.isSet() { - cancelIoEx(f.handle, &c.o) - } - - var timeout timeoutChan - if d != nil { - d.channelLock.Lock() - timeout = d.channel - d.channelLock.Unlock() - } - - var r ioResult - select { - case r = <-c.ch: - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - if f.closing.isSet() { - err = ErrFileClosed - } - } - case <-timeout: - cancelIoEx(f.handle, &c.o) - r = <-c.ch - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - err = ErrTimeout - } - } - - // runtime.KeepAlive is needed, as c is passed via native - // code to ioCompletionProcessor, c must remain alive - // until the channel read is complete. - runtime.KeepAlive(c) - return int(r.bytes), err -} - -// Read reads from a file handle. -func (f *win32File) Read(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.readDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.ReadFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.readDeadline, bytes, err) - runtime.KeepAlive(b) - - // Handle EOF conditions. - if err == nil && n == 0 && len(b) != 0 { - return 0, io.EOF - } else if err == syscall.ERROR_BROKEN_PIPE { - return 0, io.EOF - } else { - return n, err - } -} - -// Write writes to a file handle. -func (f *win32File) Write(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.writeDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.WriteFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.writeDeadline, bytes, err) - runtime.KeepAlive(b) - return n, err -} - -func (f *win32File) SetReadDeadline(deadline time.Time) error { - return f.readDeadline.set(deadline) -} - -func (f *win32File) SetWriteDeadline(deadline time.Time) error { - return f.writeDeadline.set(deadline) -} - -func (f *win32File) Flush() error { - return syscall.FlushFileBuffers(f.handle) -} - -func (d *deadlineHandler) set(deadline time.Time) error { - d.setLock.Lock() - defer d.setLock.Unlock() - - if d.timer != nil { - if !d.timer.Stop() { - <-d.channel - } - d.timer = nil - } - d.timedout.setFalse() - - select { - case <-d.channel: - d.channelLock.Lock() - d.channel = make(chan struct{}) - d.channelLock.Unlock() - default: - } - - if deadline.IsZero() { - return nil - } - - timeoutIO := func() { - d.timedout.setTrue() - close(d.channel) - } - - now := time.Now() - duration := deadline.Sub(now) - if deadline.After(now) { - // Deadline is in the future, set a timer to wait - d.timer = time.AfterFunc(duration, timeoutIO) - } else { - // Deadline is in the past. Cancel all pending IO now. - timeoutIO() - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go deleted file mode 100644 index b1d60abb83..0000000000 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build windows - -package winio - -import ( - "os" - "runtime" - "syscall" - "unsafe" -) - -//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx -//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle - -const ( - fileBasicInfo = 0 - fileIDInfo = 0x12 -) - -// FileBasicInfo contains file access time and file attributes information. -type FileBasicInfo struct { - CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime - FileAttributes uintptr // includes padding -} - -// GetFileBasicInfo retrieves times and attributes for a file. -func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { - bi := &FileBasicInfo{} - if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return bi, nil -} - -// SetFileBasicInfo sets times and attributes for a file. -func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error { - if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return nil -} - -// FileIDInfo contains the volume serial number and file ID for a file. This pair should be -// unique on a system. -type FileIDInfo struct { - VolumeSerialNumber uint64 - FileID [16]byte -} - -// GetFileID retrieves the unique (volume, file ID) pair for a file. -func GetFileID(f *os.File) (*FileIDInfo, error) { - fileID := &FileIDInfo{} - if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return fileID, nil -} diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go deleted file mode 100644 index 44340b8167..0000000000 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ /dev/null @@ -1,404 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "net" - "os" - "syscall" - "time" - "unsafe" -) - -//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe -//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW -//sys createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW -//sys waitNamedPipe(name string, timeout uint32) (err error) = WaitNamedPipeW -//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo -//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW -//sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc - -const ( - cERROR_PIPE_BUSY = syscall.Errno(231) - cERROR_PIPE_CONNECTED = syscall.Errno(535) - cERROR_SEM_TIMEOUT = syscall.Errno(121) - - cPIPE_ACCESS_DUPLEX = 0x3 - cFILE_FLAG_FIRST_PIPE_INSTANCE = 0x80000 - cSECURITY_SQOS_PRESENT = 0x100000 - cSECURITY_ANONYMOUS = 0 - - cPIPE_REJECT_REMOTE_CLIENTS = 0x8 - - cPIPE_UNLIMITED_INSTANCES = 255 - - cNMPWAIT_USE_DEFAULT_WAIT = 0 - cNMPWAIT_NOWAIT = 1 - - cPIPE_TYPE_MESSAGE = 4 - - cPIPE_READMODE_MESSAGE = 2 -) - -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - // This error should match net.errClosing since docker takes a dependency on its text. - ErrPipeListenerClosed = errors.New("use of closed network connection") - - errPipeWriteClosed = errors.New("pipe has been closed for write") -) - -type win32Pipe struct { - *win32File - path string -} - -type win32MessageBytePipe struct { - win32Pipe - writeClosed bool - readEOF bool -} - -type pipeAddress string - -func (f *win32Pipe) LocalAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) RemoteAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) SetDeadline(t time.Time) error { - f.SetReadDeadline(t) - f.SetWriteDeadline(t) - return nil -} - -// CloseWrite closes the write side of a message pipe in byte mode. -func (f *win32MessageBytePipe) CloseWrite() error { - if f.writeClosed { - return errPipeWriteClosed - } - err := f.win32File.Flush() - if err != nil { - return err - } - _, err = f.win32File.Write(nil) - if err != nil { - return err - } - f.writeClosed = true - return nil -} - -// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since -// they are used to implement CloseWrite(). -func (f *win32MessageBytePipe) Write(b []byte) (int, error) { - if f.writeClosed { - return 0, errPipeWriteClosed - } - if len(b) == 0 { - return 0, nil - } - return f.win32File.Write(b) -} - -// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message -// mode pipe will return io.EOF, as will all subsequent reads. -func (f *win32MessageBytePipe) Read(b []byte) (int, error) { - if f.readEOF { - return 0, io.EOF - } - n, err := f.win32File.Read(b) - if err == io.EOF { - // If this was the result of a zero-byte read, then - // it is possible that the read was due to a zero-size - // message. Since we are simulating CloseWrite with a - // zero-byte message, ensure that all future Read() calls - // also return EOF. - f.readEOF = true - } - return n, err -} - -func (s pipeAddress) Network() string { - return "pipe" -} - -func (s pipeAddress) String() string { - return string(s) -} - -// DialPipe connects to a named pipe by path, timing out if the connection -// takes longer than the specified duration. If timeout is nil, then the timeout -// is the default timeout established by the pipe server. -func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { - var absTimeout time.Time - if timeout != nil { - absTimeout = time.Now().Add(*timeout) - } - var err error - var h syscall.Handle - for { - h, err = createFile(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err != cERROR_PIPE_BUSY { - break - } - now := time.Now() - var ms uint32 - if absTimeout.IsZero() { - ms = cNMPWAIT_USE_DEFAULT_WAIT - } else if now.After(absTimeout) { - ms = cNMPWAIT_NOWAIT - } else { - ms = uint32(absTimeout.Sub(now).Nanoseconds() / 1000 / 1000) - } - err = waitNamedPipe(path, ms) - if err != nil { - if err == cERROR_SEM_TIMEOUT { - return nil, ErrTimeout - } - break - } - } - if err != nil { - return nil, &os.PathError{Op: "open", Path: path, Err: err} - } - - var flags uint32 - err = getNamedPipeInfo(h, &flags, nil, nil, nil) - if err != nil { - return nil, err - } - - var state uint32 - err = getNamedPipeHandleState(h, &state, nil, nil, nil, nil, 0) - if err != nil { - return nil, err - } - - if state&cPIPE_READMODE_MESSAGE != 0 { - return nil, &os.PathError{Op: "open", Path: path, Err: errors.New("message readmode pipes not supported")} - } - - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - - // If the pipe is in message mode, return a message byte pipe, which - // supports CloseWrite(). - if flags&cPIPE_TYPE_MESSAGE != 0 { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: f, path: path}, - }, nil - } - return &win32Pipe{win32File: f, path: path}, nil -} - -type acceptResponse struct { - f *win32File - err error -} - -type win32PipeListener struct { - firstHandle syscall.Handle - path string - securityDescriptor []byte - config PipeConfig - acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int -} - -func makeServerPipeHandle(path string, securityDescriptor []byte, c *PipeConfig, first bool) (syscall.Handle, error) { - var flags uint32 = cPIPE_ACCESS_DUPLEX | syscall.FILE_FLAG_OVERLAPPED - if first { - flags |= cFILE_FLAG_FIRST_PIPE_INSTANCE - } - - var mode uint32 = cPIPE_REJECT_REMOTE_CLIENTS - if c.MessageMode { - mode |= cPIPE_TYPE_MESSAGE - } - - sa := &syscall.SecurityAttributes{} - sa.Length = uint32(unsafe.Sizeof(*sa)) - if securityDescriptor != nil { - len := uint32(len(securityDescriptor)) - sa.SecurityDescriptor = localAlloc(0, len) - defer localFree(sa.SecurityDescriptor) - copy((*[0xffff]byte)(unsafe.Pointer(sa.SecurityDescriptor))[:], securityDescriptor) - } - h, err := createNamedPipe(path, flags, mode, cPIPE_UNLIMITED_INSTANCES, uint32(c.OutputBufferSize), uint32(c.InputBufferSize), 0, sa) - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - return h, nil -} - -func (l *win32PipeListener) makeServerPipe() (*win32File, error) { - h, err := makeServerPipeHandle(l.path, l.securityDescriptor, &l.config, false) - if err != nil { - return nil, err - } - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - return f, nil -} - -func (l *win32PipeListener) listenerRoutine() { - closed := false - for !closed { - select { - case <-l.closeCh: - closed = true - case responseCh := <-l.acceptCh: - p, err := l.makeServerPipe() - if err == nil { - // Wait for the client to connect. - ch := make(chan error) - go func(p *win32File) { - ch <- connectPipe(p) - }(p) - select { - case err = <-ch: - if err != nil { - p.Close() - p = nil - } - case <-l.closeCh: - // Abort the connect request by closing the handle. - p.Close() - p = nil - err = <-ch - if err == nil || err == ErrFileClosed { - err = ErrPipeListenerClosed - } - closed = true - } - } - responseCh <- acceptResponse{p, err} - } - } - syscall.Close(l.firstHandle) - l.firstHandle = 0 - // Notify Close() and Accept() callers that the handle has been closed. - close(l.doneCh) -} - -// PipeConfig contain configuration for the pipe listener. -type PipeConfig struct { - // SecurityDescriptor contains a Windows security descriptor in SDDL format. - SecurityDescriptor string - - // MessageMode determines whether the pipe is in byte or message mode. In either - // case the pipe is read in byte mode by default. The only practical difference in - // this implementation is that CloseWrite() is only supported for message mode pipes; - // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only - // transferred to the reader (and returned as io.EOF in this implementation) - // when the pipe is in message mode. - MessageMode bool - - // InputBufferSize specifies the size the input buffer, in bytes. - InputBufferSize int32 - - // OutputBufferSize specifies the size the input buffer, in bytes. - OutputBufferSize int32 -} - -// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe. -// The pipe must not already exist. -func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { - var ( - sd []byte - err error - ) - if c == nil { - c = &PipeConfig{} - } - if c.SecurityDescriptor != "" { - sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor) - if err != nil { - return nil, err - } - } - h, err := makeServerPipeHandle(path, sd, c, true) - if err != nil { - return nil, err - } - // Immediately open and then close a client handle so that the named pipe is - // created but not currently accepting connections. - h2, err := createFile(path, 0, 0, nil, syscall.OPEN_EXISTING, cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err != nil { - syscall.Close(h) - return nil, err - } - syscall.Close(h2) - l := &win32PipeListener{ - firstHandle: h, - path: path, - securityDescriptor: sd, - config: *c, - acceptCh: make(chan (chan acceptResponse)), - closeCh: make(chan int), - doneCh: make(chan int), - } - go l.listenerRoutine() - return l, nil -} - -func connectPipe(p *win32File) error { - c, err := p.prepareIo() - if err != nil { - return err - } - defer p.wg.Done() - - err = connectNamedPipe(p.handle, &c.o) - _, err = p.asyncIo(c, nil, 0, err) - if err != nil && err != cERROR_PIPE_CONNECTED { - return err - } - return nil -} - -func (l *win32PipeListener) Accept() (net.Conn, error) { - ch := make(chan acceptResponse) - select { - case l.acceptCh <- ch: - response := <-ch - err := response.err - if err != nil { - return nil, err - } - if l.config.MessageMode { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: response.f, path: l.path}, - }, nil - } - return &win32Pipe{win32File: response.f, path: l.path}, nil - case <-l.doneCh: - return nil, ErrPipeListenerClosed - } -} - -func (l *win32PipeListener) Close() error { - select { - case l.closeCh <- 1: - <-l.doneCh - case <-l.doneCh: - } - return nil -} - -func (l *win32PipeListener) Addr() net.Addr { - return pipeAddress(l.path) -} diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go deleted file mode 100644 index 9c83d36fe5..0000000000 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build windows - -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "runtime" - "sync" - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges -//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf -//sys revertToSelf() (err error) = advapi32.RevertToSelf -//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken -//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread -//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW -//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW -//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW - -const ( - SE_PRIVILEGE_ENABLED = 2 - - ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300 - - SeBackupPrivilege = "SeBackupPrivilege" - SeRestorePrivilege = "SeRestorePrivilege" -) - -const ( - securityAnonymous = iota - securityIdentification - securityImpersonation - securityDelegation -) - -var ( - privNames = make(map[string]uint64) - privNameMutex sync.Mutex -) - -// PrivilegeError represents an error enabling privileges. -type PrivilegeError struct { - privileges []uint64 -} - -func (e *PrivilegeError) Error() string { - s := "" - if len(e.privileges) > 1 { - s = "Could not enable privileges " - } else { - s = "Could not enable privilege " - } - for i, p := range e.privileges { - if i != 0 { - s += ", " - } - s += `"` - s += getPrivilegeName(p) - s += `"` - } - return s -} - -// RunWithPrivilege enables a single privilege for a function call. -func RunWithPrivilege(name string, fn func() error) error { - return RunWithPrivileges([]string{name}, fn) -} - -// RunWithPrivileges enables privileges for a function call. -func RunWithPrivileges(names []string, fn func() error) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - runtime.LockOSThread() - defer runtime.UnlockOSThread() - token, err := newThreadToken() - if err != nil { - return err - } - defer releaseThreadToken(token) - err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED) - if err != nil { - return err - } - return fn() -} - -func mapPrivileges(names []string) ([]uint64, error) { - var privileges []uint64 - privNameMutex.Lock() - defer privNameMutex.Unlock() - for _, name := range names { - p, ok := privNames[name] - if !ok { - err := lookupPrivilegeValue("", name, &p) - if err != nil { - return nil, err - } - privNames[name] = p - } - privileges = append(privileges, p) - } - return privileges, nil -} - -// EnableProcessPrivileges enables privileges globally for the process. -func EnableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED) -} - -// DisableProcessPrivileges disables privileges globally for the process. -func DisableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, 0) -} - -func enableDisableProcessPrivilege(names []string, action uint32) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - - p, _ := windows.GetCurrentProcess() - var token windows.Token - err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token) - if err != nil { - return err - } - - defer token.Close() - return adjustPrivileges(token, privileges, action) -} - -func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error { - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, uint32(len(privileges))) - for _, p := range privileges { - binary.Write(&b, binary.LittleEndian, p) - binary.Write(&b, binary.LittleEndian, action) - } - prevState := make([]byte, b.Len()) - reqSize := uint32(0) - success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize) - if !success { - return err - } - if err == ERROR_NOT_ALL_ASSIGNED { - return &PrivilegeError{privileges} - } - return nil -} - -func getPrivilegeName(luid uint64) string { - var nameBuffer [256]uint16 - bufSize := uint32(len(nameBuffer)) - err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize) - if err != nil { - return fmt.Sprintf("", luid) - } - - var displayNameBuffer [256]uint16 - displayBufSize := uint32(len(displayNameBuffer)) - var langID uint32 - err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID) - if err != nil { - return fmt.Sprintf("", string(utf16.Decode(nameBuffer[:bufSize]))) - } - - return string(utf16.Decode(displayNameBuffer[:displayBufSize])) -} - -func newThreadToken() (windows.Token, error) { - err := impersonateSelf(securityImpersonation) - if err != nil { - return 0, err - } - - var token windows.Token - err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token) - if err != nil { - rerr := revertToSelf() - if rerr != nil { - panic(rerr) - } - return 0, err - } - return token, nil -} - -func releaseThreadToken(h windows.Token) { - err := revertToSelf() - if err != nil { - panic(err) - } - h.Close() -} diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go deleted file mode 100644 index fc1ee4d3a3..0000000000 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ /dev/null @@ -1,128 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "strings" - "unicode/utf16" - "unsafe" -) - -const ( - reparseTagMountPoint = 0xA0000003 - reparseTagSymlink = 0xA000000C -) - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 -} - -// ReparsePoint describes a Win32 symlink or mount point. -type ReparsePoint struct { - Target string - IsMountPoint bool -} - -// UnsupportedReparsePointError is returned when trying to decode a non-symlink or -// mount point reparse point. -type UnsupportedReparsePointError struct { - Tag uint32 -} - -func (e *UnsupportedReparsePointError) Error() string { - return fmt.Sprintf("unsupported reparse point %x", e.Tag) -} - -// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink -// or a mount point. -func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { - tag := binary.LittleEndian.Uint32(b[0:4]) - return DecodeReparsePointData(tag, b[8:]) -} - -func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { - isMountPoint := false - switch tag { - case reparseTagMountPoint: - isMountPoint = true - case reparseTagSymlink: - default: - return nil, &UnsupportedReparsePointError{tag} - } - nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) - if !isMountPoint { - nameOffset += 4 - } - nameLength := binary.LittleEndian.Uint16(b[6:8]) - name := make([]uint16, nameLength/2) - err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name) - if err != nil { - return nil, err - } - return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil -} - -func isDriveLetter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or -// mount point. -func EncodeReparsePoint(rp *ReparsePoint) []byte { - // Generate an NT path and determine if this is a relative path. - var ntTarget string - relative := false - if strings.HasPrefix(rp.Target, `\\?\`) { - ntTarget = `\??\` + rp.Target[4:] - } else if strings.HasPrefix(rp.Target, `\\`) { - ntTarget = `\??\UNC\` + rp.Target[2:] - } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' { - ntTarget = `\??\` + rp.Target - } else { - ntTarget = rp.Target - relative = true - } - - // The paths must be NUL-terminated even though they are counted strings. - target16 := utf16.Encode([]rune(rp.Target + "\x00")) - ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00")) - - size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8 - size += len(ntTarget16)*2 + len(target16)*2 - - tag := uint32(reparseTagMountPoint) - if !rp.IsMountPoint { - tag = reparseTagSymlink - size += 4 // Add room for symlink flags - } - - data := reparseDataBuffer{ - ReparseTag: tag, - ReparseDataLength: uint16(size), - SubstituteNameOffset: 0, - SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2), - PrintNameOffset: uint16(len(ntTarget16) * 2), - PrintNameLength: uint16((len(target16) - 1) * 2), - } - - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, &data) - if !rp.IsMountPoint { - flags := uint32(0) - if relative { - flags |= 1 - } - binary.Write(&b, binary.LittleEndian, flags) - } - - binary.Write(&b, binary.LittleEndian, ntTarget16) - binary.Write(&b, binary.LittleEndian, target16) - return b.Bytes() -} diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go deleted file mode 100644 index db1b370a1b..0000000000 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows - -package winio - -import ( - "syscall" - "unsafe" -) - -//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW -//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW -//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW -//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW -//sys localFree(mem uintptr) = LocalFree -//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength - -const ( - cERROR_NONE_MAPPED = syscall.Errno(1332) -) - -type AccountLookupError struct { - Name string - Err error -} - -func (e *AccountLookupError) Error() string { - if e.Name == "" { - return "lookup account: empty account name specified" - } - var s string - switch e.Err { - case cERROR_NONE_MAPPED: - s = "not found" - default: - s = e.Err.Error() - } - return "lookup account " + e.Name + ": " + s -} - -type SddlConversionError struct { - Sddl string - Err error -} - -func (e *SddlConversionError) Error() string { - return "convert " + e.Sddl + ": " + e.Err.Error() -} - -// LookupSidByName looks up the SID of an account by name -func LookupSidByName(name string) (sid string, err error) { - if name == "" { - return "", &AccountLookupError{name, cERROR_NONE_MAPPED} - } - - var sidSize, sidNameUse, refDomainSize uint32 - err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { - return "", &AccountLookupError{name, err} - } - sidBuffer := make([]byte, sidSize) - refDomainBuffer := make([]uint16, refDomainSize) - err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) - if err != nil { - return "", &AccountLookupError{name, err} - } - var strBuffer *uint16 - err = convertSidToStringSid(&sidBuffer[0], &strBuffer) - if err != nil { - return "", &AccountLookupError{name, err} - } - sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) - localFree(uintptr(unsafe.Pointer(strBuffer))) - return sid, nil -} - -func SddlToSecurityDescriptor(sddl string) ([]byte, error) { - var sdBuffer uintptr - err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil) - if err != nil { - return nil, &SddlConversionError{sddl, err} - } - defer localFree(sdBuffer) - sd := make([]byte, getSecurityDescriptorLength(sdBuffer)) - copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)]) - return sd, nil -} - -func SecurityDescriptorToSddl(sd []byte) (string, error) { - var sddl *uint16 - // The returned string length seems to including an aribtrary number of terminating NULs. - // Don't use it. - err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil) - if err != nil { - return "", err - } - defer localFree(uintptr(unsafe.Pointer(sddl))) - return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/syscall.go b/vendor/github.com/Microsoft/go-winio/syscall.go deleted file mode 100644 index 20d64cf41d..0000000000 --- a/vendor/github.com/Microsoft/go-winio/syscall.go +++ /dev/null @@ -1,3 +0,0 @@ -package winio - -//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go deleted file mode 100644 index 4f7a52eeb7..0000000000 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ /dev/null @@ -1,528 +0,0 @@ -// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT - -package winio - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - modwinmm = windows.NewLazySystemDLL("winmm.dll") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procLocalFree = modkernel32.NewProc("LocalFree") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") - procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") - procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") - procBackupRead = modkernel32.NewProc("BackupRead") - procBackupWrite = modkernel32.NewProc("BackupWrite") -) - -func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0) - newport = syscall.Handle(r0) - if newport == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func timeBeginPeriod(period uint32) (n int32) { - r0, _, _ := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0) - n = int32(r0) - return -} - -func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa) -} - -func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile) -} - -func _createFile(name *uint16, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func waitNamedPipe(name string, timeout uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _waitNamedPipe(_p0, timeout) -} - -func _waitNamedPipe(name *uint16, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func localAlloc(uFlags uint32, length uint32) (ptr uintptr) { - r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(uFlags), uintptr(length), 0) - ptr = uintptr(r0) - return -} - -func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(accountName) - if err != nil { - return - } - return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse) -} - -func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertSidToStringSid(sid *byte, str **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(str) - if err != nil { - return - } - return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size) -} - -func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func localFree(mem uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) - return -} - -func getSecurityDescriptorLength(sd uintptr) (len uint32) { - r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0) - len = uint32(r0) - return -} - -func getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) { - var _p0 uint32 - if releaseAll { - _p0 = 1 - } else { - _p0 = 0 - } - r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize))) - success = r0 != 0 - if true { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func impersonateSelf(level uint32) (err error) { - r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func revertToSelf() (err error) { - r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { - var _p0 uint32 - if openAsSelf { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getCurrentThread() (h syscall.Handle) { - r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) - h = syscall.Handle(r0) - return -} - -func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - var _p1 *uint16 - _p1, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _lookupPrivilegeValue(_p0, _p1, luid) -} - -func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) { - r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeName(_p0, luid, buffer, size) -} - -func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId) -} - -func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/Nvveen/Gotty/LICENSE b/vendor/github.com/Nvveen/Gotty/LICENSE deleted file mode 100644 index 0b71c97360..0000000000 --- a/vendor/github.com/Nvveen/Gotty/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2012, Neal van Veen (nealvanveen@gmail.com) -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation are those -of the authors and should not be interpreted as representing official policies, -either expressed or implied, of the FreeBSD Project. diff --git a/vendor/github.com/Nvveen/Gotty/README b/vendor/github.com/Nvveen/Gotty/README deleted file mode 100644 index a6b0d9a8fe..0000000000 --- a/vendor/github.com/Nvveen/Gotty/README +++ /dev/null @@ -1,5 +0,0 @@ -Gotty is a library written in Go that determines and reads termcap database -files to produce an interface for interacting with the capabilities of a -terminal. -See the godoc documentation or the source code for more information about -function usage. diff --git a/vendor/github.com/Nvveen/Gotty/TODO b/vendor/github.com/Nvveen/Gotty/TODO deleted file mode 100644 index 470460531c..0000000000 --- a/vendor/github.com/Nvveen/Gotty/TODO +++ /dev/null @@ -1,3 +0,0 @@ -gotty.go:// TODO add more concurrency to name lookup, look for more opportunities. -all:// TODO add more documentation, with function usage in a doc.go file. -all:// TODO add more testing/benchmarking with go test. diff --git a/vendor/github.com/Nvveen/Gotty/attributes.go b/vendor/github.com/Nvveen/Gotty/attributes.go deleted file mode 100644 index a4c005fae5..0000000000 --- a/vendor/github.com/Nvveen/Gotty/attributes.go +++ /dev/null @@ -1,514 +0,0 @@ -// Copyright 2012 Neal van Veen. All rights reserved. -// Usage of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package gotty - -// Boolean capabilities -var BoolAttr = [...]string{ - "auto_left_margin", "bw", - "auto_right_margin", "am", - "no_esc_ctlc", "xsb", - "ceol_standout_glitch", "xhp", - "eat_newline_glitch", "xenl", - "erase_overstrike", "eo", - "generic_type", "gn", - "hard_copy", "hc", - "has_meta_key", "km", - "has_status_line", "hs", - "insert_null_glitch", "in", - "memory_above", "da", - "memory_below", "db", - "move_insert_mode", "mir", - "move_standout_mode", "msgr", - "over_strike", "os", - "status_line_esc_ok", "eslok", - "dest_tabs_magic_smso", "xt", - "tilde_glitch", "hz", - "transparent_underline", "ul", - "xon_xoff", "nxon", - "needs_xon_xoff", "nxon", - "prtr_silent", "mc5i", - "hard_cursor", "chts", - "non_rev_rmcup", "nrrmc", - "no_pad_char", "npc", - "non_dest_scroll_region", "ndscr", - "can_change", "ccc", - "back_color_erase", "bce", - "hue_lightness_saturation", "hls", - "col_addr_glitch", "xhpa", - "cr_cancels_micro_mode", "crxm", - "has_print_wheel", "daisy", - "row_addr_glitch", "xvpa", - "semi_auto_right_margin", "sam", - "cpi_changes_res", "cpix", - "lpi_changes_res", "lpix", - "backspaces_with_bs", "", - "crt_no_scrolling", "", - "no_correctly_working_cr", "", - "gnu_has_meta_key", "", - "linefeed_is_newline", "", - "has_hardware_tabs", "", - "return_does_clr_eol", "", -} - -// Numerical capabilities -var NumAttr = [...]string{ - "columns", "cols", - "init_tabs", "it", - "lines", "lines", - "lines_of_memory", "lm", - "magic_cookie_glitch", "xmc", - "padding_baud_rate", "pb", - "virtual_terminal", "vt", - "width_status_line", "wsl", - "num_labels", "nlab", - "label_height", "lh", - "label_width", "lw", - "max_attributes", "ma", - "maximum_windows", "wnum", - "max_colors", "colors", - "max_pairs", "pairs", - "no_color_video", "ncv", - "buffer_capacity", "bufsz", - "dot_vert_spacing", "spinv", - "dot_horz_spacing", "spinh", - "max_micro_address", "maddr", - "max_micro_jump", "mjump", - "micro_col_size", "mcs", - "micro_line_size", "mls", - "number_of_pins", "npins", - "output_res_char", "orc", - "output_res_line", "orl", - "output_res_horz_inch", "orhi", - "output_res_vert_inch", "orvi", - "print_rate", "cps", - "wide_char_size", "widcs", - "buttons", "btns", - "bit_image_entwining", "bitwin", - "bit_image_type", "bitype", - "magic_cookie_glitch_ul", "", - "carriage_return_delay", "", - "new_line_delay", "", - "backspace_delay", "", - "horizontal_tab_delay", "", - "number_of_function_keys", "", -} - -// String capabilities -var StrAttr = [...]string{ - "back_tab", "cbt", - "bell", "bel", - "carriage_return", "cr", - "change_scroll_region", "csr", - "clear_all_tabs", "tbc", - "clear_screen", "clear", - "clr_eol", "el", - "clr_eos", "ed", - "column_address", "hpa", - "command_character", "cmdch", - "cursor_address", "cup", - "cursor_down", "cud1", - "cursor_home", "home", - "cursor_invisible", "civis", - "cursor_left", "cub1", - "cursor_mem_address", "mrcup", - "cursor_normal", "cnorm", - "cursor_right", "cuf1", - "cursor_to_ll", "ll", - "cursor_up", "cuu1", - "cursor_visible", "cvvis", - "delete_character", "dch1", - "delete_line", "dl1", - "dis_status_line", "dsl", - "down_half_line", "hd", - "enter_alt_charset_mode", "smacs", - "enter_blink_mode", "blink", - "enter_bold_mode", "bold", - "enter_ca_mode", "smcup", - "enter_delete_mode", "smdc", - "enter_dim_mode", "dim", - "enter_insert_mode", "smir", - "enter_secure_mode", "invis", - "enter_protected_mode", "prot", - "enter_reverse_mode", "rev", - "enter_standout_mode", "smso", - "enter_underline_mode", "smul", - "erase_chars", "ech", - "exit_alt_charset_mode", "rmacs", - "exit_attribute_mode", "sgr0", - "exit_ca_mode", "rmcup", - "exit_delete_mode", "rmdc", - "exit_insert_mode", "rmir", - "exit_standout_mode", "rmso", - "exit_underline_mode", "rmul", - "flash_screen", "flash", - "form_feed", "ff", - "from_status_line", "fsl", - "init_1string", "is1", - "init_2string", "is2", - "init_3string", "is3", - "init_file", "if", - "insert_character", "ich1", - "insert_line", "il1", - "insert_padding", "ip", - "key_backspace", "kbs", - "key_catab", "ktbc", - "key_clear", "kclr", - "key_ctab", "kctab", - "key_dc", "kdch1", - "key_dl", "kdl1", - "key_down", "kcud1", - "key_eic", "krmir", - "key_eol", "kel", - "key_eos", "ked", - "key_f0", "kf0", - "key_f1", "kf1", - "key_f10", "kf10", - "key_f2", "kf2", - "key_f3", "kf3", - "key_f4", "kf4", - "key_f5", "kf5", - "key_f6", "kf6", - "key_f7", "kf7", - "key_f8", "kf8", - "key_f9", "kf9", - "key_home", "khome", - "key_ic", "kich1", - "key_il", "kil1", - "key_left", "kcub1", - "key_ll", "kll", - "key_npage", "knp", - "key_ppage", "kpp", - "key_right", "kcuf1", - "key_sf", "kind", - "key_sr", "kri", - "key_stab", "khts", - "key_up", "kcuu1", - "keypad_local", "rmkx", - "keypad_xmit", "smkx", - "lab_f0", "lf0", - "lab_f1", "lf1", - "lab_f10", "lf10", - "lab_f2", "lf2", - "lab_f3", "lf3", - "lab_f4", "lf4", - "lab_f5", "lf5", - "lab_f6", "lf6", - "lab_f7", "lf7", - "lab_f8", "lf8", - "lab_f9", "lf9", - "meta_off", "rmm", - "meta_on", "smm", - "newline", "_glitch", - "pad_char", "npc", - "parm_dch", "dch", - "parm_delete_line", "dl", - "parm_down_cursor", "cud", - "parm_ich", "ich", - "parm_index", "indn", - "parm_insert_line", "il", - "parm_left_cursor", "cub", - "parm_right_cursor", "cuf", - "parm_rindex", "rin", - "parm_up_cursor", "cuu", - "pkey_key", "pfkey", - "pkey_local", "pfloc", - "pkey_xmit", "pfx", - "print_screen", "mc0", - "prtr_off", "mc4", - "prtr_on", "mc5", - "repeat_char", "rep", - "reset_1string", "rs1", - "reset_2string", "rs2", - "reset_3string", "rs3", - "reset_file", "rf", - "restore_cursor", "rc", - "row_address", "mvpa", - "save_cursor", "row_address", - "scroll_forward", "ind", - "scroll_reverse", "ri", - "set_attributes", "sgr", - "set_tab", "hts", - "set_window", "wind", - "tab", "s_magic_smso", - "to_status_line", "tsl", - "underline_char", "uc", - "up_half_line", "hu", - "init_prog", "iprog", - "key_a1", "ka1", - "key_a3", "ka3", - "key_b2", "kb2", - "key_c1", "kc1", - "key_c3", "kc3", - "prtr_non", "mc5p", - "char_padding", "rmp", - "acs_chars", "acsc", - "plab_norm", "pln", - "key_btab", "kcbt", - "enter_xon_mode", "smxon", - "exit_xon_mode", "rmxon", - "enter_am_mode", "smam", - "exit_am_mode", "rmam", - "xon_character", "xonc", - "xoff_character", "xoffc", - "ena_acs", "enacs", - "label_on", "smln", - "label_off", "rmln", - "key_beg", "kbeg", - "key_cancel", "kcan", - "key_close", "kclo", - "key_command", "kcmd", - "key_copy", "kcpy", - "key_create", "kcrt", - "key_end", "kend", - "key_enter", "kent", - "key_exit", "kext", - "key_find", "kfnd", - "key_help", "khlp", - "key_mark", "kmrk", - "key_message", "kmsg", - "key_move", "kmov", - "key_next", "knxt", - "key_open", "kopn", - "key_options", "kopt", - "key_previous", "kprv", - "key_print", "kprt", - "key_redo", "krdo", - "key_reference", "kref", - "key_refresh", "krfr", - "key_replace", "krpl", - "key_restart", "krst", - "key_resume", "kres", - "key_save", "ksav", - "key_suspend", "kspd", - "key_undo", "kund", - "key_sbeg", "kBEG", - "key_scancel", "kCAN", - "key_scommand", "kCMD", - "key_scopy", "kCPY", - "key_screate", "kCRT", - "key_sdc", "kDC", - "key_sdl", "kDL", - "key_select", "kslt", - "key_send", "kEND", - "key_seol", "kEOL", - "key_sexit", "kEXT", - "key_sfind", "kFND", - "key_shelp", "kHLP", - "key_shome", "kHOM", - "key_sic", "kIC", - "key_sleft", "kLFT", - "key_smessage", "kMSG", - "key_smove", "kMOV", - "key_snext", "kNXT", - "key_soptions", "kOPT", - "key_sprevious", "kPRV", - "key_sprint", "kPRT", - "key_sredo", "kRDO", - "key_sreplace", "kRPL", - "key_sright", "kRIT", - "key_srsume", "kRES", - "key_ssave", "kSAV", - "key_ssuspend", "kSPD", - "key_sundo", "kUND", - "req_for_input", "rfi", - "key_f11", "kf11", - "key_f12", "kf12", - "key_f13", "kf13", - "key_f14", "kf14", - "key_f15", "kf15", - "key_f16", "kf16", - "key_f17", "kf17", - "key_f18", "kf18", - "key_f19", "kf19", - "key_f20", "kf20", - "key_f21", "kf21", - "key_f22", "kf22", - "key_f23", "kf23", - "key_f24", "kf24", - "key_f25", "kf25", - "key_f26", "kf26", - "key_f27", "kf27", - "key_f28", "kf28", - "key_f29", "kf29", - "key_f30", "kf30", - "key_f31", "kf31", - "key_f32", "kf32", - "key_f33", "kf33", - "key_f34", "kf34", - "key_f35", "kf35", - "key_f36", "kf36", - "key_f37", "kf37", - "key_f38", "kf38", - "key_f39", "kf39", - "key_f40", "kf40", - "key_f41", "kf41", - "key_f42", "kf42", - "key_f43", "kf43", - "key_f44", "kf44", - "key_f45", "kf45", - "key_f46", "kf46", - "key_f47", "kf47", - "key_f48", "kf48", - "key_f49", "kf49", - "key_f50", "kf50", - "key_f51", "kf51", - "key_f52", "kf52", - "key_f53", "kf53", - "key_f54", "kf54", - "key_f55", "kf55", - "key_f56", "kf56", - "key_f57", "kf57", - "key_f58", "kf58", - "key_f59", "kf59", - "key_f60", "kf60", - "key_f61", "kf61", - "key_f62", "kf62", - "key_f63", "kf63", - "clr_bol", "el1", - "clear_margins", "mgc", - "set_left_margin", "smgl", - "set_right_margin", "smgr", - "label_format", "fln", - "set_clock", "sclk", - "display_clock", "dclk", - "remove_clock", "rmclk", - "create_window", "cwin", - "goto_window", "wingo", - "hangup", "hup", - "dial_phone", "dial", - "quick_dial", "qdial", - "tone", "tone", - "pulse", "pulse", - "flash_hook", "hook", - "fixed_pause", "pause", - "wait_tone", "wait", - "user0", "u0", - "user1", "u1", - "user2", "u2", - "user3", "u3", - "user4", "u4", - "user5", "u5", - "user6", "u6", - "user7", "u7", - "user8", "u8", - "user9", "u9", - "orig_pair", "op", - "orig_colors", "oc", - "initialize_color", "initc", - "initialize_pair", "initp", - "set_color_pair", "scp", - "set_foreground", "setf", - "set_background", "setb", - "change_char_pitch", "cpi", - "change_line_pitch", "lpi", - "change_res_horz", "chr", - "change_res_vert", "cvr", - "define_char", "defc", - "enter_doublewide_mode", "swidm", - "enter_draft_quality", "sdrfq", - "enter_italics_mode", "sitm", - "enter_leftward_mode", "slm", - "enter_micro_mode", "smicm", - "enter_near_letter_quality", "snlq", - "enter_normal_quality", "snrmq", - "enter_shadow_mode", "sshm", - "enter_subscript_mode", "ssubm", - "enter_superscript_mode", "ssupm", - "enter_upward_mode", "sum", - "exit_doublewide_mode", "rwidm", - "exit_italics_mode", "ritm", - "exit_leftward_mode", "rlm", - "exit_micro_mode", "rmicm", - "exit_shadow_mode", "rshm", - "exit_subscript_mode", "rsubm", - "exit_superscript_mode", "rsupm", - "exit_upward_mode", "rum", - "micro_column_address", "mhpa", - "micro_down", "mcud1", - "micro_left", "mcub1", - "micro_right", "mcuf1", - "micro_row_address", "mvpa", - "micro_up", "mcuu1", - "order_of_pins", "porder", - "parm_down_micro", "mcud", - "parm_left_micro", "mcub", - "parm_right_micro", "mcuf", - "parm_up_micro", "mcuu", - "select_char_set", "scs", - "set_bottom_margin", "smgb", - "set_bottom_margin_parm", "smgbp", - "set_left_margin_parm", "smglp", - "set_right_margin_parm", "smgrp", - "set_top_margin", "smgt", - "set_top_margin_parm", "smgtp", - "start_bit_image", "sbim", - "start_char_set_def", "scsd", - "stop_bit_image", "rbim", - "stop_char_set_def", "rcsd", - "subscript_characters", "subcs", - "superscript_characters", "supcs", - "these_cause_cr", "docr", - "zero_motion", "zerom", - "char_set_names", "csnm", - "key_mouse", "kmous", - "mouse_info", "minfo", - "req_mouse_pos", "reqmp", - "get_mouse", "getm", - "set_a_foreground", "setaf", - "set_a_background", "setab", - "pkey_plab", "pfxl", - "device_type", "devt", - "code_set_init", "csin", - "set0_des_seq", "s0ds", - "set1_des_seq", "s1ds", - "set2_des_seq", "s2ds", - "set3_des_seq", "s3ds", - "set_lr_margin", "smglr", - "set_tb_margin", "smgtb", - "bit_image_repeat", "birep", - "bit_image_newline", "binel", - "bit_image_carriage_return", "bicr", - "color_names", "colornm", - "define_bit_image_region", "defbi", - "end_bit_image_region", "endbi", - "set_color_band", "setcolor", - "set_page_length", "slines", - "display_pc_char", "dispc", - "enter_pc_charset_mode", "smpch", - "exit_pc_charset_mode", "rmpch", - "enter_scancode_mode", "smsc", - "exit_scancode_mode", "rmsc", - "pc_term_options", "pctrm", - "scancode_escape", "scesc", - "alt_scancode_esc", "scesa", - "enter_horizontal_hl_mode", "ehhlm", - "enter_left_hl_mode", "elhlm", - "enter_low_hl_mode", "elohlm", - "enter_right_hl_mode", "erhlm", - "enter_top_hl_mode", "ethlm", - "enter_vertical_hl_mode", "evhlm", - "set_a_attributes", "sgr1", - "set_pglen_inch", "slength", - "termcap_init2", "", - "termcap_reset", "", - "linefeed_if_not_lf", "", - "backspace_if_not_bs", "", - "other_non_function_keys", "", - "arrow_key_map", "", - "acs_ulcorner", "", - "acs_llcorner", "", - "acs_urcorner", "", - "acs_lrcorner", "", - "acs_ltee", "", - "acs_rtee", "", - "acs_btee", "", - "acs_ttee", "", - "acs_hline", "", - "acs_vline", "", - "acs_plus", "", - "memory_lock", "", - "memory_unlock", "", - "box_chars_1", "", -} diff --git a/vendor/github.com/Nvveen/Gotty/gotty.go b/vendor/github.com/Nvveen/Gotty/gotty.go deleted file mode 100644 index 093cbf37e1..0000000000 --- a/vendor/github.com/Nvveen/Gotty/gotty.go +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright 2012 Neal van Veen. All rights reserved. -// Usage of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Gotty is a Go-package for reading and parsing the terminfo database -package gotty - -// TODO add more concurrency to name lookup, look for more opportunities. - -import ( - "encoding/binary" - "errors" - "fmt" - "os" - "reflect" - "strings" - "sync" -) - -// Open a terminfo file by the name given and construct a TermInfo object. -// If something went wrong reading the terminfo database file, an error is -// returned. -func OpenTermInfo(termName string) (*TermInfo, error) { - var term *TermInfo - var err error - // Find the environment variables - termloc := os.Getenv("TERMINFO") - if len(termloc) == 0 { - // Search like ncurses - locations := []string{os.Getenv("HOME") + "/.terminfo/", "/etc/terminfo/", - "/lib/terminfo/", "/usr/share/terminfo/"} - var path string - for _, str := range locations { - // Construct path - path = str + string(termName[0]) + "/" + termName - // Check if path can be opened - file, _ := os.Open(path) - if file != nil { - // Path can open, fall out and use current path - file.Close() - break - } - } - if len(path) > 0 { - term, err = readTermInfo(path) - } else { - err = errors.New(fmt.Sprintf("No terminfo file(-location) found")) - } - } - return term, err -} - -// Open a terminfo file from the environment variable containing the current -// terminal name and construct a TermInfo object. If something went wrong -// reading the terminfo database file, an error is returned. -func OpenTermInfoEnv() (*TermInfo, error) { - termenv := os.Getenv("TERM") - return OpenTermInfo(termenv) -} - -// Return an attribute by the name attr provided. If none can be found, -// an error is returned. -func (term *TermInfo) GetAttribute(attr string) (stacker, error) { - // Channel to store the main value in. - var value stacker - // Add a blocking WaitGroup - var block sync.WaitGroup - // Keep track of variable being written. - written := false - // Function to put into goroutine. - f := func(ats interface{}) { - var ok bool - var v stacker - // Switch on type of map to use and assign value to it. - switch reflect.TypeOf(ats).Elem().Kind() { - case reflect.Bool: - v, ok = ats.(map[string]bool)[attr] - case reflect.Int16: - v, ok = ats.(map[string]int16)[attr] - case reflect.String: - v, ok = ats.(map[string]string)[attr] - } - // If ok, a value is found, so we can write. - if ok { - value = v - written = true - } - // Goroutine is done - block.Done() - } - block.Add(3) - // Go for all 3 attribute lists. - go f(term.boolAttributes) - go f(term.numAttributes) - go f(term.strAttributes) - // Wait until every goroutine is done. - block.Wait() - // If a value has been written, return it. - if written { - return value, nil - } - // Otherwise, error. - return nil, fmt.Errorf("Erorr finding attribute") -} - -// Return an attribute by the name attr provided. If none can be found, -// an error is returned. A name is first converted to its termcap value. -func (term *TermInfo) GetAttributeName(name string) (stacker, error) { - tc := GetTermcapName(name) - return term.GetAttribute(tc) -} - -// A utility function that finds and returns the termcap equivalent of a -// variable name. -func GetTermcapName(name string) string { - // Termcap name - var tc string - // Blocking group - var wait sync.WaitGroup - // Function to put into a goroutine - f := func(attrs []string) { - // Find the string corresponding to the name - for i, s := range attrs { - if s == name { - tc = attrs[i+1] - } - } - // Goroutine is finished - wait.Done() - } - wait.Add(3) - // Go for all 3 attribute lists - go f(BoolAttr[:]) - go f(NumAttr[:]) - go f(StrAttr[:]) - // Wait until every goroutine is done - wait.Wait() - // Return the termcap name - return tc -} - -// This function takes a path to a terminfo file and reads it in binary -// form to construct the actual TermInfo file. -func readTermInfo(path string) (*TermInfo, error) { - // Open the terminfo file - file, err := os.Open(path) - defer file.Close() - if err != nil { - return nil, err - } - - // magic, nameSize, boolSize, nrSNum, nrOffsetsStr, strSize - // Header is composed of the magic 0432 octal number, size of the name - // section, size of the boolean section, the amount of number values, - // the number of offsets of strings, and the size of the string section. - var header [6]int16 - // Byte array is used to read in byte values - var byteArray []byte - // Short array is used to read in short values - var shArray []int16 - // TermInfo object to store values - var term TermInfo - - // Read in the header - err = binary.Read(file, binary.LittleEndian, &header) - if err != nil { - return nil, err - } - // If magic number isn't there or isn't correct, we have the wrong filetype - if header[0] != 0432 { - return nil, errors.New(fmt.Sprintf("Wrong filetype")) - } - - // Read in the names - byteArray = make([]byte, header[1]) - err = binary.Read(file, binary.LittleEndian, &byteArray) - if err != nil { - return nil, err - } - term.Names = strings.Split(string(byteArray), "|") - - // Read in the booleans - byteArray = make([]byte, header[2]) - err = binary.Read(file, binary.LittleEndian, &byteArray) - if err != nil { - return nil, err - } - term.boolAttributes = make(map[string]bool) - for i, b := range byteArray { - if b == 1 { - term.boolAttributes[BoolAttr[i*2+1]] = true - } - } - // If the number of bytes read is not even, a byte for alignment is added - if len(byteArray)%2 != 0 { - err = binary.Read(file, binary.LittleEndian, make([]byte, 1)) - if err != nil { - return nil, err - } - } - - // Read in shorts - shArray = make([]int16, header[3]) - err = binary.Read(file, binary.LittleEndian, &shArray) - if err != nil { - return nil, err - } - term.numAttributes = make(map[string]int16) - for i, n := range shArray { - if n != 0377 && n > -1 { - term.numAttributes[NumAttr[i*2+1]] = n - } - } - - // Read the offsets into the short array - shArray = make([]int16, header[4]) - err = binary.Read(file, binary.LittleEndian, &shArray) - if err != nil { - return nil, err - } - // Read the actual strings in the byte array - byteArray = make([]byte, header[5]) - err = binary.Read(file, binary.LittleEndian, &byteArray) - if err != nil { - return nil, err - } - term.strAttributes = make(map[string]string) - // We get an offset, and then iterate until the string is null-terminated - for i, offset := range shArray { - if offset > -1 { - r := offset - for ; byteArray[r] != 0; r++ { - } - term.strAttributes[StrAttr[i*2+1]] = string(byteArray[offset:r]) - } - } - return &term, nil -} diff --git a/vendor/github.com/Nvveen/Gotty/parser.go b/vendor/github.com/Nvveen/Gotty/parser.go deleted file mode 100644 index a9d5d23c54..0000000000 --- a/vendor/github.com/Nvveen/Gotty/parser.go +++ /dev/null @@ -1,362 +0,0 @@ -// Copyright 2012 Neal van Veen. All rights reserved. -// Usage of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package gotty - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -var exp = [...]string{ - "%%", - "%c", - "%s", - "%p(\\d)", - "%P([A-z])", - "%g([A-z])", - "%'(.)'", - "%{([0-9]+)}", - "%l", - "%\\+|%-|%\\*|%/|%m", - "%&|%\\||%\\^", - "%=|%>|%<", - "%A|%O", - "%!|%~", - "%i", - "%(:[\\ #\\-\\+]{0,4})?(\\d+\\.\\d+|\\d+)?[doxXs]", - "%\\?(.*?);", -} - -var regex *regexp.Regexp -var staticVar map[byte]stacker - -// Parses the attribute that is received with name attr and parameters params. -func (term *TermInfo) Parse(attr string, params ...interface{}) (string, error) { - // Get the attribute name first. - iface, err := term.GetAttribute(attr) - str, ok := iface.(string) - if err != nil { - return "", err - } - if !ok { - return str, errors.New("Only string capabilities can be parsed.") - } - // Construct the hidden parser struct so we can use a recursive stack based - // parser. - ps := &parser{} - // Dynamic variables only exist in this context. - ps.dynamicVar = make(map[byte]stacker, 26) - ps.parameters = make([]stacker, len(params)) - // Convert the parameters to insert them into the parser struct. - for i, x := range params { - ps.parameters[i] = x - } - // Recursively walk and return. - result, err := ps.walk(str) - return result, err -} - -// Parses the attribute that is received with name attr and parameters params. -// Only works on full name of a capability that is given, which it uses to -// search for the termcap name. -func (term *TermInfo) ParseName(attr string, params ...interface{}) (string, error) { - tc := GetTermcapName(attr) - return term.Parse(tc, params) -} - -// Identify each token in a stack based manner and do the actual parsing. -func (ps *parser) walk(attr string) (string, error) { - // We use a buffer to get the modified string. - var buf bytes.Buffer - // Next, find and identify all tokens by their indices and strings. - tokens := regex.FindAllStringSubmatch(attr, -1) - if len(tokens) == 0 { - return attr, nil - } - indices := regex.FindAllStringIndex(attr, -1) - q := 0 // q counts the matches of one token - // Iterate through the string per character. - for i := 0; i < len(attr); i++ { - // If the current position is an identified token, execute the following - // steps. - if q < len(indices) && i >= indices[q][0] && i < indices[q][1] { - // Switch on token. - switch { - case tokens[q][0][:2] == "%%": - // Literal percentage character. - buf.WriteByte('%') - case tokens[q][0][:2] == "%c": - // Pop a character. - c, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - buf.WriteByte(c.(byte)) - case tokens[q][0][:2] == "%s": - // Pop a string. - str, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - if _, ok := str.(string); !ok { - return buf.String(), errors.New("Stack head is not a string") - } - buf.WriteString(str.(string)) - case tokens[q][0][:2] == "%p": - // Push a parameter on the stack. - index, err := strconv.ParseInt(tokens[q][1], 10, 8) - index-- - if err != nil { - return buf.String(), err - } - if int(index) >= len(ps.parameters) { - return buf.String(), errors.New("Parameters index out of bound") - } - ps.st.push(ps.parameters[index]) - case tokens[q][0][:2] == "%P": - // Pop a variable from the stack as a dynamic or static variable. - val, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - index := tokens[q][2] - if len(index) > 1 { - errorStr := fmt.Sprintf("%s is not a valid dynamic variables index", - index) - return buf.String(), errors.New(errorStr) - } - // Specify either dynamic or static. - if index[0] >= 'a' && index[0] <= 'z' { - ps.dynamicVar[index[0]] = val - } else if index[0] >= 'A' && index[0] <= 'Z' { - staticVar[index[0]] = val - } - case tokens[q][0][:2] == "%g": - // Push a variable from the stack as a dynamic or static variable. - index := tokens[q][3] - if len(index) > 1 { - errorStr := fmt.Sprintf("%s is not a valid static variables index", - index) - return buf.String(), errors.New(errorStr) - } - var val stacker - if index[0] >= 'a' && index[0] <= 'z' { - val = ps.dynamicVar[index[0]] - } else if index[0] >= 'A' && index[0] <= 'Z' { - val = staticVar[index[0]] - } - ps.st.push(val) - case tokens[q][0][:2] == "%'": - // Push a character constant. - con := tokens[q][4] - if len(con) > 1 { - errorStr := fmt.Sprintf("%s is not a valid character constant", con) - return buf.String(), errors.New(errorStr) - } - ps.st.push(con[0]) - case tokens[q][0][:2] == "%{": - // Push an integer constant. - con, err := strconv.ParseInt(tokens[q][5], 10, 32) - if err != nil { - return buf.String(), err - } - ps.st.push(con) - case tokens[q][0][:2] == "%l": - // Push the length of the string that is popped from the stack. - popStr, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - if _, ok := popStr.(string); !ok { - errStr := fmt.Sprintf("Stack head is not a string") - return buf.String(), errors.New(errStr) - } - ps.st.push(len(popStr.(string))) - case tokens[q][0][:2] == "%?": - // If-then-else construct. First, the whole string is identified and - // then inside this substring, we can specify which parts to switch on. - ifReg, _ := regexp.Compile("%\\?(.*)%t(.*)%e(.*);|%\\?(.*)%t(.*);") - ifTokens := ifReg.FindStringSubmatch(tokens[q][0]) - var ( - ifStr string - err error - ) - // Parse the if-part to determine if-else. - if len(ifTokens[1]) > 0 { - ifStr, err = ps.walk(ifTokens[1]) - } else { // else - ifStr, err = ps.walk(ifTokens[4]) - } - // Return any errors - if err != nil { - return buf.String(), err - } else if len(ifStr) > 0 { - // Self-defined limitation, not sure if this is correct, but didn't - // seem like it. - return buf.String(), errors.New("If-clause cannot print statements") - } - var thenStr string - // Pop the first value that is set by parsing the if-clause. - choose, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - // Switch to if or else. - if choose.(int) == 0 && len(ifTokens[1]) > 0 { - thenStr, err = ps.walk(ifTokens[3]) - } else if choose.(int) != 0 { - if len(ifTokens[1]) > 0 { - thenStr, err = ps.walk(ifTokens[2]) - } else { - thenStr, err = ps.walk(ifTokens[5]) - } - } - if err != nil { - return buf.String(), err - } - buf.WriteString(thenStr) - case tokens[q][0][len(tokens[q][0])-1] == 'd': // Fallthrough for printing - fallthrough - case tokens[q][0][len(tokens[q][0])-1] == 'o': // digits. - fallthrough - case tokens[q][0][len(tokens[q][0])-1] == 'x': - fallthrough - case tokens[q][0][len(tokens[q][0])-1] == 'X': - fallthrough - case tokens[q][0][len(tokens[q][0])-1] == 's': - token := tokens[q][0] - // Remove the : that comes before a flag. - if token[1] == ':' { - token = token[:1] + token[2:] - } - digit, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - // The rest is determined like the normal formatted prints. - digitStr := fmt.Sprintf(token, digit.(int)) - buf.WriteString(digitStr) - case tokens[q][0][:2] == "%i": - // Increment the parameters by one. - if len(ps.parameters) < 2 { - return buf.String(), errors.New("Not enough parameters to increment.") - } - val1, val2 := ps.parameters[0].(int), ps.parameters[1].(int) - val1++ - val2++ - ps.parameters[0], ps.parameters[1] = val1, val2 - default: - // The rest of the tokens is a special case, where two values are - // popped and then operated on by the token that comes after them. - op1, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - op2, err := ps.st.pop() - if err != nil { - return buf.String(), err - } - var result stacker - switch tokens[q][0][:2] { - case "%+": - // Addition - result = op2.(int) + op1.(int) - case "%-": - // Subtraction - result = op2.(int) - op1.(int) - case "%*": - // Multiplication - result = op2.(int) * op1.(int) - case "%/": - // Division - result = op2.(int) / op1.(int) - case "%m": - // Modulo - result = op2.(int) % op1.(int) - case "%&": - // Bitwise AND - result = op2.(int) & op1.(int) - case "%|": - // Bitwise OR - result = op2.(int) | op1.(int) - case "%^": - // Bitwise XOR - result = op2.(int) ^ op1.(int) - case "%=": - // Equals - result = op2 == op1 - case "%>": - // Greater-than - result = op2.(int) > op1.(int) - case "%<": - // Lesser-than - result = op2.(int) < op1.(int) - case "%A": - // Logical AND - result = op2.(bool) && op1.(bool) - case "%O": - // Logical OR - result = op2.(bool) || op1.(bool) - case "%!": - // Logical complement - result = !op1.(bool) - case "%~": - // Bitwise complement - result = ^(op1.(int)) - } - ps.st.push(result) - } - - i = indices[q][1] - 1 - q++ - } else { - // We are not "inside" a token, so just skip until the end or the next - // token, and add all characters to the buffer. - j := i - if q != len(indices) { - for !(j >= indices[q][0] && j < indices[q][1]) { - j++ - } - } else { - j = len(attr) - } - buf.WriteString(string(attr[i:j])) - i = j - } - } - // Return the buffer as a string. - return buf.String(), nil -} - -// Push a stacker-value onto the stack. -func (st *stack) push(s stacker) { - *st = append(*st, s) -} - -// Pop a stacker-value from the stack. -func (st *stack) pop() (stacker, error) { - if len(*st) == 0 { - return nil, errors.New("Stack is empty.") - } - newStack := make(stack, len(*st)-1) - val := (*st)[len(*st)-1] - copy(newStack, (*st)[:len(*st)-1]) - *st = newStack - return val, nil -} - -// Initialize regexes and the static vars (that don't get changed between -// calls. -func init() { - // Initialize the main regex. - expStr := strings.Join(exp[:], "|") - regex, _ = regexp.Compile(expStr) - // Initialize the static variables. - staticVar = make(map[byte]stacker, 26) -} diff --git a/vendor/github.com/Nvveen/Gotty/types.go b/vendor/github.com/Nvveen/Gotty/types.go deleted file mode 100644 index 9bcc65e9b8..0000000000 --- a/vendor/github.com/Nvveen/Gotty/types.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2012 Neal van Veen. All rights reserved. -// Usage of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -package gotty - -type TermInfo struct { - boolAttributes map[string]bool - numAttributes map[string]int16 - strAttributes map[string]string - // The various names of the TermInfo file. - Names []string -} - -type stacker interface { -} -type stack []stacker - -type parser struct { - st stack - parameters []stacker - dynamicVar map[byte]stacker -} diff --git a/vendor/github.com/PuerkitoBio/purell/LICENSE b/vendor/github.com/PuerkitoBio/purell/LICENSE deleted file mode 100644 index 4b9986dea7..0000000000 --- a/vendor/github.com/PuerkitoBio/purell/LICENSE +++ /dev/null @@ -1,12 +0,0 @@ -Copyright (c) 2012, Martin Angers -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -* Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/purell/README.md b/vendor/github.com/PuerkitoBio/purell/README.md deleted file mode 100644 index f33e2e9d77..0000000000 --- a/vendor/github.com/PuerkitoBio/purell/README.md +++ /dev/null @@ -1,187 +0,0 @@ -# Purell - -Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know... - -Based on the [wikipedia paper][wiki] and the [RFC 3986 document][rfc]. - -[![build status](https://travis-ci.org/PuerkitoBio/purell.svg?branch=master)](http://travis-ci.org/PuerkitoBio/purell) - -## Install - -`go get github.com/PuerkitoBio/purell` - -## Changelog - -* **2016-11-14 (v1.1.0)** : IDN: Conform to RFC 5895: Fold character width (thanks to @beeker1121). -* **2016-07-27 (v1.0.0)** : Normalize IDN to ASCII (thanks to @zenovich). -* **2015-02-08** : Add fix for relative paths issue ([PR #5][pr5]) and add fix for unnecessary encoding of reserved characters ([see issue #7][iss7]). -* **v0.2.0** : Add benchmarks, Attempt IDN support. -* **v0.1.0** : Initial release. - -## Examples - -From `example_test.go` (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."): - -```go -package purell - -import ( - "fmt" - "net/url" -) - -func ExampleNormalizeURLString() { - if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/", - FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil { - panic(err) - } else { - fmt.Print(normalized) - } - // Output: http://somewebsite.com:80/Amazing%3F/url/ -} - -func ExampleMustNormalizeURLString() { - normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/", - FlagsUnsafeGreedy) - fmt.Print(normalized) - - // Output: http://somewebsite.com/Amazing%FA/url -} - -func ExampleNormalizeURL() { - if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil { - panic(err) - } else { - normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment) - fmt.Print(normalized) - } - - // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0 -} -``` - -## API - -As seen in the examples above, purell offers three methods, `NormalizeURLString(string, NormalizationFlags) (string, error)`, `MustNormalizeURLString(string, NormalizationFlags) (string)` and `NormalizeURL(*url.URL, NormalizationFlags) (string)`. They all normalize the provided URL based on the specified flags. Here are the available flags: - -```go -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) -``` - -For convenience, the set of flags `FlagsSafe`, `FlagsUsuallySafe[Greedy|NonGreedy]`, `FlagsUnsafe[Greedy|NonGreedy]` and `FlagsAll[Greedy|NonGreedy]` are provided for the similarly grouped normalizations on [wikipedia's URL normalization page][wiki]. You can add (using the bitwise OR `|` operator) or remove (using the bitwise AND NOT `&^` operator) individual flags from the sets if required, to build your own custom set. - -The [full godoc reference is available on gopkgdoc][godoc]. - -Some things to note: - -* `FlagDecodeUnnecessaryEscapes`, `FlagEncodeNecessaryEscapes`, `FlagUppercaseEscapes` and `FlagRemoveEmptyQuerySeparator` are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary `?` at the end of the url). So this operation cannot **not** be done. For this reason, `FlagRemoveEmptyQuerySeparator` (as well as the other three) has been included in the `FlagsSafe` convenience set, instead of `FlagsUnsafe`, where Wikipedia puts it. - -* The `FlagDecodeUnnecessaryEscapes` decodes the following escapes (*from -> to*): - - %24 -> $ - - %26 -> & - - %2B-%3B -> +,-./0123456789:; - - %3D -> = - - %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ - - %5F -> _ - - %61-%7A -> abcdefghijklmnopqrstuvwxyz - - %7E -> ~ - - -* When the `NormalizeURL` function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization). - -* The *replace IP with domain name* normalization (`http://208.77.188.166/ → http://www.example.com/`) is obviously not possible for a library without making some network requests. This is not implemented in purell. - -* The *remove unused query string parameters* and *remove default query parameters* are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object. - -### Safe vs Usually Safe vs Unsafe - -Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between. - -Consider the following URL: - -`HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -Normalizing with the `FlagsSafe` gives: - -`https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid` - -With the `FlagsUsuallySafeGreedy`: - -`https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid` - -And with `FlagsUnsafeGreedy`: - -`http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3` - -## TODOs - -* Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes `(^|/)((?:default|index)\.\w{1,4})$`. - -## Thanks / Contributions - -@rogpeppe -@jehiah -@opennota -@pchristopher1275 -@zenovich -@beeker1121 - -## License - -The [BSD 3-Clause license][bsd]. - -[bsd]: http://opensource.org/licenses/BSD-3-Clause -[wiki]: http://en.wikipedia.org/wiki/URL_normalization -[rfc]: http://tools.ietf.org/html/rfc3986#section-6 -[godoc]: http://go.pkgdoc.org/github.com/PuerkitoBio/purell -[pr5]: https://github.com/PuerkitoBio/purell/pull/5 -[iss7]: https://github.com/PuerkitoBio/purell/issues/7 diff --git a/vendor/github.com/PuerkitoBio/purell/purell.go b/vendor/github.com/PuerkitoBio/purell/purell.go deleted file mode 100644 index 6d0fc190a1..0000000000 --- a/vendor/github.com/PuerkitoBio/purell/purell.go +++ /dev/null @@ -1,379 +0,0 @@ -/* -Package purell offers URL normalization as described on the wikipedia page: -http://en.wikipedia.org/wiki/URL_normalization -*/ -package purell - -import ( - "bytes" - "fmt" - "net/url" - "regexp" - "sort" - "strconv" - "strings" - - "github.com/PuerkitoBio/urlesc" - "golang.org/x/net/idna" - "golang.org/x/text/unicode/norm" - "golang.org/x/text/width" -) - -// A set of normalization flags determines how a URL will -// be normalized. -type NormalizationFlags uint - -const ( - // Safe normalizations - FlagLowercaseScheme NormalizationFlags = 1 << iota // HTTP://host -> http://host, applied by default in Go1.1 - FlagLowercaseHost // http://HOST -> http://host - FlagUppercaseEscapes // http://host/t%ef -> http://host/t%EF - FlagDecodeUnnecessaryEscapes // http://host/t%41 -> http://host/tA - FlagEncodeNecessaryEscapes // http://host/!"#$ -> http://host/%21%22#$ - FlagRemoveDefaultPort // http://host:80 -> http://host - FlagRemoveEmptyQuerySeparator // http://host/path? -> http://host/path - - // Usually safe normalizations - FlagRemoveTrailingSlash // http://host/path/ -> http://host/path - FlagAddTrailingSlash // http://host/path -> http://host/path/ (should choose only one of these add/remove trailing slash flags) - FlagRemoveDotSegments // http://host/path/./a/b/../c -> http://host/path/a/c - - // Unsafe normalizations - FlagRemoveDirectoryIndex // http://host/path/index.html -> http://host/path/ - FlagRemoveFragment // http://host/path#fragment -> http://host/path - FlagForceHTTP // https://host -> http://host - FlagRemoveDuplicateSlashes // http://host/path//a///b -> http://host/path/a/b - FlagRemoveWWW // http://www.host/ -> http://host/ - FlagAddWWW // http://host/ -> http://www.host/ (should choose only one of these add/remove WWW flags) - FlagSortQuery // http://host/path?c=3&b=2&a=1&b=1 -> http://host/path?a=1&b=1&b=2&c=3 - - // Normalizations not in the wikipedia article, required to cover tests cases - // submitted by jehiah - FlagDecodeDWORDHost // http://1113982867 -> http://66.102.7.147 - FlagDecodeOctalHost // http://0102.0146.07.0223 -> http://66.102.7.147 - FlagDecodeHexHost // http://0x42660793 -> http://66.102.7.147 - FlagRemoveUnnecessaryHostDots // http://.host../path -> http://host/path - FlagRemoveEmptyPortSeparator // http://host:/path -> http://host/path - - // Convenience set of safe normalizations - FlagsSafe NormalizationFlags = FlagLowercaseHost | FlagLowercaseScheme | FlagUppercaseEscapes | FlagDecodeUnnecessaryEscapes | FlagEncodeNecessaryEscapes | FlagRemoveDefaultPort | FlagRemoveEmptyQuerySeparator - - // For convenience sets, "greedy" uses the "remove trailing slash" and "remove www. prefix" flags, - // while "non-greedy" uses the "add (or keep) the trailing slash" and "add www. prefix". - - // Convenience set of usually safe normalizations (includes FlagsSafe) - FlagsUsuallySafeGreedy NormalizationFlags = FlagsSafe | FlagRemoveTrailingSlash | FlagRemoveDotSegments - FlagsUsuallySafeNonGreedy NormalizationFlags = FlagsSafe | FlagAddTrailingSlash | FlagRemoveDotSegments - - // Convenience set of unsafe normalizations (includes FlagsUsuallySafe) - FlagsUnsafeGreedy NormalizationFlags = FlagsUsuallySafeGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagRemoveWWW | FlagSortQuery - FlagsUnsafeNonGreedy NormalizationFlags = FlagsUsuallySafeNonGreedy | FlagRemoveDirectoryIndex | FlagRemoveFragment | FlagForceHTTP | FlagRemoveDuplicateSlashes | FlagAddWWW | FlagSortQuery - - // Convenience set of all available flags - FlagsAllGreedy = FlagsUnsafeGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator - FlagsAllNonGreedy = FlagsUnsafeNonGreedy | FlagDecodeDWORDHost | FlagDecodeOctalHost | FlagDecodeHexHost | FlagRemoveUnnecessaryHostDots | FlagRemoveEmptyPortSeparator -) - -const ( - defaultHttpPort = ":80" - defaultHttpsPort = ":443" -) - -// Regular expressions used by the normalizations -var rxPort = regexp.MustCompile(`(:\d+)/?$`) -var rxDirIndex = regexp.MustCompile(`(^|/)((?:default|index)\.\w{1,4})$`) -var rxDupSlashes = regexp.MustCompile(`/{2,}`) -var rxDWORDHost = regexp.MustCompile(`^(\d+)((?:\.+)?(?:\:\d*)?)$`) -var rxOctalHost = regexp.MustCompile(`^(0\d*)\.(0\d*)\.(0\d*)\.(0\d*)((?:\.+)?(?:\:\d*)?)$`) -var rxHexHost = regexp.MustCompile(`^0x([0-9A-Fa-f]+)((?:\.+)?(?:\:\d*)?)$`) -var rxHostDots = regexp.MustCompile(`^(.+?)(:\d+)?$`) -var rxEmptyPort = regexp.MustCompile(`:+$`) - -// Map of flags to implementation function. -// FlagDecodeUnnecessaryEscapes has no action, since it is done automatically -// by parsing the string as an URL. Same for FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator. - -// Since maps have undefined traversing order, make a slice of ordered keys -var flagsOrder = []NormalizationFlags{ - FlagLowercaseScheme, - FlagLowercaseHost, - FlagRemoveDefaultPort, - FlagRemoveDirectoryIndex, - FlagRemoveDotSegments, - FlagRemoveFragment, - FlagForceHTTP, // Must be after remove default port (because https=443/http=80) - FlagRemoveDuplicateSlashes, - FlagRemoveWWW, - FlagAddWWW, - FlagSortQuery, - FlagDecodeDWORDHost, - FlagDecodeOctalHost, - FlagDecodeHexHost, - FlagRemoveUnnecessaryHostDots, - FlagRemoveEmptyPortSeparator, - FlagRemoveTrailingSlash, // These two (add/remove trailing slash) must be last - FlagAddTrailingSlash, -} - -// ... and then the map, where order is unimportant -var flags = map[NormalizationFlags]func(*url.URL){ - FlagLowercaseScheme: lowercaseScheme, - FlagLowercaseHost: lowercaseHost, - FlagRemoveDefaultPort: removeDefaultPort, - FlagRemoveDirectoryIndex: removeDirectoryIndex, - FlagRemoveDotSegments: removeDotSegments, - FlagRemoveFragment: removeFragment, - FlagForceHTTP: forceHTTP, - FlagRemoveDuplicateSlashes: removeDuplicateSlashes, - FlagRemoveWWW: removeWWW, - FlagAddWWW: addWWW, - FlagSortQuery: sortQuery, - FlagDecodeDWORDHost: decodeDWORDHost, - FlagDecodeOctalHost: decodeOctalHost, - FlagDecodeHexHost: decodeHexHost, - FlagRemoveUnnecessaryHostDots: removeUnncessaryHostDots, - FlagRemoveEmptyPortSeparator: removeEmptyPortSeparator, - FlagRemoveTrailingSlash: removeTrailingSlash, - FlagAddTrailingSlash: addTrailingSlash, -} - -// MustNormalizeURLString returns the normalized string, and panics if an error occurs. -// It takes an URL string as input, as well as the normalization flags. -func MustNormalizeURLString(u string, f NormalizationFlags) string { - result, e := NormalizeURLString(u, f) - if e != nil { - panic(e) - } - return result -} - -// NormalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. -// It takes an URL string as input, as well as the normalization flags. -func NormalizeURLString(u string, f NormalizationFlags) (string, error) { - parsed, err := url.Parse(u) - if err != nil { - return "", err - } - - if f&FlagLowercaseHost == FlagLowercaseHost { - parsed.Host = strings.ToLower(parsed.Host) - } - - // The idna package doesn't fully conform to RFC 5895 - // (https://tools.ietf.org/html/rfc5895), so we do it here. - // Taken from Go 1.8 cycle source, courtesy of bradfitz. - // TODO: Remove when (if?) idna package conforms to RFC 5895. - parsed.Host = width.Fold.String(parsed.Host) - parsed.Host = norm.NFC.String(parsed.Host) - if parsed.Host, err = idna.ToASCII(parsed.Host); err != nil { - return "", err - } - - return NormalizeURL(parsed, f), nil -} - -// NormalizeURL returns the normalized string. -// It takes a parsed URL object as input, as well as the normalization flags. -func NormalizeURL(u *url.URL, f NormalizationFlags) string { - for _, k := range flagsOrder { - if f&k == k { - flags[k](u) - } - } - return urlesc.Escape(u) -} - -func lowercaseScheme(u *url.URL) { - if len(u.Scheme) > 0 { - u.Scheme = strings.ToLower(u.Scheme) - } -} - -func lowercaseHost(u *url.URL) { - if len(u.Host) > 0 { - u.Host = strings.ToLower(u.Host) - } -} - -func removeDefaultPort(u *url.URL) { - if len(u.Host) > 0 { - scheme := strings.ToLower(u.Scheme) - u.Host = rxPort.ReplaceAllStringFunc(u.Host, func(val string) string { - if (scheme == "http" && val == defaultHttpPort) || (scheme == "https" && val == defaultHttpsPort) { - return "" - } - return val - }) - } -} - -func removeTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if strings.HasSuffix(u.Path, "/") { - u.Path = u.Path[:l-1] - } - } else if l = len(u.Host); l > 0 { - if strings.HasSuffix(u.Host, "/") { - u.Host = u.Host[:l-1] - } - } -} - -func addTrailingSlash(u *url.URL) { - if l := len(u.Path); l > 0 { - if !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } else if l = len(u.Host); l > 0 { - if !strings.HasSuffix(u.Host, "/") { - u.Host += "/" - } - } -} - -func removeDotSegments(u *url.URL) { - if len(u.Path) > 0 { - var dotFree []string - var lastIsDot bool - - sections := strings.Split(u.Path, "/") - for _, s := range sections { - if s == ".." { - if len(dotFree) > 0 { - dotFree = dotFree[:len(dotFree)-1] - } - } else if s != "." { - dotFree = append(dotFree, s) - } - lastIsDot = (s == "." || s == "..") - } - // Special case if host does not end with / and new path does not begin with / - u.Path = strings.Join(dotFree, "/") - if u.Host != "" && !strings.HasSuffix(u.Host, "/") && !strings.HasPrefix(u.Path, "/") { - u.Path = "/" + u.Path - } - // Special case if the last segment was a dot, make sure the path ends with a slash - if lastIsDot && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - } - } -} - -func removeDirectoryIndex(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDirIndex.ReplaceAllString(u.Path, "$1") - } -} - -func removeFragment(u *url.URL) { - u.Fragment = "" -} - -func forceHTTP(u *url.URL) { - if strings.ToLower(u.Scheme) == "https" { - u.Scheme = "http" - } -} - -func removeDuplicateSlashes(u *url.URL) { - if len(u.Path) > 0 { - u.Path = rxDupSlashes.ReplaceAllString(u.Path, "/") - } -} - -func removeWWW(u *url.URL) { - if len(u.Host) > 0 && strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = u.Host[4:] - } -} - -func addWWW(u *url.URL) { - if len(u.Host) > 0 && !strings.HasPrefix(strings.ToLower(u.Host), "www.") { - u.Host = "www." + u.Host - } -} - -func sortQuery(u *url.URL) { - q := u.Query() - - if len(q) > 0 { - arKeys := make([]string, len(q)) - i := 0 - for k := range q { - arKeys[i] = k - i++ - } - sort.Strings(arKeys) - buf := new(bytes.Buffer) - for _, k := range arKeys { - sort.Strings(q[k]) - for _, v := range q[k] { - if buf.Len() > 0 { - buf.WriteRune('&') - } - buf.WriteString(fmt.Sprintf("%s=%s", k, urlesc.QueryEscape(v))) - } - } - - // Rebuild the raw query string - u.RawQuery = buf.String() - } -} - -func decodeDWORDHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxDWORDHost.FindStringSubmatch(u.Host); len(matches) > 2 { - var parts [4]int64 - - dword, _ := strconv.ParseInt(matches[1], 10, 0) - for i, shift := range []uint{24, 16, 8, 0} { - parts[i] = dword >> shift & 0xFF - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[2]) - } - } -} - -func decodeOctalHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxOctalHost.FindStringSubmatch(u.Host); len(matches) > 5 { - var parts [4]int64 - - for i := 1; i <= 4; i++ { - parts[i-1], _ = strconv.ParseInt(matches[i], 8, 0) - } - u.Host = fmt.Sprintf("%d.%d.%d.%d%s", parts[0], parts[1], parts[2], parts[3], matches[5]) - } - } -} - -func decodeHexHost(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHexHost.FindStringSubmatch(u.Host); len(matches) > 2 { - // Conversion is safe because of regex validation - parsed, _ := strconv.ParseInt(matches[1], 16, 0) - // Set host as DWORD (base 10) encoded host - u.Host = fmt.Sprintf("%d%s", parsed, matches[2]) - // The rest is the same as decoding a DWORD host - decodeDWORDHost(u) - } - } -} - -func removeUnncessaryHostDots(u *url.URL) { - if len(u.Host) > 0 { - if matches := rxHostDots.FindStringSubmatch(u.Host); len(matches) > 1 { - // Trim the leading and trailing dots - u.Host = strings.Trim(matches[1], ".") - if len(matches) > 2 { - u.Host += matches[2] - } - } - } -} - -func removeEmptyPortSeparator(u *url.URL) { - if len(u.Host) > 0 { - u.Host = rxEmptyPort.ReplaceAllString(u.Host, "") - } -} diff --git a/vendor/github.com/PuerkitoBio/urlesc/LICENSE b/vendor/github.com/PuerkitoBio/urlesc/LICENSE deleted file mode 100644 index 7448756763..0000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/PuerkitoBio/urlesc/README.md b/vendor/github.com/PuerkitoBio/urlesc/README.md deleted file mode 100644 index 57aff0a539..0000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/README.md +++ /dev/null @@ -1,16 +0,0 @@ -urlesc [![Build Status](https://travis-ci.org/PuerkitoBio/urlesc.svg?branch=master)](https://travis-ci.org/PuerkitoBio/urlesc) [![GoDoc](http://godoc.org/github.com/PuerkitoBio/urlesc?status.svg)](http://godoc.org/github.com/PuerkitoBio/urlesc) -====== - -Package urlesc implements query escaping as per RFC 3986. - -It contains some parts of the net/url package, modified so as to allow -some reserved characters incorrectly escaped by net/url (see [issue 5684](https://github.com/golang/go/issues/5684)). - -## Install - - go get github.com/PuerkitoBio/urlesc - -## License - -Go license (BSD-3-Clause) - diff --git a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go b/vendor/github.com/PuerkitoBio/urlesc/urlesc.go deleted file mode 100644 index 1b84624594..0000000000 --- a/vendor/github.com/PuerkitoBio/urlesc/urlesc.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2009 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 urlesc implements query escaping as per RFC 3986. -// It contains some parts of the net/url package, modified so as to allow -// some reserved characters incorrectly escaped by net/url. -// See https://github.com/golang/go/issues/5684 -package urlesc - -import ( - "bytes" - "net/url" - "strings" -) - -type encoding int - -const ( - encodePath encoding = 1 + iota - encodeUserPassword - encodeQueryComponent - encodeFragment -) - -// Return true if the specified character should be escaped when -// appearing in a URL string, according to RFC 3986. -func shouldEscape(c byte, mode encoding) bool { - // §2.3 Unreserved characters (alphanum) - if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { - return false - } - - switch c { - case '-', '.', '_', '~': // §2.3 Unreserved characters (mark) - return false - - // §2.2 Reserved characters (reserved) - case ':', '/', '?', '#', '[', ']', '@', // gen-delims - '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': // sub-delims - // Different sections of the URL allow a few of - // the reserved characters to appear unescaped. - switch mode { - case encodePath: // §3.3 - // The RFC allows sub-delims and : @. - // '/', '[' and ']' can be used to assign meaning to individual path - // segments. This package only manipulates the path as a whole, - // so we allow those as well. That leaves only ? and # to escape. - return c == '?' || c == '#' - - case encodeUserPassword: // §3.2.1 - // The RFC allows : and sub-delims in - // userinfo. The parsing of userinfo treats ':' as special so we must escape - // all the gen-delims. - return c == ':' || c == '/' || c == '?' || c == '#' || c == '[' || c == ']' || c == '@' - - case encodeQueryComponent: // §3.4 - // The RFC allows / and ?. - return c != '/' && c != '?' - - case encodeFragment: // §4.1 - // The RFC text is silent but the grammar allows - // everything, so escape nothing but # - return c == '#' - } - } - - // Everything else must be escaped. - return true -} - -// QueryEscape escapes the string so it can be safely placed -// inside a URL query. -func QueryEscape(s string) string { - return escape(s, encodeQueryComponent) -} - -func escape(s string, mode encoding) string { - spaceCount, hexCount := 0, 0 - for i := 0; i < len(s); i++ { - c := s[i] - if shouldEscape(c, mode) { - if c == ' ' && mode == encodeQueryComponent { - spaceCount++ - } else { - hexCount++ - } - } - } - - if spaceCount == 0 && hexCount == 0 { - return s - } - - t := make([]byte, len(s)+2*hexCount) - j := 0 - for i := 0; i < len(s); i++ { - switch c := s[i]; { - case c == ' ' && mode == encodeQueryComponent: - t[j] = '+' - j++ - case shouldEscape(c, mode): - t[j] = '%' - t[j+1] = "0123456789ABCDEF"[c>>4] - t[j+2] = "0123456789ABCDEF"[c&15] - j += 3 - default: - t[j] = s[i] - j++ - } - } - return string(t) -} - -var uiReplacer = strings.NewReplacer( - "%21", "!", - "%27", "'", - "%28", "(", - "%29", ")", - "%2A", "*", -) - -// unescapeUserinfo unescapes some characters that need not to be escaped as per RFC3986. -func unescapeUserinfo(s string) string { - return uiReplacer.Replace(s) -} - -// Escape reassembles the URL into a valid URL string. -// The general form of the result is one of: -// -// scheme:opaque -// scheme://userinfo@host/path?query#fragment -// -// If u.Opaque is non-empty, String uses the first form; -// otherwise it uses the second form. -// -// In the second form, the following rules apply: -// - if u.Scheme is empty, scheme: is omitted. -// - if u.User is nil, userinfo@ is omitted. -// - if u.Host is empty, host/ is omitted. -// - if u.Scheme and u.Host are empty and u.User is nil, -// the entire scheme://userinfo@host/ is omitted. -// - if u.Host is non-empty and u.Path begins with a /, -// the form host/path does not add its own /. -// - if u.RawQuery is empty, ?query is omitted. -// - if u.Fragment is empty, #fragment is omitted. -func Escape(u *url.URL) string { - var buf bytes.Buffer - if u.Scheme != "" { - buf.WriteString(u.Scheme) - buf.WriteByte(':') - } - if u.Opaque != "" { - buf.WriteString(u.Opaque) - } else { - if u.Scheme != "" || u.Host != "" || u.User != nil { - buf.WriteString("//") - if ui := u.User; ui != nil { - buf.WriteString(unescapeUserinfo(ui.String())) - buf.WriteByte('@') - } - if h := u.Host; h != "" { - buf.WriteString(h) - } - } - if u.Path != "" && u.Path[0] != '/' && u.Host != "" { - buf.WriteByte('/') - } - buf.WriteString(escape(u.Path, encodePath)) - } - if u.RawQuery != "" { - buf.WriteByte('?') - buf.WriteString(u.RawQuery) - } - if u.Fragment != "" { - buf.WriteByte('#') - buf.WriteString(escape(u.Fragment, encodeFragment)) - } - return buf.String() -} diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md deleted file mode 100644 index 747e4d89a2..0000000000 --- a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md +++ /dev/null @@ -1,94 +0,0 @@ -# 0.11.5 - -* feature: add writer and writerlevel to entry (#372) - -# 0.11.4 - -* bug: fix undefined variable on solaris (#493) - -# 0.11.3 - -* formatter: configure quoting of empty values (#484) -* formatter: configure quoting character (default is `"`) (#484) -* bug: fix not importing io correctly in non-linux environments (#481) - -# 0.11.2 - -* bug: fix windows terminal detection (#476) - -# 0.11.1 - -* bug: fix tty detection with custom out (#471) - -# 0.11.0 - -* performance: Use bufferpool to allocate (#370) -* terminal: terminal detection for app-engine (#343) -* feature: exit handler (#375) - -# 0.10.0 - -* feature: Add a test hook (#180) -* feature: `ParseLevel` is now case-insensitive (#326) -* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) -* performance: avoid re-allocations on `WithFields` (#335) - -# 0.9.0 - -* logrus/text_formatter: don't emit empty msg -* logrus/hooks/airbrake: move out of main repository -* logrus/hooks/sentry: move out of main repository -* logrus/hooks/papertrail: move out of main repository -* logrus/hooks/bugsnag: move out of main repository -* logrus/core: run tests with `-race` -* logrus/core: detect TTY based on `stderr` -* logrus/core: support `WithError` on logger -* logrus/core: Solaris support - -# 0.8.7 - -* logrus/core: fix possible race (#216) -* logrus/doc: small typo fixes and doc improvements - - -# 0.8.6 - -* hooks/raven: allow passing an initialized client - -# 0.8.5 - -* logrus/core: revert #208 - -# 0.8.4 - -* formatter/text: fix data race (#218) - -# 0.8.3 - -* logrus/core: fix entry log level (#208) -* logrus/core: improve performance of text formatter by 40% -* logrus/core: expose `LevelHooks` type -* logrus/core: add support for DragonflyBSD and NetBSD -* formatter/text: print structs more verbosely - -# 0.8.2 - -* logrus: fix more Fatal family functions - -# 0.8.1 - -* logrus: fix not exiting on `Fatalf` and `Fatalln` - -# 0.8.0 - -* logrus: defaults to stderr instead of stdout -* hooks/sentry: add special field for `*http.Request` -* formatter/text: ignore Windows for colors - -# 0.7.3 - -* formatter/\*: allow configuration of timestamp layout - -# 0.7.2 - -* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE deleted file mode 100644 index f090cb42f3..0000000000 --- a/vendor/github.com/Sirupsen/logrus/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Simon Eskildsen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md deleted file mode 100644 index c322876110..0000000000 --- a/vendor/github.com/Sirupsen/logrus/README.md +++ /dev/null @@ -1,479 +0,0 @@ -# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus) - -**Seeing weird case-sensitive problems?** See [this -issue](https://github.com/sirupsen/logrus/issues/451#issuecomment-264332021). -This change has been reverted. I apologize for causing this. I greatly -underestimated the impact this would have. Logrus strives for stability and -backwards compatibility and failed to provide that. - -Logrus is a structured logger for Go (golang), completely API compatible with -the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not -yet stable (pre 1.0). Logrus itself is completely stable and has been used in -many large deployments. The core API is unlikely to change much but please -version control your Logrus to make sure you aren't fetching latest `master` on -every build.** - -Nicely color-coded in development (when a TTY is attached, otherwise just -plain text): - -![Colored](http://i.imgur.com/PY7qMwd.png) - -With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash -or Splunk: - -```json -{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the -ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} - -{"level":"warning","msg":"The group's number increased tremendously!", -"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"A giant walrus appears!", -"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} - -{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", -"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} - -{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, -"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} -``` - -With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not -attached, the output is compatible with the -[logfmt](http://godoc.org/github.com/kr/logfmt) format: - -```text -time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 -time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 -time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true -time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 -time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 -time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true -exit status 1 -``` - -#### Example - -The simplest way to use Logrus is simply the package-level exported logger: - -```go -package main - -import ( - log "github.com/Sirupsen/logrus" -) - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - }).Info("A walrus appears") -} -``` - -Note that it's completely api-compatible with the stdlib logger, so you can -replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` -and you'll now have the flexibility of Logrus. You can customize it all you -want: - -```go -package main - -import ( - "os" - log "github.com/Sirupsen/logrus" -) - -func init() { - // Log as JSON instead of the default ASCII formatter. - log.SetFormatter(&log.JSONFormatter{}) - - // Output to stdout instead of the default stderr - // Can be any io.Writer, see below for File example - log.SetOutput(os.Stdout) - - // Only log the warning severity or above. - log.SetLevel(log.WarnLevel) -} - -func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") - - log.WithFields(log.Fields{ - "omg": true, - "number": 122, - }).Warn("The group's number increased tremendously!") - - log.WithFields(log.Fields{ - "omg": true, - "number": 100, - }).Fatal("The ice breaks!") - - // A common pattern is to re-use fields between logging statements by re-using - // the logrus.Entry returned from WithFields() - contextLogger := log.WithFields(log.Fields{ - "common": "this is a common field", - "other": "I also should be logged always", - }) - - contextLogger.Info("I'll be logged with common and other field") - contextLogger.Info("Me too") -} -``` - -For more advanced usage such as logging to multiple locations from the same -application, you can also create an instance of the `logrus` Logger: - -```go -package main - -import ( - "os" - "github.com/Sirupsen/logrus" -) - -// Create a new instance of the logger. You can have any number of instances. -var log = logrus.New() - -func main() { - // The API for setting attributes is a little different than the package level - // exported logger. See Godoc. - log.Out = os.Stdout - - // You could set this to any `io.Writer` such as a file - // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666) - // if err == nil { - // log.Out = file - // } else { - // log.Info("Failed to log to file, using default stderr") - // } - - log.WithFields(logrus.Fields{ - "animal": "walrus", - "size": 10, - }).Info("A group of walrus emerges from the ocean") -} -``` - -#### Fields - -Logrus encourages careful, structured logging though logging fields instead of -long, unparseable error messages. For example, instead of: `log.Fatalf("Failed -to send event %s to topic %s with key %d")`, you should log the much more -discoverable: - -```go -log.WithFields(log.Fields{ - "event": event, - "topic": topic, - "key": key, -}).Fatal("Failed to send event") -``` - -We've found this API forces you to think about logging in a way that produces -much more useful logging messages. We've been in countless situations where just -a single added field to a log statement that was already there would've saved us -hours. The `WithFields` call is optional. - -In general, with Logrus using any of the `printf`-family functions should be -seen as a hint you should add a field, however, you can still use the -`printf`-family functions with Logrus. - -#### Default Fields - -Often it's helpful to have fields _always_ attached to log statements in an -application or parts of one. For example, you may want to always log the -`request_id` and `user_ip` in the context of a request. Instead of writing -`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on -every line, you can create a `logrus.Entry` to pass around instead: - -```go -requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) -requestLogger.Info("something happened on that request") # will log request_id and user_ip -requestLogger.Warn("something not great happened") -``` - -#### Hooks - -You can add hooks for logging levels. For example to send errors to an exception -tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to -multiple places simultaneously, e.g. syslog. - -Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in -`init`: - -```go -import ( - log "github.com/Sirupsen/logrus" - "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake" - logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" - "log/syslog" -) - -func init() { - - // Use the Airbrake hook to report errors that have Error severity or above to - // an exception tracker. You can create custom hooks, see the Hooks section. - log.AddHook(airbrake.NewHook(123, "xyz", "production")) - - hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") - if err != nil { - log.Error("Unable to connect to local syslog daemon") - } else { - log.AddHook(hook) - } -} -``` -Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). - -| Hook | Description | -| ----- | ----------- | -| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | -| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. | -| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) | -| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) | -| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | -| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | -| [Discordrus](https://github.com/kz/discordrus) | Hook for logging to [Discord](https://discordapp.com/) | -| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch| -| [Firehose](https://github.com/beaubrewer/firehose) | Hook for logging to [Amazon Firehose](https://aws.amazon.com/kinesis/firehose/) -| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | -| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) | -| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) | -| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | -| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | -| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | -| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) | -| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | -| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka | -| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | -| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) | -| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) | -| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) | -| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | -| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) | -| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | -| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | -| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) | -| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | -| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. | -| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) | -| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) | -| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | -| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) | -| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | -| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)| -| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. | -| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | -| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) | -| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)| -| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | -| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) | -| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) | -| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash | - -#### Level logging - -Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. - -```go -log.Debug("Useful debugging information.") -log.Info("Something noteworthy happened!") -log.Warn("You should probably take a look at this.") -log.Error("Something failed but I'm not quitting.") -// Calls os.Exit(1) after logging -log.Fatal("Bye.") -// Calls panic() after logging -log.Panic("I'm bailing.") -``` - -You can set the logging level on a `Logger`, then it will only log entries with -that severity or anything above it: - -```go -// Will log anything that is info or above (warn, error, fatal, panic). Default. -log.SetLevel(log.InfoLevel) -``` - -It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose -environment if your application has that. - -#### Entries - -Besides the fields added with `WithField` or `WithFields` some fields are -automatically added to all logging events: - -1. `time`. The timestamp when the entry was created. -2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after - the `AddFields` call. E.g. `Failed to send event.` -3. `level`. The logging level. E.g. `info`. - -#### Environments - -Logrus has no notion of environment. - -If you wish for hooks and formatters to only be used in specific environments, -you should handle that yourself. For example, if your application has a global -variable `Environment`, which is a string representation of the environment you -could do: - -```go -import ( - log "github.com/Sirupsen/logrus" -) - -init() { - // do something here to set environment depending on an environment variable - // or command-line flag - if Environment == "production" { - log.SetFormatter(&log.JSONFormatter{}) - } else { - // The TextFormatter is default, you don't actually have to do this. - log.SetFormatter(&log.TextFormatter{}) - } -} -``` - -This configuration is how `logrus` was intended to be used, but JSON in -production is mostly only useful if you do log aggregation with tools like -Splunk or Logstash. - -#### Formatters - -The built-in logging formatters are: - -* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise - without colors. - * *Note:* to force colored output when there is no TTY, set the `ForceColors` - field to `true`. To force no colored output even if there is a TTY set the - `DisableColors` field to `true`. For Windows, see - [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). -* `logrus.JSONFormatter`. Logs fields as JSON. - * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). - -Third party logging formatters: - -* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. -* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. -* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. - -You can define your formatter by implementing the `Formatter` interface, -requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a -`Fields` type (`map[string]interface{}`) with all your fields as well as the -default ones (see Entries section above): - -```go -type MyJSONFormatter struct { -} - -log.SetFormatter(new(MyJSONFormatter)) - -func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { - // Note this doesn't include Time, Level and Message which are available on - // the Entry. Consult `godoc` on information about those fields or read the - // source of the official loggers. - serialized, err := json.Marshal(entry.Data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} -``` - -#### Logger as an `io.Writer` - -Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. - -```go -w := logger.Writer() -defer w.Close() - -srv := http.Server{ - // create a stdlib log.Logger that writes to - // logrus.Logger. - ErrorLog: log.New(w, "", 0), -} -``` - -Each line written to that writer will be printed the usual way, using formatters -and hooks. The level for those entries is `info`. - -This means that we can override the standard library logger easily: - -```go -logger := logrus.New() -logger.Formatter = &logrus.JSONFormatter{} - -// Use logrus for standard log output -// Note that `log` here references stdlib's log -// Not logrus imported under the name `log`. -log.SetOutput(logger.Writer()) -``` - -#### Rotation - -Log rotation is not provided with Logrus. Log rotation should be done by an -external program (like `logrotate(8)`) that can compress and delete old log -entries. It should not be a feature of the application-level logger. - -#### Tools - -| Tool | Description | -| ---- | ----------- | -|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| -|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | - -#### Testing - -Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: - -* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook -* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): - -```go -logger, hook := NewNullLogger() -logger.Error("Hello error") - -assert.Equal(1, len(hook.Entries)) -assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level) -assert.Equal("Hello error", hook.LastEntry().Message) - -hook.Reset() -assert.Nil(hook.LastEntry()) -``` - -#### Fatal handlers - -Logrus can register one or more functions that will be called when any `fatal` -level message is logged. The registered handlers will be executed before -logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need -to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. - -``` -... -handler := func() { - // gracefully shutdown something... -} -logrus.RegisterExitHandler(handler) -... -``` - -#### Thread safety - -By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs. -If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. - -Situation when locking is not needed includes: - -* You have no hooks registered, or hooks calling is already thread-safe. - -* Writing to logger.Out is already thread-safe, for example: - - 1) logger.Out is protected by locks. - - 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) - - (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go deleted file mode 100644 index 8af90637a9..0000000000 --- a/vendor/github.com/Sirupsen/logrus/alt_exit.go +++ /dev/null @@ -1,64 +0,0 @@ -package logrus - -// The following code was sourced and modified from the -// https://github.com/tebeka/atexit package governed by the following license: -// -// Copyright (c) 2012 Miki Tebeka . -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -import ( - "fmt" - "os" -) - -var handlers = []func(){} - -func runHandler(handler func()) { - defer func() { - if err := recover(); err != nil { - fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) - } - }() - - handler() -} - -func runHandlers() { - for _, handler := range handlers { - runHandler(handler) - } -} - -// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) -func Exit(code int) { - runHandlers() - os.Exit(code) -} - -// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke -// all handlers. The handlers will also be invoked when any Fatal log entry is -// made. -// -// This method is useful when a caller wishes to use logrus to log a fatal -// message but also needs to gracefully shutdown. An example usecase could be -// closing database connections, or sending a alert that the application is -// closing. -func RegisterExitHandler(handler func()) { - handlers = append(handlers, handler) -} diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go deleted file mode 100644 index dddd5f877b..0000000000 --- a/vendor/github.com/Sirupsen/logrus/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -/* -Package logrus is a structured logger for Go, completely API compatible with the standard library logger. - - -The simplest way to use Logrus is simply the package-level exported logger: - - package main - - import ( - log "github.com/Sirupsen/logrus" - ) - - func main() { - log.WithFields(log.Fields{ - "animal": "walrus", - "number": 1, - "size": 10, - }).Info("A walrus appears") - } - -Output: - time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 - -For a full guide visit https://github.com/Sirupsen/logrus -*/ -package logrus diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go deleted file mode 100644 index 4edbe7a2de..0000000000 --- a/vendor/github.com/Sirupsen/logrus/entry.go +++ /dev/null @@ -1,275 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "os" - "sync" - "time" -) - -var bufferPool *sync.Pool - -func init() { - bufferPool = &sync.Pool{ - New: func() interface{} { - return new(bytes.Buffer) - }, - } -} - -// Defines the key when adding errors using WithError. -var ErrorKey = "error" - -// An entry is the final or intermediate Logrus logging entry. It contains all -// the fields passed with WithField{,s}. It's finally logged when Debug, Info, -// Warn, Error, Fatal or Panic is called on it. These objects can be reused and -// passed around as much as you wish to avoid field duplication. -type Entry struct { - Logger *Logger - - // Contains all the fields set by the user. - Data Fields - - // Time at which the log entry was created - Time time.Time - - // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic - Level Level - - // Message passed to Debug, Info, Warn, Error, Fatal or Panic - Message string - - // When formatter is called in entry.log(), an Buffer may be set to entry - Buffer *bytes.Buffer -} - -func NewEntry(logger *Logger) *Entry { - return &Entry{ - Logger: logger, - // Default is three fields, give a little extra room - Data: make(Fields, 5), - } -} - -// Returns the string representation from the reader and ultimately the -// formatter. -func (entry *Entry) String() (string, error) { - serialized, err := entry.Logger.Formatter.Format(entry) - if err != nil { - return "", err - } - str := string(serialized) - return str, nil -} - -// Add an error as single field (using the key defined in ErrorKey) to the Entry. -func (entry *Entry) WithError(err error) *Entry { - return entry.WithField(ErrorKey, err) -} - -// Add a single field to the Entry. -func (entry *Entry) WithField(key string, value interface{}) *Entry { - return entry.WithFields(Fields{key: value}) -} - -// Add a map of fields to the Entry. -func (entry *Entry) WithFields(fields Fields) *Entry { - data := make(Fields, len(entry.Data)+len(fields)) - for k, v := range entry.Data { - data[k] = v - } - for k, v := range fields { - data[k] = v - } - return &Entry{Logger: entry.Logger, Data: data} -} - -// This function is not declared with a pointer value because otherwise -// race conditions will occur when using multiple goroutines -func (entry Entry) log(level Level, msg string) { - var buffer *bytes.Buffer - entry.Time = time.Now() - entry.Level = level - entry.Message = msg - - if err := entry.Logger.Hooks.Fire(level, &entry); err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) - entry.Logger.mu.Unlock() - } - buffer = bufferPool.Get().(*bytes.Buffer) - buffer.Reset() - defer bufferPool.Put(buffer) - entry.Buffer = buffer - serialized, err := entry.Logger.Formatter.Format(&entry) - entry.Buffer = nil - if err != nil { - entry.Logger.mu.Lock() - fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) - entry.Logger.mu.Unlock() - } else { - entry.Logger.mu.Lock() - _, err = entry.Logger.Out.Write(serialized) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) - } - entry.Logger.mu.Unlock() - } - - // To avoid Entry#log() returning a value that only would make sense for - // panic() to use in Entry#Panic(), we avoid the allocation by checking - // directly here. - if level <= PanicLevel { - panic(&entry) - } -} - -func (entry *Entry) Debug(args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.log(DebugLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Print(args ...interface{}) { - entry.Info(args...) -} - -func (entry *Entry) Info(args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.log(InfoLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warn(args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.log(WarnLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Warning(args ...interface{}) { - entry.Warn(args...) -} - -func (entry *Entry) Error(args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.log(ErrorLevel, fmt.Sprint(args...)) - } -} - -func (entry *Entry) Fatal(args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.log(FatalLevel, fmt.Sprint(args...)) - } - Exit(1) -} - -func (entry *Entry) Panic(args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.log(PanicLevel, fmt.Sprint(args...)) - } - panic(fmt.Sprint(args...)) -} - -// Entry Printf family functions - -func (entry *Entry) Debugf(format string, args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.Debug(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Infof(format string, args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.Info(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Printf(format string, args ...interface{}) { - entry.Infof(format, args...) -} - -func (entry *Entry) Warnf(format string, args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.Warn(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Warningf(format string, args ...interface{}) { - entry.Warnf(format, args...) -} - -func (entry *Entry) Errorf(format string, args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.Error(fmt.Sprintf(format, args...)) - } -} - -func (entry *Entry) Fatalf(format string, args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.Fatal(fmt.Sprintf(format, args...)) - } - Exit(1) -} - -func (entry *Entry) Panicf(format string, args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.Panic(fmt.Sprintf(format, args...)) - } -} - -// Entry Println family functions - -func (entry *Entry) Debugln(args ...interface{}) { - if entry.Logger.Level >= DebugLevel { - entry.Debug(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Infoln(args ...interface{}) { - if entry.Logger.Level >= InfoLevel { - entry.Info(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Println(args ...interface{}) { - entry.Infoln(args...) -} - -func (entry *Entry) Warnln(args ...interface{}) { - if entry.Logger.Level >= WarnLevel { - entry.Warn(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Warningln(args ...interface{}) { - entry.Warnln(args...) -} - -func (entry *Entry) Errorln(args ...interface{}) { - if entry.Logger.Level >= ErrorLevel { - entry.Error(entry.sprintlnn(args...)) - } -} - -func (entry *Entry) Fatalln(args ...interface{}) { - if entry.Logger.Level >= FatalLevel { - entry.Fatal(entry.sprintlnn(args...)) - } - Exit(1) -} - -func (entry *Entry) Panicln(args ...interface{}) { - if entry.Logger.Level >= PanicLevel { - entry.Panic(entry.sprintlnn(args...)) - } -} - -// Sprintlnn => Sprint no newline. This is to get the behavior of how -// fmt.Sprintln where spaces are always added between operands, regardless of -// their type. Instead of vendoring the Sprintln implementation to spare a -// string allocation, we do the simplest thing. -func (entry *Entry) sprintlnn(args ...interface{}) string { - msg := fmt.Sprintln(args...) - return msg[:len(msg)-1] -} diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go deleted file mode 100644 index 9a0120ac1d..0000000000 --- a/vendor/github.com/Sirupsen/logrus/exported.go +++ /dev/null @@ -1,193 +0,0 @@ -package logrus - -import ( - "io" -) - -var ( - // std is the name of the standard logger in stdlib `log` - std = New() -) - -func StandardLogger() *Logger { - return std -} - -// SetOutput sets the standard logger output. -func SetOutput(out io.Writer) { - std.mu.Lock() - defer std.mu.Unlock() - std.Out = out -} - -// SetFormatter sets the standard logger formatter. -func SetFormatter(formatter Formatter) { - std.mu.Lock() - defer std.mu.Unlock() - std.Formatter = formatter -} - -// SetLevel sets the standard logger level. -func SetLevel(level Level) { - std.mu.Lock() - defer std.mu.Unlock() - std.Level = level -} - -// GetLevel returns the standard logger level. -func GetLevel() Level { - std.mu.Lock() - defer std.mu.Unlock() - return std.Level -} - -// AddHook adds a hook to the standard logger hooks. -func AddHook(hook Hook) { - std.mu.Lock() - defer std.mu.Unlock() - std.Hooks.Add(hook) -} - -// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. -func WithError(err error) *Entry { - return std.WithField(ErrorKey, err) -} - -// WithField creates an entry from the standard logger and adds a field to -// it. If you want multiple fields, use `WithFields`. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithField(key string, value interface{}) *Entry { - return std.WithField(key, value) -} - -// WithFields creates an entry from the standard logger and adds multiple -// fields to it. This is simply a helper for `WithField`, invoking it -// once for each field. -// -// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal -// or Panic on the Entry it returns. -func WithFields(fields Fields) *Entry { - return std.WithFields(fields) -} - -// Debug logs a message at level Debug on the standard logger. -func Debug(args ...interface{}) { - std.Debug(args...) -} - -// Print logs a message at level Info on the standard logger. -func Print(args ...interface{}) { - std.Print(args...) -} - -// Info logs a message at level Info on the standard logger. -func Info(args ...interface{}) { - std.Info(args...) -} - -// Warn logs a message at level Warn on the standard logger. -func Warn(args ...interface{}) { - std.Warn(args...) -} - -// Warning logs a message at level Warn on the standard logger. -func Warning(args ...interface{}) { - std.Warning(args...) -} - -// Error logs a message at level Error on the standard logger. -func Error(args ...interface{}) { - std.Error(args...) -} - -// Panic logs a message at level Panic on the standard logger. -func Panic(args ...interface{}) { - std.Panic(args...) -} - -// Fatal logs a message at level Fatal on the standard logger. -func Fatal(args ...interface{}) { - std.Fatal(args...) -} - -// Debugf logs a message at level Debug on the standard logger. -func Debugf(format string, args ...interface{}) { - std.Debugf(format, args...) -} - -// Printf logs a message at level Info on the standard logger. -func Printf(format string, args ...interface{}) { - std.Printf(format, args...) -} - -// Infof logs a message at level Info on the standard logger. -func Infof(format string, args ...interface{}) { - std.Infof(format, args...) -} - -// Warnf logs a message at level Warn on the standard logger. -func Warnf(format string, args ...interface{}) { - std.Warnf(format, args...) -} - -// Warningf logs a message at level Warn on the standard logger. -func Warningf(format string, args ...interface{}) { - std.Warningf(format, args...) -} - -// Errorf logs a message at level Error on the standard logger. -func Errorf(format string, args ...interface{}) { - std.Errorf(format, args...) -} - -// Panicf logs a message at level Panic on the standard logger. -func Panicf(format string, args ...interface{}) { - std.Panicf(format, args...) -} - -// Fatalf logs a message at level Fatal on the standard logger. -func Fatalf(format string, args ...interface{}) { - std.Fatalf(format, args...) -} - -// Debugln logs a message at level Debug on the standard logger. -func Debugln(args ...interface{}) { - std.Debugln(args...) -} - -// Println logs a message at level Info on the standard logger. -func Println(args ...interface{}) { - std.Println(args...) -} - -// Infoln logs a message at level Info on the standard logger. -func Infoln(args ...interface{}) { - std.Infoln(args...) -} - -// Warnln logs a message at level Warn on the standard logger. -func Warnln(args ...interface{}) { - std.Warnln(args...) -} - -// Warningln logs a message at level Warn on the standard logger. -func Warningln(args ...interface{}) { - std.Warningln(args...) -} - -// Errorln logs a message at level Error on the standard logger. -func Errorln(args ...interface{}) { - std.Errorln(args...) -} - -// Panicln logs a message at level Panic on the standard logger. -func Panicln(args ...interface{}) { - std.Panicln(args...) -} - -// Fatalln logs a message at level Fatal on the standard logger. -func Fatalln(args ...interface{}) { - std.Fatalln(args...) -} diff --git a/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go deleted file mode 100644 index b5fbe934d1..0000000000 --- a/vendor/github.com/Sirupsen/logrus/formatter.go +++ /dev/null @@ -1,45 +0,0 @@ -package logrus - -import "time" - -const DefaultTimestampFormat = time.RFC3339 - -// The Formatter interface is used to implement a custom Formatter. It takes an -// `Entry`. It exposes all the fields, including the default ones: -// -// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. -// * `entry.Data["time"]`. The timestamp. -// * `entry.Data["level"]. The level the entry was logged at. -// -// Any additional fields added with `WithField` or `WithFields` are also in -// `entry.Data`. Format is expected to return an array of bytes which are then -// logged to `logger.Out`. -type Formatter interface { - Format(*Entry) ([]byte, error) -} - -// This is to not silently overwrite `time`, `msg` and `level` fields when -// dumping it. If this code wasn't there doing: -// -// logrus.WithField("level", 1).Info("hello") -// -// Would just silently drop the user provided level. Instead with this code -// it'll logged as: -// -// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} -// -// It's not exported because it's still using Data in an opinionated way. It's to -// avoid code duplication between the two default formatters. -func prefixFieldClashes(data Fields) { - if t, ok := data["time"]; ok { - data["fields.time"] = t - } - - if m, ok := data["msg"]; ok { - data["fields.msg"] = m - } - - if l, ok := data["level"]; ok { - data["fields.level"] = l - } -} diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go deleted file mode 100644 index 3f151cdc39..0000000000 --- a/vendor/github.com/Sirupsen/logrus/hooks.go +++ /dev/null @@ -1,34 +0,0 @@ -package logrus - -// A hook to be fired when logging on the logging levels returned from -// `Levels()` on your implementation of the interface. Note that this is not -// fired in a goroutine or a channel with workers, you should handle such -// functionality yourself if your call is non-blocking and you don't wish for -// the logging calls for levels returned from `Levels()` to block. -type Hook interface { - Levels() []Level - Fire(*Entry) error -} - -// Internal type for storing the hooks on a logger instance. -type LevelHooks map[Level][]Hook - -// Add a hook to an instance of logger. This is called with -// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. -func (hooks LevelHooks) Add(hook Hook) { - for _, level := range hook.Levels() { - hooks[level] = append(hooks[level], hook) - } -} - -// Fire all the hooks for the passed level. Used by `entry.log` to fire -// appropriate hooks for a log entry. -func (hooks LevelHooks) Fire(level Level, entry *Entry) error { - for _, hook := range hooks[level] { - if err := hook.Fire(entry); err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go deleted file mode 100644 index 266554e9ff..0000000000 --- a/vendor/github.com/Sirupsen/logrus/json_formatter.go +++ /dev/null @@ -1,74 +0,0 @@ -package logrus - -import ( - "encoding/json" - "fmt" -) - -type fieldKey string -type FieldMap map[fieldKey]string - -const ( - FieldKeyMsg = "msg" - FieldKeyLevel = "level" - FieldKeyTime = "time" -) - -func (f FieldMap) resolve(key fieldKey) string { - if k, ok := f[key]; ok { - return k - } - - return string(key) -} - -type JSONFormatter struct { - // TimestampFormat sets the format used for marshaling timestamps. - TimestampFormat string - - // DisableTimestamp allows disabling automatic timestamps in output - DisableTimestamp bool - - // FieldMap allows users to customize the names of keys for various fields. - // As an example: - // formatter := &JSONFormatter{ - // FieldMap: FieldMap{ - // FieldKeyTime: "@timestamp", - // FieldKeyLevel: "@level", - // FieldKeyLevel: "@message", - // }, - // } - FieldMap FieldMap -} - -func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { - data := make(Fields, len(entry.Data)+3) - for k, v := range entry.Data { - switch v := v.(type) { - case error: - // Otherwise errors are ignored by `encoding/json` - // https://github.com/Sirupsen/logrus/issues/137 - data[k] = v.Error() - default: - data[k] = v - } - } - prefixFieldClashes(data) - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat - } - - if !f.DisableTimestamp { - data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) - } - data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message - data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() - - serialized, err := json.Marshal(data) - if err != nil { - return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) - } - return append(serialized, '\n'), nil -} diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go deleted file mode 100644 index b769f3d352..0000000000 --- a/vendor/github.com/Sirupsen/logrus/logger.go +++ /dev/null @@ -1,308 +0,0 @@ -package logrus - -import ( - "io" - "os" - "sync" -) - -type Logger struct { - // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a - // file, or leave it default which is `os.Stderr`. You can also set this to - // something more adventorous, such as logging to Kafka. - Out io.Writer - // Hooks for the logger instance. These allow firing events based on logging - // levels and log entries. For example, to send errors to an error tracking - // service, log to StatsD or dump the core on fatal errors. - Hooks LevelHooks - // All log entries pass through the formatter before logged to Out. The - // included formatters are `TextFormatter` and `JSONFormatter` for which - // TextFormatter is the default. In development (when a TTY is attached) it - // logs with colors, but to a file it wouldn't. You can easily implement your - // own that implements the `Formatter` interface, see the `README` or included - // formatters for examples. - Formatter Formatter - // The logging level the logger should log at. This is typically (and defaults - // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be - // logged. `logrus.Debug` is useful in - Level Level - // Used to sync writing to the log. Locking is enabled by Default - mu MutexWrap - // Reusable empty entry - entryPool sync.Pool -} - -type MutexWrap struct { - lock sync.Mutex - disabled bool -} - -func (mw *MutexWrap) Lock() { - if !mw.disabled { - mw.lock.Lock() - } -} - -func (mw *MutexWrap) Unlock() { - if !mw.disabled { - mw.lock.Unlock() - } -} - -func (mw *MutexWrap) Disable() { - mw.disabled = true -} - -// Creates a new logger. Configuration should be set by changing `Formatter`, -// `Out` and `Hooks` directly on the default logger instance. You can also just -// instantiate your own: -// -// var log = &Logger{ -// Out: os.Stderr, -// Formatter: new(JSONFormatter), -// Hooks: make(LevelHooks), -// Level: logrus.DebugLevel, -// } -// -// It's recommended to make this a global instance called `log`. -func New() *Logger { - return &Logger{ - Out: os.Stderr, - Formatter: new(TextFormatter), - Hooks: make(LevelHooks), - Level: InfoLevel, - } -} - -func (logger *Logger) newEntry() *Entry { - entry, ok := logger.entryPool.Get().(*Entry) - if ok { - return entry - } - return NewEntry(logger) -} - -func (logger *Logger) releaseEntry(entry *Entry) { - logger.entryPool.Put(entry) -} - -// Adds a field to the log entry, note that it doesn't log until you call -// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. -// If you want multiple fields, use `WithFields`. -func (logger *Logger) WithField(key string, value interface{}) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithField(key, value) -} - -// Adds a struct of fields to the log entry. All it does is call `WithField` for -// each `Field`. -func (logger *Logger) WithFields(fields Fields) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithFields(fields) -} - -// Add an error as single field to the log entry. All it does is call -// `WithError` for the given `error`. -func (logger *Logger) WithError(err error) *Entry { - entry := logger.newEntry() - defer logger.releaseEntry(entry) - return entry.WithError(err) -} - -func (logger *Logger) Debugf(format string, args ...interface{}) { - if logger.Level >= DebugLevel { - entry := logger.newEntry() - entry.Debugf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Infof(format string, args ...interface{}) { - if logger.Level >= InfoLevel { - entry := logger.newEntry() - entry.Infof(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Printf(format string, args ...interface{}) { - entry := logger.newEntry() - entry.Printf(format, args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warnf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warningf(format string, args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warnf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Errorf(format string, args ...interface{}) { - if logger.Level >= ErrorLevel { - entry := logger.newEntry() - entry.Errorf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatalf(format string, args ...interface{}) { - if logger.Level >= FatalLevel { - entry := logger.newEntry() - entry.Fatalf(format, args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panicf(format string, args ...interface{}) { - if logger.Level >= PanicLevel { - entry := logger.newEntry() - entry.Panicf(format, args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Debug(args ...interface{}) { - if logger.Level >= DebugLevel { - entry := logger.newEntry() - entry.Debug(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Info(args ...interface{}) { - if logger.Level >= InfoLevel { - entry := logger.newEntry() - entry.Info(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Print(args ...interface{}) { - entry := logger.newEntry() - entry.Info(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warn(args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warn(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warning(args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warn(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Error(args ...interface{}) { - if logger.Level >= ErrorLevel { - entry := logger.newEntry() - entry.Error(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatal(args ...interface{}) { - if logger.Level >= FatalLevel { - entry := logger.newEntry() - entry.Fatal(args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panic(args ...interface{}) { - if logger.Level >= PanicLevel { - entry := logger.newEntry() - entry.Panic(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Debugln(args ...interface{}) { - if logger.Level >= DebugLevel { - entry := logger.newEntry() - entry.Debugln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Infoln(args ...interface{}) { - if logger.Level >= InfoLevel { - entry := logger.newEntry() - entry.Infoln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Println(args ...interface{}) { - entry := logger.newEntry() - entry.Println(args...) - logger.releaseEntry(entry) -} - -func (logger *Logger) Warnln(args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warnln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Warningln(args ...interface{}) { - if logger.Level >= WarnLevel { - entry := logger.newEntry() - entry.Warnln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Errorln(args ...interface{}) { - if logger.Level >= ErrorLevel { - entry := logger.newEntry() - entry.Errorln(args...) - logger.releaseEntry(entry) - } -} - -func (logger *Logger) Fatalln(args ...interface{}) { - if logger.Level >= FatalLevel { - entry := logger.newEntry() - entry.Fatalln(args...) - logger.releaseEntry(entry) - } - Exit(1) -} - -func (logger *Logger) Panicln(args ...interface{}) { - if logger.Level >= PanicLevel { - entry := logger.newEntry() - entry.Panicln(args...) - logger.releaseEntry(entry) - } -} - -//When file is opened with appending mode, it's safe to -//write concurrently to a file (within 4k message on Linux). -//In these cases user can choose to disable the lock. -func (logger *Logger) SetNoLock() { - logger.mu.Disable() -} diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go deleted file mode 100644 index e596691116..0000000000 --- a/vendor/github.com/Sirupsen/logrus/logrus.go +++ /dev/null @@ -1,143 +0,0 @@ -package logrus - -import ( - "fmt" - "log" - "strings" -) - -// Fields type, used to pass to `WithFields`. -type Fields map[string]interface{} - -// Level type -type Level uint8 - -// Convert the Level to a string. E.g. PanicLevel becomes "panic". -func (level Level) String() string { - switch level { - case DebugLevel: - return "debug" - case InfoLevel: - return "info" - case WarnLevel: - return "warning" - case ErrorLevel: - return "error" - case FatalLevel: - return "fatal" - case PanicLevel: - return "panic" - } - - return "unknown" -} - -// ParseLevel takes a string level and returns the Logrus log level constant. -func ParseLevel(lvl string) (Level, error) { - switch strings.ToLower(lvl) { - case "panic": - return PanicLevel, nil - case "fatal": - return FatalLevel, nil - case "error": - return ErrorLevel, nil - case "warn", "warning": - return WarnLevel, nil - case "info": - return InfoLevel, nil - case "debug": - return DebugLevel, nil - } - - var l Level - return l, fmt.Errorf("not a valid logrus Level: %q", lvl) -} - -// A constant exposing all logging levels -var AllLevels = []Level{ - PanicLevel, - FatalLevel, - ErrorLevel, - WarnLevel, - InfoLevel, - DebugLevel, -} - -// These are the different logging levels. You can set the logging level to log -// on your instance of logger, obtained with `logrus.New()`. -const ( - // PanicLevel level, highest level of severity. Logs and then calls panic with the - // message passed to Debug, Info, ... - PanicLevel Level = iota - // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the - // logging level is set to Panic. - FatalLevel - // ErrorLevel level. Logs. Used for errors that should definitely be noted. - // Commonly used for hooks to send errors to an error tracking service. - ErrorLevel - // WarnLevel level. Non-critical entries that deserve eyes. - WarnLevel - // InfoLevel level. General operational entries about what's going on inside the - // application. - InfoLevel - // DebugLevel level. Usually only enabled when debugging. Very verbose logging. - DebugLevel -) - -// Won't compile if StdLogger can't be realized by a log.Logger -var ( - _ StdLogger = &log.Logger{} - _ StdLogger = &Entry{} - _ StdLogger = &Logger{} -) - -// StdLogger is what your logrus-enabled library should take, that way -// it'll accept a stdlib logger and a logrus logger. There's no standard -// interface, this is the closest we get, unfortunately. -type StdLogger interface { - Print(...interface{}) - Printf(string, ...interface{}) - Println(...interface{}) - - Fatal(...interface{}) - Fatalf(string, ...interface{}) - Fatalln(...interface{}) - - Panic(...interface{}) - Panicf(string, ...interface{}) - Panicln(...interface{}) -} - -// The FieldLogger interface generalizes the Entry and Logger types -type FieldLogger interface { - WithField(key string, value interface{}) *Entry - WithFields(fields Fields) *Entry - WithError(err error) *Entry - - Debugf(format string, args ...interface{}) - Infof(format string, args ...interface{}) - Printf(format string, args ...interface{}) - Warnf(format string, args ...interface{}) - Warningf(format string, args ...interface{}) - Errorf(format string, args ...interface{}) - Fatalf(format string, args ...interface{}) - Panicf(format string, args ...interface{}) - - Debug(args ...interface{}) - Info(args ...interface{}) - Print(args ...interface{}) - Warn(args ...interface{}) - Warning(args ...interface{}) - Error(args ...interface{}) - Fatal(args ...interface{}) - Panic(args ...interface{}) - - Debugln(args ...interface{}) - Infoln(args ...interface{}) - Println(args ...interface{}) - Warnln(args ...interface{}) - Warningln(args ...interface{}) - Errorln(args ...interface{}) - Fatalln(args ...interface{}) - Panicln(args ...interface{}) -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_appengine.go b/vendor/github.com/Sirupsen/logrus/terminal_appengine.go deleted file mode 100644 index e011a86945..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_appengine.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build appengine - -package logrus - -import "io" - -// IsTerminal returns true if stderr's file descriptor is a terminal. -func IsTerminal(f io.Writer) bool { - return true -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go deleted file mode 100644 index 5f6be4d3c0..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly -// +build !appengine - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TIOCGETA - -type Termios syscall.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go deleted file mode 100644 index 308160ca80..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_linux.go +++ /dev/null @@ -1,14 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !appengine - -package logrus - -import "syscall" - -const ioctlReadTermios = syscall.TCGETS - -type Termios syscall.Termios diff --git a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go deleted file mode 100644 index 190297abf3..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go +++ /dev/null @@ -1,28 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux darwin freebsd openbsd netbsd dragonfly -// +build !appengine - -package logrus - -import ( - "io" - "os" - "syscall" - "unsafe" -) - -// IsTerminal returns true if stderr's file descriptor is a terminal. -func IsTerminal(f io.Writer) bool { - var termios Termios - switch v := f.(type) { - case *os.File: - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(v.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 - default: - return false - } -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go deleted file mode 100644 index 3c86b1abee..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build solaris,!appengine - -package logrus - -import ( - "io" - "os" - - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(f io.Writer) bool { - switch v := f.(type) { - case *os.File: - _, err := unix.IoctlGetTermios(int(v.Fd()), unix.TCGETA) - return err == nil - default: - return false - } -} diff --git a/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go deleted file mode 100644 index 05d2f91f16..0000000000 --- a/vendor/github.com/Sirupsen/logrus/terminal_windows.go +++ /dev/null @@ -1,33 +0,0 @@ -// Based on ssh/terminal: -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows,!appengine - -package logrus - -import ( - "io" - "os" - "syscall" - "unsafe" -) - -var kernel32 = syscall.NewLazyDLL("kernel32.dll") - -var ( - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") -) - -// IsTerminal returns true if stderr's file descriptor is a terminal. -func IsTerminal(f io.Writer) bool { - switch v := f.(type) { - case *os.File: - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(v.Fd()), uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 - default: - return false - } -} diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go deleted file mode 100644 index ba88854061..0000000000 --- a/vendor/github.com/Sirupsen/logrus/text_formatter.go +++ /dev/null @@ -1,189 +0,0 @@ -package logrus - -import ( - "bytes" - "fmt" - "sort" - "strings" - "sync" - "time" -) - -const ( - nocolor = 0 - red = 31 - green = 32 - yellow = 33 - blue = 34 - gray = 37 -) - -var ( - baseTimestamp time.Time -) - -func init() { - baseTimestamp = time.Now() -} - -type TextFormatter struct { - // Set to true to bypass checking for a TTY before outputting colors. - ForceColors bool - - // Force disabling colors. - DisableColors bool - - // Disable timestamp logging. useful when output is redirected to logging - // system that already adds timestamps. - DisableTimestamp bool - - // Enable logging the full timestamp when a TTY is attached instead of just - // the time passed since beginning of execution. - FullTimestamp bool - - // TimestampFormat to use for display when a full timestamp is printed - TimestampFormat string - - // The fields are sorted by default for a consistent output. For applications - // that log extremely frequently and don't use the JSON formatter this may not - // be desired. - DisableSorting bool - - // QuoteEmptyFields will wrap empty fields in quotes if true - QuoteEmptyFields bool - - // QuoteCharacter can be set to the override the default quoting character " - // with something else. For example: ', or `. - QuoteCharacter string - - // Whether the logger's out is to a terminal - isTerminal bool - - sync.Once -} - -func (f *TextFormatter) init(entry *Entry) { - if len(f.QuoteCharacter) == 0 { - f.QuoteCharacter = "\"" - } - if entry.Logger != nil { - f.isTerminal = IsTerminal(entry.Logger.Out) - } -} - -func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { - var b *bytes.Buffer - keys := make([]string, 0, len(entry.Data)) - for k := range entry.Data { - keys = append(keys, k) - } - - if !f.DisableSorting { - sort.Strings(keys) - } - if entry.Buffer != nil { - b = entry.Buffer - } else { - b = &bytes.Buffer{} - } - - prefixFieldClashes(entry.Data) - - f.Do(func() { f.init(entry) }) - - isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors - - timestampFormat := f.TimestampFormat - if timestampFormat == "" { - timestampFormat = DefaultTimestampFormat - } - if isColored { - f.printColored(b, entry, keys, timestampFormat) - } else { - if !f.DisableTimestamp { - f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat)) - } - f.appendKeyValue(b, "level", entry.Level.String()) - if entry.Message != "" { - f.appendKeyValue(b, "msg", entry.Message) - } - for _, key := range keys { - f.appendKeyValue(b, key, entry.Data[key]) - } - } - - b.WriteByte('\n') - return b.Bytes(), nil -} - -func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) { - var levelColor int - switch entry.Level { - case DebugLevel: - levelColor = gray - case WarnLevel: - levelColor = yellow - case ErrorLevel, FatalLevel, PanicLevel: - levelColor = red - default: - levelColor = blue - } - - levelText := strings.ToUpper(entry.Level.String())[0:4] - - if f.DisableTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message) - } else if !f.FullTimestamp { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message) - } else { - fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message) - } - for _, k := range keys { - v := entry.Data[k] - fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) - f.appendValue(b, v) - } -} - -func (f *TextFormatter) needsQuoting(text string) bool { - if f.QuoteEmptyFields && len(text) == 0 { - return true - } - for _, ch := range text { - if !((ch >= 'a' && ch <= 'z') || - (ch >= 'A' && ch <= 'Z') || - (ch >= '0' && ch <= '9') || - ch == '-' || ch == '.') { - return true - } - } - return false -} - -func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { - - b.WriteString(key) - b.WriteByte('=') - f.appendValue(b, value) - b.WriteByte(' ') -} - -func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { - switch value := value.(type) { - case string: - if !f.needsQuoting(value) { - b.WriteString(value) - } else { - fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, value, f.QuoteCharacter) - } - case error: - errmsg := value.Error() - if !f.needsQuoting(errmsg) { - b.WriteString(errmsg) - } else { - fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, errmsg, f.QuoteCharacter) - } - default: - fmt.Fprint(b, value) - } -} diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go deleted file mode 100644 index 7bdebedc60..0000000000 --- a/vendor/github.com/Sirupsen/logrus/writer.go +++ /dev/null @@ -1,62 +0,0 @@ -package logrus - -import ( - "bufio" - "io" - "runtime" -) - -func (logger *Logger) Writer() *io.PipeWriter { - return logger.WriterLevel(InfoLevel) -} - -func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { - return NewEntry(logger).WriterLevel(level) -} - -func (entry *Entry) Writer() *io.PipeWriter { - return entry.WriterLevel(InfoLevel) -} - -func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { - reader, writer := io.Pipe() - - var printFunc func(args ...interface{}) - - switch level { - case DebugLevel: - printFunc = entry.Debug - case InfoLevel: - printFunc = entry.Info - case WarnLevel: - printFunc = entry.Warn - case ErrorLevel: - printFunc = entry.Error - case FatalLevel: - printFunc = entry.Fatal - case PanicLevel: - printFunc = entry.Panic - default: - printFunc = entry.Print - } - - go entry.writerScanner(reader, printFunc) - runtime.SetFinalizer(writer, writerFinalizer) - - return writer -} - -func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - printFunc(scanner.Text()) - } - if err := scanner.Err(); err != nil { - entry.Errorf("Error while reading from Writer: %s", err) - } - reader.Close() -} - -func writerFinalizer(writer *io.PipeWriter) { - writer.Close() -} diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md deleted file mode 100644 index 5e57ef2ece..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md +++ /dev/null @@ -1,1536 +0,0 @@ -Release v1.10.18 (2017-07-27) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * The CreateDefaultVPC API enables you to create a new default VPC . You no longer need to contact AWS support, if your default VPC has been deleted. -* `service/kinesisanalytics`: Updates service API and documentation - * Added additional exception types and clarified documentation. - -Release v1.10.17 (2017-07-27) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service documentation and examples - * Corrected a typo. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Elastic GPUs allow you to easily attach low-cost graphics acceleration to current generation EC2 instances. With Amazon EC2 Elastic GPUs, you can configure the right amount of graphics acceleration to your particular workload without being constrained by fixed hardware configurations and limited GPU selection. -* `service/monitoring`: Updates service documentation - * This release adds high resolution features to CloudWatch, with support for Custom Metrics down to 1 second and Alarms down to 10 seconds. - -Release v1.10.16 (2017-07-26) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory adds support for additional batch operations. -* `service/cloudformation`: Updates service API and documentation - * AWS CloudFormation StackSets enables you to manage stacks across multiple accounts and regions. - -### SDK Enhancements -* `aws/signer/v4`: Optimize V4 signer's header duplicate space stripping. [#1417](https://github.com/aws/aws-sdk-go/pull/1417) - -Release v1.10.15 (2017-07-24) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and waiters - * Amazon AppStream 2.0 image builders and fleets can now access applications and network resources that rely on Microsoft Active Directory (AD) for authentication and permissions. This new feature allows you to join your streaming instances to your AD, so you can use your existing AD user management tools. -* `service/ec2`: Updates service API and documentation - * Spot Fleet tagging capability allows customers to automatically tag instances launched by Spot Fleet. You can use this feature to label or distinguish instances created by distinct Spot Fleets. Tagging your EC2 instances also enables you to see instance cost allocation by tag in your AWS bill. - -### SDK Bugs -* `aws/signer/v4`: Fix out of bounds panic in stripExcessSpaces [#1412](https://github.com/aws/aws-sdk-go/pull/1412) - * Fixes the out of bands panic in stripExcessSpaces caused by an incorrect calculation of the stripToIdx value. Simplified to code also. - * Fixes [#1411](https://github.com/aws/aws-sdk-go/issues/1411) -Release v1.10.14 (2017-07-20) -=== - -### Service Client Updates -* `service/elasticmapreduce`: Updates service API and documentation - * Amazon EMR now includes the ability to use a custom Amazon Linux AMI and adjustable root volume size when launching a cluster. - -Release v1.10.13 (2017-07-19) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Update budget Management API's to list/create/update RI_UTILIZATION type budget. Update budget Management API's to support DAILY timeUnit for RI_UTILIZATION type budget. - -### SDK Enhancements -* `service/s3`: Use interfaces assertions instead of ValuesAtPath for S3 field lookups. [#1401](https://github.com/aws/aws-sdk-go/pull/1401) - * Improves the performance across the board for all S3 API calls by removing the usage of `ValuesAtPath` being used for every S3 API call. - -### SDK Bugs -* `aws/request`: waiter test bug - * waiters_test.go file would sometimes fail due to travis hiccups. This occurs because a test would sometimes fail the cancel check and succeed the timeout. However, the timeout check should never occur in that test. This fix introduces a new field that dictates how waiters will sleep. -Release v1.10.12 (2017-07-17) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - * Lambda@Edge lets you run code closer to your end users without provisioning or managing servers. With Lambda@Edge, your code runs in AWS edge locations, allowing you to respond to your end users at the lowest latency. Your code is triggered by Amazon CloudFront events, such as requests to and from origin servers and viewers, and it is ready to execute at every AWS edge location whenever a request for content is received. You just upload your Node.js code to AWS Lambda and Lambda takes care of everything required to run and scale your code with high availability. You only pay for the compute time you consume - there is no charge when your code is not running. - -Release v1.10.11 (2017-07-14) -=== - -### Service Client Updates -* `service/discovery`: Updates service API and documentation - * Adding feature to the Export API for Discovery Service to allow filters for the export task to allow export based on per agent id. -* `service/ec2`: Updates service API - * New EC2 GPU Graphics instance -* `service/marketplacecommerceanalytics`: Updates service documentation - * Update to Documentation Model For New Report Cadence / Reformat of Docs - -Release v1.10.10 (2017-07-13) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for management of gateway responses. -* `service/ec2`: Updates service API and documentation - * X-ENI (or Cross-Account ENI) is a new feature that allows the attachment or association of Elastic Network Interfaces (ENI) between VPCs in different AWS accounts located in the same availability zone. With this new capability, service providers and partners can deliver managed solutions in a variety of new architectural patterns where the provider and consumer of the service are in different AWS accounts. -* `service/lex-models`: Updates service documentation - -Release v1.10.9 (2017-07-12) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Auto Scaling now supports a new type of scaling policy called target tracking scaling policies that you can use to set up dynamic scaling for your application. -* `service/swf`: Updates service API, documentation, paginators, and examples - * Added support for attaching control data to Lambda tasks. Control data lets you attach arbitrary strings to your decisions and history events. - -Release v1.10.8 (2017-07-06) -=== - -### Service Client Updates -* `service/ds`: Updates service API, documentation, and paginators - * You can now improve the resilience and performance of your Microsoft AD directory by deploying additional domain controllers. Added UpdateNumberofDomainControllers API that allows you to update the number of domain controllers you want for your directory, and DescribeDomainControllers API that allows you to describe the detailed information of each domain controller of your directory. Also added the 'DesiredNumberOfDomainControllers' field to the DescribeDirectories API output for Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * You can now encrypt your data at rest within an Amazon Kinesis Stream using server-side encryption. Server-side encryption via AWS KMS makes it easy for customers to meet strict data management requirements by encrypting their data at rest within the Amazon Kinesis Streams, a fully managed real-time data processing service. -* `service/kms`: Updates service API and documentation - * This release of AWS Key Management Service introduces the ability to determine whether a key is AWS managed or customer managed. -* `service/ssm`: Updates service API and documentation - * Amazon EC2 Systems Manager now expands Patching support to Amazon Linux, Red Hat and Ubuntu in addition to the already supported Windows Server. - -Release v1.10.7 (2017-07-05) -=== - -### Service Client Updates -* `service/monitoring`: Updates service API and documentation - * We are excited to announce the availability of APIs and CloudFormation support for CloudWatch Dashboards. You can use the new dashboard APIs or CloudFormation templates to dynamically build and maintain dashboards to monitor your infrastructure and applications. There are four new dashboard APIs - PutDashboard, GetDashboard, DeleteDashboards, and ListDashboards APIs. PutDashboard is used to create a new dashboard or modify an existing one whereas GetDashboard is the API to get the details of a specific dashboard. ListDashboards and DeleteDashboards are used to get the names or delete multiple dashboards respectively. Getting started with dashboard APIs is similar to any other AWS APIs. The APIs can be accessed through AWS SDK or through CLI tools. -* `service/route53`: Updates service API and documentation - * Bug fix for InvalidChangeBatch exception. - -### SDK Enhancements -* `service/s3/s3manager`: adding cleanup function to batch objects [#1375](https://github.com/aws/aws-sdk-go/issues/1375) - * This enhancement will add an After field that will be called after each iteration of the batch operation. - -Release v1.10.6 (2017-06-30) -=== - -### Service Client Updates -* `service/marketplacecommerceanalytics`: Updates service documentation - * Documentation updates for AWS Marketplace Commerce Analytics. -* `service/s3`: Updates service API and documentation - * API Update for S3: Adding Object Tagging Header to MultipartUpload Initialization - -Release v1.10.5 (2017-06-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * CloudWatch Events now allows different AWS accounts to share events with each other through a new resource called event bus. Event buses accept events from AWS services, other AWS accounts and PutEvents API calls. Currently all AWS accounts have one default event bus. To send events to another account, customers simply write rules to match the events of interest and attach an event bus in the receiving account as the target to the rule. The PutTargets API has been updated to allow adding cross account event buses as targets. In addition, we have released two new APIs - PutPermission and RemovePermission - that enables customers to add/remove permissions to their default event bus. -* `service/gamelift`: Updates service API and documentation - * Allow developers to download GameLift fleet creation logs to assist with debugging. -* `service/ssm`: Updates service API and documentation - * Adding Resource Data Sync support to SSM Inventory. New APIs: * CreateResourceDataSync - creates a new resource data sync configuration, * ListResourceDataSync - lists existing resource data sync configurations, * DeleteResourceDataSync - deletes an existing resource data sync configuration. - -Release v1.10.4 (2017-06-27) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Proper tagging of resources is critical to post-launch operations such as billing, cost allocation, and resource management. By using Service Catalog's TagOption Library, administrators can define a library of re-usable TagOptions that conform to company standards, and associate these with Service Catalog portfolios and products. Learn how to move your current tags to the new library, create new TagOptions, and view and associate your library items with portfolios and products. Understand how to ensure that the right tags are created on products launched through Service Catalog and how to provide users with defined selectable tags. - -### SDK Bugs -* `aws/signer/v4`: checking length on `stripExcessSpaces` [#1372](https://github.com/aws/aws-sdk-go/issues/1372) - * Fixes a bug where `stripExcessSpaces` did not check length against the slice. - * Fixes: [#1371](https://github.com/aws/aws-sdk-go/issues/1371) -Release v1.10.3 (2017-06-23) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * The Lambda Invoke API will now throw new exception InvalidRuntimeException (status code 502) for invokes with deprecated runtimes. - -Release v1.10.2 (2017-06-22) -=== - -### Service Client Updates -* `service/codepipeline`: Updates service API, documentation, and paginators - * A new API, ListPipelineExecutions, enables you to retrieve summary information about the most recent executions in a pipeline, including pipeline execution ID, status, start time, and last updated time. You can request information for a maximum of 100 executions. Pipeline execution data is available for the most recent 12 months of activity. -* `service/dms`: Updates service API and documentation - * Added tagging for DMS certificates. -* `service/elasticloadbalancing`: Updates service waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * This release adds a new nextPageToken property to the result of the GetOperationsForResource API. Developers can now get the next set of items in a list by making subsequent calls to GetOperationsForResource API with the token from the previous call. This release also deprecates the nextPageCount property, which previously returned null (use the nextPageToken property instead). This release also deprecates the customImageName property on the CreateInstancesRequest class, which was previously ignored by the API. -* `service/route53`: Updates service API and documentation - * This release reintroduces the HealthCheckInUse exception. - -Release v1.10.1 (2017-06-21) -=== - -### Service Client Updates -* `service/dax`: Adds new service - * Amazon DynamoDB Accelerator (DAX) is a fully managed, highly available, in-memory cache for DynamoDB that delivers up to a 10x performance improvement - from milliseconds to microseconds - even at millions of requests per second. DAX does all the heavy lifting required to add in-memory acceleration to your DynamoDB tables, without requiring developers to manage cache invalidation, data population, or cluster management. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports multivalue answers in response to DNS queries, which lets you route traffic approximately randomly to multiple resources, such as web servers. Create one multivalue answer record for each resource and, optionally, associate an Amazon Route 53 health check with each record, and Amazon Route 53 responds to DNS queries with up to eight healthy records. -* `service/ssm`: Updates service API, documentation, and paginators - * Adding hierarchy support to the SSM Parameter Store API. Added support tor tagging. New APIs: GetParameter - retrieves one parameter, DeleteParameters - deletes multiple parameters (max number 10), GetParametersByPath - retrieves parameters located in the hierarchy. Updated APIs: PutParameter - added ability to enforce parameter value by applying regex (AllowedPattern), DescribeParameters - modified to support Tag filtering. -* `service/waf`: Updates service API and documentation - * You can now create, edit, update, and delete a new type of WAF rule with a rate tracking component. -* `service/waf-regional`: Updates service API and documentation - -Release v1.10.0 (2017-06-20) -=== - -### Service Client Updates -* `service/workdocs`: Updates service API and documentation - * This release provides a new API to retrieve the activities performed by WorkDocs users. - -### SDK Features -* `aws/credentials/plugincreds`: Add support for Go plugin for credentials [#1320](https://github.com/aws/aws-sdk-go/pull/1320) - * Adds support for using plugins to retrieve credentials for API requests. This change adds a new package plugincreds under aws/credentials. See the `example/aws/credentials/plugincreds` folder in the SDK for example usage. - -Release v1.9.00 (2017-06-19) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * Improvements to Exception Modeling - -### SDK Features -* `service/s3/s3manager`: Adds batch operations to s3manager [#1333](https://github.com/aws/aws-sdk-go/pull/1333) - * Allows for batch upload, download, and delete of objects. Also adds the interface pattern to allow for easy traversal of objects. E.G `DownloadWithIterator`, `UploadWithIterator`, and `BatchDelete`. `BatchDelete` also contains a utility iterator using the `ListObjects` API to easily delete a list of objects. - -Release v1.8.44 (2017-06-16) -=== - -### Service Client Updates -* `service/xray`: Updates service API, documentation, and paginators - * Add a response time histogram to the services in response of GetServiceGraph API. - -Release v1.8.43 (2017-06-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adds API to describe Amazon FPGA Images (AFIs) available to customers, which includes public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. -* `service/ecs`: Updates service API and documentation - * Added support for cpu, memory, and memory reservation container overrides on the RunTask and StartTask APIs. -* `service/iot`: Updates service API and documentation - * Revert the last release: remove CertificatePem from DescribeCertificate API. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Added ProvisioningArtifactSummaries to DescribeProductAsAdmin's output to show the provisioning artifacts belong to the product. Allow filtering by SourceProductId in SearchProductsAsAdmin for AWS Marketplace products. Added a verbose option to DescribeProvisioningArtifact to display the CloudFormation template used to create the provisioning artifact.Added DescribeProvisionedProduct API. Changed the type of ProvisionedProduct's Status to be distinct from Record's Status. New ProvisionedProduct's Status are AVAILABLE, UNDER_CHANGE, TAINTED, ERROR. Changed Record's Status set of values to CREATED, IN_PROGRESS, IN_PROGRESS_IN_ERROR, SUCCEEDED, FAILED. - -### SDK Bugs -* `private/model/api`: Fix RESTXML support for XML Namespace [#1343](https://github.com/aws/aws-sdk-go/pull/1343) - * Fixes a bug with the SDK's generation of services using the REST XML protocol not annotating shape references with the XML Namespace attribute. - * Fixes [#1334](https://github.com/aws/aws-sdk-go/pull/1334) -Release v1.8.42 (2017-06-14) -=== - -### Service Client Updates -* `service/applicationautoscaling`: Updates service API and documentation -* `service/clouddirectory`: Updates service documentation - * Documentation update for Cloud Directory - -Release v1.8.41 (2017-06-13) -=== - -### Service Client Updates -* `service/configservice`: Updates service API - -Release v1.8.40 (2017-06-13) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * API Update for RDS: this update enables copy-on-write, a new Aurora MySQL Compatible Edition feature that allows users to restore their database, and support copy of TDE enabled snapshot cross region. - -### SDK Bugs -* `aws/request`: Fix NewErrParamMinLen to use correct ParamMinLenErrCode [#1336](https://github.com/aws/aws-sdk-go/issues/1336) - * Fixes the `NewErrParamMinLen` function returning the wrong error code. `ParamMinLenErrCode` should be returned not `ParamMinValueErrCode`. - * Fixes [#1335](https://github.com/aws/aws-sdk-go/issues/1335) -Release v1.8.39 (2017-06-09) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworks`: Updates service API and documentation - * Tagging Support for AWS OpsWorks Stacks - -Release v1.8.38 (2017-06-08) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * In addition to using certificate ID, AWS IoT customers can now obtain the description of a certificate with the certificate PEM. -* `service/pinpoint`: Updates service API and documentation - * Starting today Amazon Pinpoint adds SMS Text and Email Messaging support in addition to Mobile Push Notifications, providing developers, product managers and marketers with multi-channel messaging capabilities to drive user engagement in their applications. Pinpoint also enables backend services and applications to message users directly and provides advanced user and app analytics to understand user behavior and messaging performance. -* `service/rekognition`: Updates service API and documentation - * API Update for AmazonRekognition: Adding RecognizeCelebrities API - -Release v1.8.37 (2017-06-07) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Add support to APIs for privileged containers. This change would allow performing privileged operations like starting the Docker daemon inside builds possible in custom docker images. -* `service/greengrass`: Adds new service - * AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud. - -Release v1.8.36 (2017-06-06) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation update for AWS Certificate Manager. -* `service/cloudfront`: Updates service documentation - * Doc update to fix incorrect prefix in S3OriginConfig -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API - * Update client side validation for SalesForce action. - -Release v1.8.35 (2017-06-05) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * AppStream 2.0 Custom Security Groups allows you to easily control what network resources your streaming instances and images have access to. You can assign up to 5 security groups per Fleet to control the inbound and outbound network access to your streaming instances to specific IP ranges, network protocols, or ports. -* `service/iot`: Updates service API, documentation, paginators, and examples - * Added Salesforce action to IoT Rules Engine. - -Release v1.8.34 (2017-06-02) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API, documentation, and paginators - * Kinesis Analytics publishes error messages CloudWatch logs in case of application misconfigurations -* `service/workdocs`: Updates service API and documentation - * This release includes new APIs to manage tags and custom metadata on resources and also new APIs to add and retrieve comments at the document level. - -Release v1.8.33 (2017-06-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has improved how it manages connections to GitHub accounts and repositories. You can now create and store up to 25 connections to GitHub accounts in order to associate AWS CodeDeploy applications with GitHub repositories. Each connection can support multiple repositories. You can create connections to up to 25 different GitHub accounts, or create more than one connection to a single account. The ListGitHubAccountTokenNames command has been introduced to retrieve the names of stored connections to GitHub accounts that you have created. The name of the connection to GitHub used for an AWS CodeDeploy application is also included in the ApplicationInfo structure. Two new fields, lastAttemptedDeployment and lastSuccessfulDeployment, have been added to DeploymentGroupInfo to improve the handling of deployment group information in the AWS CodeDeploy console. Information about these latest deployments can also be retrieved using the GetDeploymentGroup and BatchGetDeployment group requests. Also includes a region update (us-gov-west-1). -* `service/cognitoidentityprovider`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lexmodelbuildingservice`: Updates service documentation and examples - -### SDK Enhancements -* `aws/defaults`: Exports shared credentials and config default filenames used by the SDK. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * Adds SharedCredentialsFilename and SharedConfigFilename functions to defaults package. - -### SDK Bugs -* `aws/credentials`: Fixes shared credential provider's default filename on Windows. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * The shared credentials provider would attempt to use the wrong filename on Windows if the `HOME` environment variable was defined. -* `service/s3/s3manager`: service/s3/s3manager: Fix Downloader ignoring Range get parameter [#1311](https://github.com/aws/aws-sdk-go/pull/1311) - * Fixes the S3 Download Manager ignoring the GetObjectInput's Range parameter. If this parameter is provided it will force the downloader to fallback to a single GetObject request disabling concurrency and automatic part size gets. - * Fixes [#1296](https://github.com/aws/aws-sdk-go/issues/1296) -Release v1.8.32 (2017-05-31) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Amazon RDS customers can now easily and quickly stop and start their DB instances. - -Release v1.8.31 (2017-05-30) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Cloud Directory has launched support for Typed Links, enabling customers to create object-to-object relationships that are not hierarchical in nature. Typed Links enable customers to quickly query for data along these relationships. Customers can also enforce referential integrity using Typed Links, ensuring data in use is not inadvertently deleted. -* `service/s3`: Updates service paginators and examples - * New example snippets for Amazon S3. - -Release v1.8.30 (2017-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Support added for persistent user storage, backed by S3. -* `service/rekognition`: Updates service API and documentation - * Updated the CompareFaces API response to include orientation information, unmatched faces, landmarks, pose, and quality of the compared faces. - -Release v1.8.29 (2017-05-24) -=== - -### Service Client Updates -* `service/iam`: Updates service API - * The unique ID and access key lengths were extended from 32 to 128 -* `service/storagegateway`: Updates service API and documentation - * Two Storage Gateway data types, Tape and TapeArchive, each have a new response element, TapeUsedInBytes. This element helps you manage your virtual tapes. By using TapeUsedInBytes, you can see the amount of data written to each virtual tape. -* `service/sts`: Updates service API, documentation, and paginators - * The unique ID and access key lengths were extended from 32 to 128. - -Release v1.8.28 (2017-05-23) -=== - -### Service Client Updates -* `service/databasemigrationservice`: Updates service API, documentation, paginators, and examples - * This release adds support for using Amazon S3 and Amazon DynamoDB as targets for database migration, and using MongoDB as a source for database migration. For more information, see the AWS Database Migration Service documentation. - -Release v1.8.27 (2017-05-22) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Updates service API, documentation, and paginators - * You can now specify the number of resources returned per page in GetResources operation, as an optional parameter, to easily manage the list of resources returned by your queries. - -### SDK Bugs -* `aws/request`: Add support for PUT temporary redirects (307) [#1283](https://github.com/aws/aws-sdk-go/issues/1283) - * Adds support for Go 1.8's GetBody function allowing the SDK's http request using PUT and POST methods to be redirected with temporary redirects with 307 status code. - * Fixes: [#1267](https://github.com/aws/aws-sdk-go/issues/1267) -* `aws/request`: Add handling for retrying temporary errors during unmarshal [#1289](https://github.com/aws/aws-sdk-go/issues/1289) - * Adds support for retrying temporary errors that occur during unmarshaling of a request's response body. - * Fixes: [#1275](https://github.com/aws/aws-sdk-go/issues/1275) -Release v1.8.26 (2017-05-18) -=== - -### Service Client Updates -* `service/athena`: Adds new service - * This release adds support for Amazon Athena. Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. -* `service/lightsail`: Updates service API, documentation, and paginators - * This release adds new APIs that make it easier to set network port configurations on Lightsail instances. Developers can now make a single request to both open and close public ports on an instance using the PutInstancePublicPorts operation. - -### SDK Bugs -* `aws/request`: Fix logging from reporting wrong retry request errors #1281 - * Fixes the SDK's retry request logging to report the the actual error that occurred, not a stubbed Unknown error message. - * Fixes the SDK's response logger to not output the response log multiple times per retry. -Release v1.8.25 (2017-05-17) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service documentation, paginators, and examples - * Various Auto Scaling documentation updates -* `service/cloudwatchevents`: Updates service documentation - * Various CloudWatch Events documentation updates. -* `service/cloudwatchlogs`: Updates service documentation and paginators - * Various CloudWatch Logs documentation updates. -* `service/polly`: Updates service API - * Amazon Polly adds new German voice "Vicki" - -Release v1.8.24 (2017-05-16) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * This release introduces the previousRevision field in the responses to the GetDeployment and BatchGetDeployments actions. previousRevision provides information about the application revision that was deployed to the deployment group before the most recent successful deployment. Also, the fileExistsBehavior parameter has been added for CreateDeployment action requests. In the past, if the AWS CodeDeploy agent detected files in a target location that weren't part of the application revision from the most recent successful deployment, it would fail the current deployment by default. This new parameter provides options for how the agent handles these files: fail the deployment, retain the content, or overwrite the content. -* `service/gamelift`: Updates service API and documentation - * Allow developers to specify how metrics are grouped in CloudWatch for their GameLift fleets. Developers can also specify how many concurrent game sessions activate on a per-instance basis. -* `service/inspector`: Updates service API, documentation, paginators, and examples - * Adds ability to produce an assessment report that includes detailed and comprehensive results of a specified assessment run. -* `service/kms`: Updates service documentation - * Update documentation for KMS. - -Release v1.8.23 (2017-05-15) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * UpdateAssociation API now supports updating document name and targets of an association. GetAutomationExecution API can return FailureDetails as an optional field to the StepExecution Object, which contains failure type, failure stage as well as other failure related information for a failed step. - -### SDK Enhancements -* `aws/session`: SDK should be able to load multiple custom shared config files. [#1258](https://github.com/aws/aws-sdk-go/issues/1258) - * This change adds a `SharedConfigFiles` field to the `session.Options` type that allows you to specify the files, and their order, the SDK will use for loading shared configuration and credentials from when the `Session` is created. Use the `NewSessionWithOptions` Session constructor to specify these options. You'll also most likely want to enable support for the shared configuration file's additional attributes by setting `session.Option`'s `SharedConfigState` to `session.SharedConfigEnabled`. - -Release v1.8.22 (2017-05-11) -=== - -### Service Client Updates -* `service/elb`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `service/lexmodelbuildingservice`: Updates service API and documentation -* `service/organizations`: Updates service API, documentation, paginators, and examples - * AWS Organizations APIs that return an Account object now include the email address associated with the account’s root user. - -Release v1.8.21 (2017-05-09) -=== - -### Service Client Updates -* `service/codestar`: Updates service documentation - * Updated documentation for AWS CodeStar. -* `service/workspaces`: Updates service API, documentation, and paginators - * Doc-only Update for WorkSpaces - -Release v1.8.20 (2017-05-04) -=== - -### Service Client Updates -* `service/ecs`: Updates service API, documentation, and paginators - * Exposes container instance registration time in ECS:DescribeContainerInstances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/marketplaceentitlementservice`: Adds new service -* `service/lambda`: Updates service API and documentation - * Support for UpdateFunctionCode DryRun option - -Release v1.8.19 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding back the removed waiters and paginators. - -Release v1.8.18 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples - * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. -* `service/rds`: Updates service API, documentation, and examples - * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. -* `service/rekognition`: Updates service API - * Fix for missing file type check -* `service/snowball`: Updates service API, documentation, and paginators - * The Snowball API has a new exception that can be thrown for list operation requests. -* `service/sqs`: Updates service API, documentation, and paginators - * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. - -Release v1.8.17 (2017-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. - -Release v1.8.16 (2017-04-21) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and paginators - * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. -* `service/kinesis`: Updates service API, documentation, waiters, and paginators - * Adds a new waiter, StreamNotExists, to Kinesis. - -### SDK Enhancements -* `aws/endpoints`: Add utilities improving endpoints lookup (#1218) - * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. - * Fixes #994 - -### SDK Bugs -* `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) - * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. - * Fixes #1205 -Release v1.8.15 (2017-04-20) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * API Update for AWS Device Farm: Support for Deals and Promotions -* `service/directconnect`: Updates service documentation - * Documentation updates for AWS Direct Connect. -* `service/elbv2`: Updates service waiters -* `service/kms`: Updates service documentation and examples - * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom -* `service/route53`: Updates service documentation - * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. -* `service/route53domains`: Updates service API, documentation, and paginators - * Adding examples and other documentation updates. - -### SDK Enhancements -* `service/s3`: Add utilities to make getting a bucket's region easier (#1207) - * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. - -### SDK Bugs -* `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) - * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. - * Fixes #1208 - -Release v1.8.14 (2017-04-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for "embed" property. -* `service/codestar`: Adds new service - * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. -* `service/ec2`: Updates service API and documentation - * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). -* `service/iam`: Updates service API and documentation - * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. -* `service/lambda`: Updates service API and documentation - * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. -* `service/lexmodelbuildingservice`: Adds new service -* `service/polly`: Updates service API, documentation, and paginators - * API Update for Amazon Polly: Add support for speech marks -* `service/rekognition`: Updates service API and documentation - * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. - -Release v1.8.13 (2017-04-18) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. - -### SDK Enhancements -* `aws/request`: add support for appengine's custom standard library (#1190) - * Remove syscall error checking on appengine platforms. - -Release v1.8.12 (2017-04-11) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway request validators -* `service/batch`: Updates service API and documentation - * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment -* `service/gamelift`: Updates service API and documentation - * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. -* `service/opsworks`: Updates service API, documentation, and paginators - * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. - -### SDK Bugs -* `aws/client`: Fix clients polluting handler list (#1197) - * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. - * Fixes #1184 -* `aws/request`: Fix waiter error match condition (#1195) - * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. -Release v1.8.11 (2017-04-07) -=== - -### Service Client Updates -* `service/redshift`: Updates service API, documentation, and paginators - * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. - -Release v1.8.10 (2017-04-06) -=== - -### Service Client Updates -* `service/elbv2`: Updates service documentation - -Release v1.8.9 (2017-04-05) -=== - -### Service Client Updates -* `service/elasticache`: Updates service API, documentation, paginators, and examples - * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. - -Release v1.8.8 (2017-04-04) -=== - -### Service Client Updates -* `service/cloudwatch`: Updates service API, documentation, and paginators - * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. - -Release v1.8.7 (2017-04-03) -=== - -### Service Client Updates -* `service/lexruntimeservice`: Updates service API and documentation - * Adds support to PostContent for speech input - -### SDK Enhancements -* `aws/request`: Improve handler copy, push back, push front performance (#1171) - * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. -* Update codegen header to use Go std wording (#1172) - * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. - -### SDK Bugs -* `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) - * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. -Release v1.8.6 (2017-04-01) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * ListObjectAttributes now supports filtering by facet. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.8.5 (2017-03-30) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding paginators for ListExports and ListImports -* `service/cloudfront`: Adds new service - * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers -* `service/configservice`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Adds new service -* `service/storagegateway`: Updates service API and documentation - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. - -Release v1.8.4 (2017-03-28) -=== - -### Service Client Updates -* `service/batch`: Updates service API, documentation, and paginators - * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. -* `service/ec2`: Updates service API and documentation - * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at - the time of their creation. You can do this from the EC2 Instance launch - wizard or through the RunInstances or CreateVolume APIs. By tagging - resources at the time of creation, you can eliminate the need to run custom - tagging scripts after resource creation. In addition, you can now set - resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and - the RunInstances APIs. This allows you to implement stronger security - policies by giving you more granular control over which users and groups - have access to these APIs. You can also enforce the use of tagging and - control what tag keys and values are set on your resources. When you combine - tag usage and resource-level IAM policies together, you can ensure your - instances and volumes are properly secured upon creation and achieve more - accurate cost allocation reporting. These new features are provided at no - additional cost. - -### SDK Enhancements -* `aws/request`: Add retry support for RequestTimeoutException (#1158) - * Adds support for retrying RequestTimeoutException error code that is returned by some services. - -### SDK Bugs -* `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) - * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. -Release v1.8.3 (2017-03-27) -=== - -## Service Client Updates -* `service/ssm`: Updates service API, documentation, and paginators - * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. -Release v1.8.2 (2017-03-24) -=== - -Service Client Updates ---- -* `service/applicationautoscaling`: Updates service API, documentation, and paginators - * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. -* `service/cloudtrail`: Updates service API and documentation - * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors - -Release v1.8.1 (2017-03-23) -=== - -Service Client Updates ---- -* `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators - * Adds export configuration options to the AWS Discovery Service API. -* `service/elbv2`: Updates waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and paginators - * Adds support for new runtime Node.js v6.10 for AWS Lambda service - -Release v1.8.0 (2017-03-22) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation -* `service/directconnect`: Updates service API - * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. -* `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators - * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. -* `service/pinpoint`: Updates service API and documentation - * Amazon Pinpoint User Segmentation - * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview - * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose - * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream -* `service/rekognition`: Updates service documentation. - -SDK Features ---- -* `aws/request`: Add support for context.Context to SDK API operation requests (#1132) - * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). - * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. - * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. - * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. - * Adds Context support for s3manager and s3crypto clients. - -SDK Enhancements ---- -* `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) - * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. - -SDK Bug Fixes ---- -* `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) - * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. -* `private/model/api`: Do not return a link if uid is empty (#1133) - * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. -* `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) -Release v1.7.9 (2017-03-13) -=== - -Service Client Updates ---- -* `service/devicefarm`: Updates service API, documentation, paginators, and examples - * Network shaping allows users to simulate network connections and conditions while testing their Android, iOS, and web apps with AWS Device Farm. -* `service/cloudwatchevents`: Updates service API, documentation, and examples - -SDK Enhancement -=== -* `aws/session`: Add support for side loaded CA bundles (#1117) - * Adds supports for side loading Certificate Authority bundle files to the SDK using AWS_CA_BUNDLE environment variable or CustomCABundle session option. -* `service/s3/s3crypto`: Add support for AES/CBC/PKCS5Padding (#1124) - -SDK Bug -=== -* `service/rds`: Fixing issue when not providing `SourceRegion` on cross -region operations (#1127) -* `service/rds`: Enables cross region for `CopyDBClusterSnapshot` and -`CreateDBCluster` (#1128) - -Release v1.7.8 (2017-03-10) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service paginators - * Add paginators for Codedeploy -* `service/emr`: Updates service API, documentation, and paginators - * This release includes support for instance fleets in Amazon EMR. - -Release v1.7.7 (2017-03-09) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API, documentation, and paginators - * API Gateway has added support for ACM certificates on custom domain names. Both Amazon-issued certificates and uploaded third-part certificates are supported. -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Introduces a new Cloud Directory API that enables you to retrieve all available parent paths for any type of object (a node, leaf node, policy node, and index node) in a hierarchy. - -Release v1.7.6 (2017-03-09) -=== - -Service Client Updates ---- -* `service/organizations`: Updates service documentation and examples - * Doc-only Update for Organizations: Add SDK Code Snippets -* `service/workdocs`: Adds new service - * The Administrative SDKs for Amazon WorkDocs provides full administrator level access to WorkDocs site resources, allowing developers to integrate their applications to manage WorkDocs users, content and permissions programmatically - -Release v1.7.5 (2017-03-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Add support to using encrypted clusters as cross-region replication masters. Update CopyDBClusterSnapshot API to support encrypted cross region copy of Aurora cluster snapshots. - -Release v1.7.4 (2017-03-06) -=== - -Service Client Updates ---- -* `service/budgets`: Updates service API and paginators - * When creating or editing a budget via the AWS Budgets API you can define notifications that are sent to subscribers when the actual or forecasted value for cost or usage exceeds the notificationThreshold associated with the budget notification object. Starting today, the maximum allowed value for the notificationThreshold was raised from 100 to 300. This change was made to give you more flexibility when setting budget notifications. -* `service/cloudtrail`: Updates service documentation and paginators - * Doc-only update for AWSCloudTrail: Updated links/descriptions -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworkscm`: Updates service API, documentation, and paginators - * OpsWorks for Chef Automate has added a new field "AssociatePublicIpAddress" to the CreateServer request, "CloudFormationStackArn" to the Server model and "TERMINATED" server state. - - -Release v1.7.3 (2017-02-28) -=== - -Service Client Updates ---- -* `service/mturk`: Renaming service - * service/mechanicalturkrequesterservice was renamed to service/mturk. Be sure to change any references of the old client to the new. - -Release v1.7.2 (2017-02-28) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API and documentation - * Release notes: Time to Live (TTL) is a feature that allows you to define when items in a table expire and can be purged from the database, so that you don't have to track expired data and delete it manually. With TTL enabled on a DynamoDB table, you can set a timestamp for deletion on a per-item basis, allowing you to limit storage usage to only those records that are relevant. -* `service/iam`: Updates service API, documentation, and paginators - * This release adds support for AWS Organizations service control policies (SCPs) to SimulatePrincipalPolicy operation. If there are SCPs associated with the simulated user's account, their effect on the result is captured in the OrganizationDecisionDetail element in the EvaluationResult. -* `service/mechanicalturkrequesterservice`: Adds new service - * Amazon Mechanical Turk is a web service that provides an on-demand, scalable, human workforce to complete jobs that humans can do better than computers, for example, recognizing objects in photos. -* `service/organizations`: Adds new service - * AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources. -* `service/dynamodbstreams`: Updates service API, documentation, and paginators -* `service/waf`: Updates service API, documentation, and paginators - * Aws WAF - For GetSampledRequests action, changed max number of samples from 100 to 500. -* `service/wafregional`: Updates service API, documentation, and paginators - -Release v1.7.1 (2017-02-24) -=== - -Service Client Updates ---- -* `service/elasticsearchservice`: Updates service API, documentation, paginators, and examples - * Added three new API calls to existing Amazon Elasticsearch service to expose Amazon Elasticsearch imposed limits to customers. - -Release v1.7.0 (2017-02-23) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API - * New EC2 I3 instance type - -SDK Bug ---- -* `service/s3/s3manager`: Adding support for SSE (#1097) - * Fixes SSE fields not being applied to a part during multi part upload. - -SDK Feature ---- -* `aws/session`: Add support for AssumeRoles with MFA (#1088) - * Adds support for assuming IAM roles with MFA enabled. A TokenProvider func was added to stscreds.AssumeRoleProvider that will be called each time the role's credentials need to be refreshed. A basic token provider that sources the MFA token from stdin as stscreds.StdinTokenProvider. -* `aws/session`: Update SDK examples and docs to use session.Must (#1099) - * Updates the SDK's example and docs to use session.Must where possible to highlight its usage as apposed to session error checking that is most cases errors will be terminal to the application anyways. -Release v1.6.27 (2017-02-22) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Updates service documentation - * ListObjectAttributes documentation updated based on forum feedback -* `service/elasticbeanstalk`: Updates service API, documentation, and paginators - * Elastic Beanstalk adds support for creating and managing custom platform. -* `service/gamelift`: Updates service API, documentation, and paginators - * Allow developers to configure global queues for creating GameSessions. Allow PlayerData on PlayerSessions to store player-specific data. -* `service/route53`: Updates service API, documentation, and examples - * Added support for operations CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization to throw a ConcurrentModification error when a conflicting modification occurs in parallel to the authorizations in place for a given hosted zone. - -Release v1.6.26 (2017-02-21) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * Added the billingProduct parameter to the RegisterImage API. - -Release v1.6.25 (2017-02-17) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API, documentation, and paginators - * This update will introduce the ability for Direct Connect customers to take advantage of Link Aggregation (LAG). This allows you to bundle many individual physical interfaces into a single logical interface, referred to as a LAG. This makes administration much simpler as the majority of configuration is done on the LAG while you are free to add or remove physical interfaces from the bundle as bandwidth demand increases or decreases. A concrete example of the simplification added by LAG is that customers need only a single BGP session as opposed to one session per physical connection. - -Release v1.6.24 (2017-02-16) -=== - -Service Client Updates ---- -* `service/cognitoidentity`: Updates service API, documentation, and paginators - * Allow createIdentityPool and updateIdentityPool API to set server side token check value on identity pool -* `service/configservice`: Updates service API and documentation - * AWS Config now supports a new test mode for the PutEvaluations API. Set the TestMode parameter to true in your custom rule to verify whether your AWS Lambda function will deliver evaluation results to AWS Config. No updates occur to your existing evaluations, and evaluation results are not sent to AWS Config. - -Release v1.6.23 (2017-02-15) -=== - -Service Client Updates ---- -* `service/kms`: Updates service API, documentation, paginators, and examples - * his release of AWS Key Management Service introduces the ability to tag keys. Tagging keys can help you organize your keys and track your KMS costs in the cost allocation report. This release also increases the maximum length of a key ID to accommodate ARNs that include a long key alias. - -Release v1.6.22 (2017-02-14) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Adds support for the new Modify Volumes apis. - -Release v1.6.21 (2017-02-11) -=== - -Service Client Updates ---- -* `service/storagegateway`: Updates service API, documentation, and paginators - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. This is done by creating Nfs file shares using existing APIs CreateNfsFileShare. Using the feature in this update, the customer can restrict the clients that have read/write access to the gateway by specifying the list of clients as a list of IP addresses or CIDR blocks. This list can be specified using the API CreateNfsFileShare while creating new file shares, or UpdateNfsFileShare while update existing file shares. To find out the list of clients that have access, the existing API DescribeNfsFileShare will now output the list of clients that have access. - -Release v1.6.20 (2017-02-09) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * This feature allows customers to associate an IAM profile to running instances that do not have any. -* `service/rekognition`: Updates service API and documentation - * DetectFaces and IndexFaces operations now return an estimate of the age of the face as an age range. - -SDK Features ---- -* `aws/endpoints`: Add option to resolve unknown endpoints (#1074) -Release v1.6.19 (2017-02-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service examples - * Doc Update -* `service/lexruntimeservice`: Adds new service - * Preview release - -SDK Bug Fixes ---- -* `private/protocol/json`: Fixes json to throw an error if a float number is (+/-)Inf and NaN (#1068) -* `private/model/api`: Fix documentation error listing (#1067) - -SDK Features ---- -* `private/model`: Add service response error code generation (#1061) - -Release v1.6.18 (2017-01-27) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Adds new service - * Amazon Cloud Directory is a highly scalable, high performance, multi-tenant directory service in the cloud. Its web-based directories make it easy for you to organize and manage application resources such as users, groups, locations, devices, policies, and the rich relationships between them. -* `service/codedeploy`: Updates service API, documentation, and paginators - * This release of AWS CodeDeploy introduces support for blue/green deployments. In a blue/green deployment, the current set of instances in a deployment group is replaced by new instances that have the latest application revision installed on them. After traffic is rerouted behind a load balancer to the replacement instances, the original instances can be terminated automatically or kept running for other uses. -* `service/ec2`: Updates service API and documentation - * Adds instance health check functionality to replace unhealthy EC2 Spot fleet instances with fresh ones. -* `service/rds`: Updates service API and documentation - * Snapshot Engine Version Upgrade - -Release v1.6.17 (2017-01-25) -=== - -Service Client Updates ---- -* `service/elbv2`: Updates service API, documentation, and paginators - * Application Load Balancers now support native Internet Protocol version 6 (IPv6) in an Amazon Virtual Private Cloud (VPC). With this ability, clients can now connect to the Application Load Balancer in a dual-stack mode via either IPv4 or IPv6. -* `service/rds`: Updates service API and documentation - * Cross Region Read Replica Copying (CreateDBInstanceReadReplica) - -Release v1.6.16 (2017-01-24) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation and paginators - * Documentation updates -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now includes the option to view the differences between a commit and its parent commit from within the console. You can view the differences inline (Unified view) or side by side (Split view). To view information about the differences between a commit and something other than its parent, you can use the AWS CLI and the get-differences and get-blob commands, or you can use the GetDifferences and GetBlob APIs. -* `service/ecs`: Updates service API and documentation - * Amazon ECS now supports a state for container instances that can be used to drain a container instance in preparation for maintenance or cluster scale down. - -Release v1.6.15 (2017-01-20) -=== - -Service Client Updates ---- -* `service/acm`: Updates service API, documentation, and paginators - * Update for AWS Certificate Manager: Updated response elements for DescribeCertificate API in support of managed renewal -* `service/health`: Updates service documentation - -Release v1.6.14 (2017-01-19) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Amazon EC2 Spot instances now support dedicated tenancy, providing the ability to run Spot instances single-tenant manner on physically isolated hardware within a VPC to satisfy security, privacy, or other compliance requirements. Dedicated Spot instances can be requested using RequestSpotInstances and RequestSpotFleet. - -Release v1.6.13 (2017-01-18) -=== - -Service Client Updates ---- -* `service/rds`: Updates service API, documentation, and paginators - -Release v1.6.12 (2017-01-17) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API, documentation, and paginators - * Tagging Support for Amazon DynamoDB Tables and Indexes -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service API, paginators, and examples - * Doc-only Update for Glacier: Added code snippets -* `service/polly`: Updates service documentation and examples - * Doc-only update for Amazon Polly -- added snippets -* `service/rekognition`: Updates service documentation and paginators - * Added code samples to Rekognition reference topics. -* `service/route53`: Updates service API and paginators - * Add ca-central-1 and eu-west-2 enum values to CloudWatchRegion enum - -Release v1.6.11 (2017-01-16) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API, documentation, and paginators -* `service/costandusagereportservice`: Adds new service - * The AWS Cost and Usage Report Service API allows you to enable and disable the Cost & Usage report, as well as modify the report name, the data granularity, and the delivery preferences. -* `service/dynamodb`: Updates service API, documentation, and examples - * Snippets for the DynamoDB API. -* `service/elasticache`: Updates service API, documentation, and examples - * Adds new code examples. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.10 (2017-01-04) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API and documentation - * AWSConfig is planning to add support for OversizedConfigurationItemChangeNotification message type in putConfigRule. After this release customers can use/write rules based on OversizedConfigurationItemChangeNotification mesage type. -* `service/efs`: Updates service API, documentation, and examples - * Doc-only Update for EFS: Added code snippets -* `service/iam`: Updates service documentation and examples -* `service/lambda`: Updates service documentation and examples - * Doc only updates for Lambda: Added code snippets -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Added support for data set disbursed_amount_by_instance_hours, with historical data available starting 2012-09-04. New data is published to this data set every 30 days. -* `service/rds`: Updates service documentation - * Updated documentation for CopyDBSnapshot. -* `service/rekognition`: Updates service documentation and examples - * Doc-only Update for Rekognition: Added code snippets -* `service/snowball`: Updates service examples -* `service/dynamodbstreams`: Updates service API and examples - * Doc-only Update for DynamoDB Streams: Added code snippets - -SDK Feature ---- -* `private/model/api`: Increasing the readability of code generated files. (#1024) -Release v1.6.9 (2016-12-30) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service API and documentation - * CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication. -* `service/ecs`: Updates service API and documentation - * Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.8 (2016-12-22) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts. -* `service/directoryservice`: Updates service documentation - * Added code snippets for the DS SDKs -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/iam`: Updates service API and documentation - * Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service. -* `service/kms`: Updates service API, documentation, and examples - * Update docs and add SDK examples - -Release v1.6.7 (2016-12-22) -=== - -Service Client Updates ---- -* `service/ecr`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Cross Region Encrypted Snapshot Copying (CopyDBSnapshot) - -Release v1.6.6 (2016-12-20) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/firehose`: Updates service API, documentation, and examples - * Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations. -* `service/route53`: Updates service API and documentation - * Enum updates for eu-west-2 and ca-central-1 -* `service/storagegateway`: Updates service API, documentation, and examples - * File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. - -Release v1.6.5 (2016-12-19) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation - * Minor doc update for CloudFormation. -* `service/cloudtrail`: Updates service paginators -* `service/cognitoidentity`: Updates service API and documentation - * We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role -* `service/applicationdiscoveryservice`: Updates service API and documentation - * Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API. -* `service/inspector`: Updates service API, documentation, and examples - * Doc-only Update for Inspector: Adding SDK code snippets for Inspector -* `service/sqs`: Updates service documentation - -SDK Bug Fixes ---- -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1011) - * Fixes: Not retrying when PriorRequestNotComplete #1009 - -SDK Feature ---- -* `private/model/api`: Adds crosslinking to service documentation (#1010) - -Release v1.6.4 (2016-12-15) -=== - -Service Client Updates ---- -* `service/cognitoidentityprovider`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service API and documentation - * This will provide customers with access to the Patch Baseline and Patch Compliance APIs. - -SDK Bug Fixes ---- -* `service/route53`: Fix URL path cleaning for Route53 API requests (#1006) - * Fixes: SerializationError when using Route53 ChangeResourceRecordSets #1005 -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1002) - * Fixes: Not retrying when PriorRequestNotComplete #1001 - -Release v1.6.3 (2016-12-14) -=== - -Service Client Updates ---- -* `service/batch`: Adds new service - * AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs. -* `service/databasemigrationservice`: Updates service API and documentation - * Adds support for SSL enabled Oracle endpoints and task modification. -* `service/elasticbeanstalk`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/cloudwatchlogs`: Updates service API and documentation - * Add support for associating LogGroups with AWSTagris tags -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Add new enum to DataSetType: sales_compensation_billed_revenue -* `service/rds`: Updates service documentation - * Doc-only Update for RDS: New versions available in CreateDBInstance -* `service/sts`: Updates service documentation - * Adding Code Snippet Examples for SDKs for STS - -SDK Bug Fixes ---- -* `aws/request`: Fix retrying timeout requests (#981) - * Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947 -* `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991) - * Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984 -* private/protocol/rest: Use RawPath instead of Opaque (#993) - * Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray -* private/model/api: Generate REST-JSON JSONVersion correctly (#998) - * Fixes: REST-JSON protocol service code missing JSONVersion metadata. - -Release v1.6.2 (2016-12-08) -=== - -Service Client Updates ---- -* `service/cloudfront`: Add lambda function associations to cache behaviors -* `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content. -* `service/rds`: Updates service API and documentation -* `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc. - -Release v1.6.1 (2016-12-07) -=== - -Service Client Updates ---- -* `service/config`: Updates service API -* `service/s3`: Updates service API -* `service/sqs`: Updates service API and documentation - -Release v1.6.0 (2016-12-06) -=== - -Service Client Updates ---- -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API -* `service/sts`: Updates service API, documentation, and examples - -SDK Bug Fixes ---- -* private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975 - * Fixes GetBucketACL Grantee required type always nil. #916 - -SDK Feature ---- -* aws/endpoints: Add endpoint metadata to SDK #961 - * Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK. - -Release v1.5.13 (2016-12-01) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/appstream`: Adds new service -* `service/codebuild`: Adds new service -* `service/directconnect`: Updates service API and documentation -* `service/ec2`: Adds new service -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/health`: Adds new service -* `service/lambda`: Updates service API and documentation -* `service/opsworkscm`: Adds new service -* `service/pinpoint`: Adds new service -* `service/shield`: Adds new service -* `service/ssm`: Updates service API and documentation -* `service/states`: Adds new service -* `service/xray`: Adds new service - -Release v1.5.12 (2016-11-30) -=== - -Service Client Updates ---- -* `service/lightsail`: Adds new service -* `service/polly`: Adds new service -* `service/rekognition`: Adds new service -* `service/snowball`: Updates service API and documentation - -Release v1.5.11 (2016-11-29) -=== - -Service Client Updates ---- -`service/s3`: Updates service API and documentation - -Release v1.5.10 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/glacier`: Updates service API, documentation, and examples -* `service/route53`: Updates service API and documentation -* `service/s3`: Updates service API and documentation - -SDK Bug Fixes ---- -* `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly -into tagged fields -[#916](https://github.com/aws/aws-sdk-go/issues/916) - -Release v1.5.9 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudtrail`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - -Release v1.5.8 (2016-11-18) -=== - -Service Client Updates ---- -* `service/application-autoscaling`: Updates service API and documentation -* `service/elasticmapreduce`: Updates service API and documentation -* `service/elastictranscoder`: Updates service API, documentation, and examples -* `service/gamelift`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - -Release v1.5.7 (2016-11-18) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/meteringmarketplace`: Updates service API and documentation -* `service/monitoring`: Updates service API and documentation -* `service/sqs`: Updates service API, documentation, and examples - -Release v1.5.6 (2016-11-16) -=== - -Service Client Updates ---- -`service/route53`: Updates service API and documentation -`service/servicecatalog`: Updates service API and documentation - -Release v1.5.5 (2016-11-15) -=== - -Service Client Updates ---- -* `service/ds`: Updates service API and documentation -* `service/elasticache`: Updates service API and documentation -* `service/kinesis`: Updates service API and documentation - -Release v1.5.4 (2016-11-15) -=== - -Service Client Updates ---- -* `service/cognito-idp`: Updates service API and documentation - -Release v1.5.3 (2016-11-11) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation and examples -* `service/logs`: Updates service API and documentation - -Release v1.5.2 (2016-11-03) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API and documentation - -Release v1.5.1 (2016-11-02) -=== - -Service Client Updates ---- -* `service/email`: Updates service API and documentation - -Release v1.5.0 (2016-11-01) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/ecr`: Updates service paginators - -SDK Feature Updates ---- -* `private/model/api`: Add generated setters for API parameters (#918) - * Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility. - -Release v1.4.22 (2016-10-25) -=== - -Service Client Updates ---- -* `service/elasticloadbalancingv2`: Updates service documentation. -* `service/autoscaling`: Updates service documentation. - -Release v1.4.21 (2016-10-24) -=== - -Service Client Updates ---- -* `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations. -* `service/ecs`: Updates documentation. - -SDK Feature Updates ---- -* `private/models/api`: Improve code generation of documentation. - -Release v1.4.20 (2016-10-20) -=== - -Service Client Updates ---- -* `service/budgets`: Adds new service, AWS Budgets. -* `service/waf`: Updates service documentation. - -Release v1.4.19 (2016-10-18) -=== - -Service Client Updates ---- -* `service/cloudfront`: Updates service API and documentation. - * Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS. -* `service/configservice`: Update service API and documentation. -* `service/iot`: Updates service API and documentation. -* `service/kinesisanalytics`: Updates service API and documentation. - * Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema. -* `service/rds`: Updates service API and documentation. - * Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster. - -SDK Feature Updates ---- -* `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897 - * Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan. - -Release v1.4.18 (2016-10-17) -=== - -Service Model Updates ---- -* `service/route53`: Updates service API and documentation. - -Release v1.4.17 -=== - -Service Model Updates ---- -* `service/acm`: Update service API, and documentation. - * This change allows users to import third-party SSL/TLS certificates into ACM. -* `service/elasticbeanstalk`: Update service API, documentation, and pagination. - * Elastic Beanstalk DescribeApplicationVersions API is being updated to support pagination. -* `service/gamelift`: Update service API, and documentation. - * New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse. - -SDK Features ---- -* `service/s3`: Add support for accelerate with dualstack [#887](https://github.com/aws/aws-sdk-go/issues/887) - -Release v1.4.16 (2016-10-13) -=== - -Service Model Updates ---- -* `service/ecr`: Update Amazon EC2 Container Registry service model - * DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp. -* `service/elasticache`: Update Amazon ElastiCache service model - * Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities - -SDK Bug Fixes ---- -* `aws/session`: Skip shared config on read errors [#883](https://github.com/aws/aws-sdk-go/issues/883) -* `aws/signer/v4`: Add support for URL.EscapedPath to signer [#885](https://github.com/aws/aws-sdk-go/issues/885) - -SDK Features ---- -* `private/model/api`: Add docs for errors to API operations [#881](https://github.com/aws/aws-sdk-go/issues/881) -* `private/model/api`: Improve field and waiter doc strings [#879](https://github.com/aws/aws-sdk-go/issues/879) -* `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [#886](https://github.com/aws/aws-sdk-go/issues/886) -* Add build tags to internal SDK tools [#880](https://github.com/aws/aws-sdk-go/issues/880) - -Release v1.4.15 (2016-10-06) -=== - -Service Model Updates ---- -* `service/cognitoidentityprovider`: Update Amazon Cognito Identity Provider service model -* `service/devicefarm`: Update AWS Device Farm documentation -* `service/opsworks`: Update AWS OpsWorks service model -* `service/s3`: Update Amazon Simple Storage Service model -* `service/waf`: Update AWS WAF service model - -SDK Bug Fixes ---- -* `aws/request`: Fix HTTP Request Body race condition [#874](https://github.com/aws/aws-sdk-go/issues/874) - -SDK Feature Updates ---- -* `aws/ec2metadata`: Add support for EC2 User Data [#872](https://github.com/aws/aws-sdk-go/issues/872) -* `aws/signer/v4`: Remove logic determining if request needs to be resigned [#876](https://github.com/aws/aws-sdk-go/issues/876) - -Release v1.4.14 (2016-09-29) -=== -* `service/ec2`: api, documentation, and paginators updates. -* `service/s3`: api and documentation updates. - -Release v1.4.13 (2016-09-27) -=== -* `service/codepipeline`: documentation updates. -* `service/cloudformation`: api and documentation updates. -* `service/kms`: documentation updates. -* `service/elasticfilesystem`: documentation updates. -* `service/snowball`: documentation updates. diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md deleted file mode 100644 index 8a1927a39c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md +++ /dev/null @@ -1,5 +0,0 @@ -### SDK Features - -### SDK Enhancements - -### SDK Bugs diff --git a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md deleted file mode 100644 index 7c0186f0c9..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md +++ /dev/null @@ -1,127 +0,0 @@ -Contributing to the AWS SDK for Go - -We work hard to provide a high-quality and useful SDK, and we greatly value -feedback and contributions from our community. Whether it's a bug report, -new feature, correction, or additional documentation, we welcome your issues -and pull requests. Please read through this document before submitting any -issues or pull requests to ensure we have all the necessary information to -effectively respond to your bug report or contribution. - - -## Filing Bug Reports - -You can file bug reports against the SDK on the [GitHub issues][issues] page. - -If you are filing a report for a bug or regression in the SDK, it's extremely -helpful to provide as much information as possible when opening the original -issue. This helps us reproduce and investigate the possible bug without having -to wait for this extra information to be provided. Please read the following -guidelines prior to filing a bug report. - -1. Search through existing [issues][] to ensure that your specific issue has - not yet been reported. If it is a common issue, it is likely there is - already a bug report for your problem. - -2. Ensure that you have tested the latest version of the SDK. Although you - may have an issue against an older version of the SDK, we cannot provide - bug fixes for old versions. It's also possible that the bug may have been - fixed in the latest release. - -3. Provide as much information about your environment, SDK version, and - relevant dependencies as possible. For example, let us know what version - of Go you are using, which and version of the operating system, and the - the environment your code is running in. e.g Container. - -4. Provide a minimal test case that reproduces your issue or any error - information you related to your problem. We can provide feedback much - more quickly if we know what operations you are calling in the SDK. If - you cannot provide a full test case, provide as much code as you can - to help us diagnose the problem. Any relevant information should be provided - as well, like whether this is a persistent issue, or if it only occurs - some of the time. - - -## Submitting Pull Requests - -We are always happy to receive code and documentation contributions to the SDK. -Please be aware of the following notes prior to opening a pull request: - -1. The SDK is released under the [Apache license][license]. Any code you submit - will be released under that license. For substantial contributions, we may - ask you to sign a [Contributor License Agreement (CLA)][cla]. - -2. If you would like to implement support for a significant feature that is not - yet available in the SDK, please talk to us beforehand to avoid any - duplication of effort. - -3. Wherever possible, pull requests should contain tests as appropriate. - Bugfixes should contain tests that exercise the corrected behavior (i.e., the - test should fail without the bugfix and pass with it), and new features - should be accompanied by tests exercising the feature. - -4. Pull requests that contain failing tests will not be merged until the test - failures are addressed. Pull requests that cause a significant drop in the - SDK's test coverage percentage are unlikely to be merged until tests have - been added. - -5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. - Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests - directly on these models. If you discover an issue with the models please - create a Github [issue](issues) describing the issue. - -### Testing - -To run the tests locally, running the `make unit` command will `go get` the -SDK's testing dependencies, and run vet, link and unit tests for the SDK. - -``` -make unit -``` - -Standard go testing functionality is supported as well. To test SDK code that -is tagged with `codegen` you'll need to set the build tag in the go test -command. The `make unit` command will do this automatically. - -``` -go test -tags codegen ./private/... -``` - -See the `Makefile` for additional testing tags that can be used in testing. - -To test on multiple platform the SDK includes several DockerFiles under the -`awstesting/sandbox` folder, and associated make recipes to to execute -unit testing within environments configured for specific Go versions. - -``` -make sandbox-test-go18 -``` - -To run all sandbox environments use the following make recipe - -``` -# Optionally update the Go tip that will be used during the batch testing -make update-aws-golang-tip - -# Run all SDK tests for supported Go versions in sandboxes -make sandbox-test -``` - -In addition the sandbox environment include make recipes for interactive modes -so you can run command within the Docker container and context of the SDK. - -``` -make sandbox-go18 -``` - -### Changelog - -You can see all release changes in the `CHANGELOG.md` file at the root of the -repository. The release notes added to this file will contain service client -updates, and major SDK changes. - -[issues]: https://github.com/aws/aws-sdk-go/issues -[pr]: https://github.com/aws/aws-sdk-go/pulls -[license]: http://aws.amazon.com/apache2.0/ -[cla]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[releasenotes]: https://github.com/aws/aws-sdk-go/releases - diff --git a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go/LICENSE.txt deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/aws/aws-sdk-go/Makefile b/vendor/github.com/aws/aws-sdk-go/Makefile deleted file mode 100644 index df9803c2a2..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/Makefile +++ /dev/null @@ -1,180 +0,0 @@ -LINTIGNOREDOT='awstesting/integration.+should not use dot imports' -LINTIGNOREDOC='service/[^/]+/(api|service|waiters)\.go:.+(comment on exported|should have comment or be unexported)' -LINTIGNORECONST='service/[^/]+/(api|service|waiters)\.go:.+(type|struct field|const|func) ([^ ]+) should be ([^ ]+)' -LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)' -LINTIGNOREINFLECT='service/[^/]+/(api|errors|service)\.go:.+(method|const) .+ should be ' -LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be ' -LINTIGNOREDEPS='vendor/.+\.go' -LINTIGNOREPKGCOMMENT='service/[^/]+/doc_custom.go:.+package comment should be of the form' -UNIT_TEST_TAGS="example codegen awsinclude" - -SDK_WITH_VENDOR_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/src") -SDK_ONLY_PKGS=$(shell go list ./... | grep -v "/vendor/") -SDK_UNIT_TEST_ONLY_PKGS=$(shell go list -tags ${UNIT_TEST_TAGS} ./... | grep -v "/vendor/") -SDK_GO_1_4=$(shell go version | grep "go1.4") -SDK_GO_1_5=$(shell go version | grep "go1.5") -SDK_GO_VERSION=$(shell go version | awk '''{print $$3}''' | tr -d '''\n''') - -all: get-deps generate unit - -help: - @echo "Please use \`make ' where is one of" - @echo " api_info to print a list of services and versions" - @echo " docs to build SDK documentation" - @echo " build to go build the SDK" - @echo " unit to run unit tests" - @echo " integration to run integration tests" - @echo " performance to run performance tests" - @echo " verify to verify tests" - @echo " lint to lint the SDK" - @echo " vet to vet the SDK" - @echo " generate to go generate and make services" - @echo " gen-test to generate protocol tests" - @echo " gen-services to generate services" - @echo " get-deps to go get the SDK dependencies" - @echo " get-deps-tests to get the SDK's test dependencies" - @echo " get-deps-verify to get the SDK's verification dependencies" - -generate: gen-test gen-endpoints gen-services - -gen-test: gen-protocol-test - -gen-services: - go generate ./service - -gen-protocol-test: - go generate ./private/protocol/... - -gen-endpoints: - go generate ./models/endpoints/ - -build: - @echo "go build SDK and vendor packages" - @go build ${SDK_ONLY_PKGS} - -unit: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} $(SDK_UNIT_TEST_ONLY_PKGS) - -unit-with-race-cover: get-deps-tests build verify - @echo "go test SDK and vendor packages" - @go test -tags ${UNIT_TEST_TAGS} -race -cpu=1,2,4 $(SDK_UNIT_TEST_ONLY_PKGS) - -integration: get-deps-tests integ-custom smoke-tests performance - -integ-custom: - go test -tags "integration" ./awstesting/integration/customizations/... - -cleanup-integ: - go run -tags "integration" ./awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" - -smoke-tests: get-deps-tests - gucumber -go-tags "integration" ./awstesting/integration/smoke - -performance: get-deps-tests - AWS_TESTING_LOG_RESULTS=${log-detailed} AWS_TESTING_REGION=$(region) AWS_TESTING_DB_TABLE=$(table) gucumber -go-tags "integration" ./awstesting/performance - -sandbox-tests: sandbox-test-go15 sandbox-test-go15-novendorexp sandbox-test-go16 sandbox-test-go17 sandbox-test-go18 sandbox-test-gotip - -sandbox-build-go15: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5 -t "aws-sdk-go-1.5" . -sandbox-go15: sandbox-build-go15 - docker run -i -t aws-sdk-go-1.5 bash -sandbox-test-go15: sandbox-build-go15 - docker run -t aws-sdk-go-1.5 - -sandbox-build-go15-novendorexp: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5-novendorexp -t "aws-sdk-go-1.5-novendorexp" . -sandbox-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -i -t aws-sdk-go-1.5-novendorexp bash -sandbox-test-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -t aws-sdk-go-1.5-novendorexp - -sandbox-build-go16: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.6 -t "aws-sdk-go-1.6" . -sandbox-go16: sandbox-build-go16 - docker run -i -t aws-sdk-go-1.6 bash -sandbox-test-go16: sandbox-build-go16 - docker run -t aws-sdk-go-1.6 - -sandbox-build-go17: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.7 -t "aws-sdk-go-1.7" . -sandbox-go17: sandbox-build-go17 - docker run -i -t aws-sdk-go-1.7 bash -sandbox-test-go17: sandbox-build-go17 - docker run -t aws-sdk-go-1.7 - -sandbox-build-go18: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.8" . -sandbox-go18: sandbox-build-go18 - docker run -i -t aws-sdk-go-1.8 bash -sandbox-test-go18: sandbox-build-go18 - docker run -t aws-sdk-go-1.8 - -sandbox-build-gotip: - @echo "Run make update-aws-golang-tip, if this test fails because missing aws-golang:tip container" - docker build -f ./awstesting/sandbox/Dockerfile.test.gotip -t "aws-sdk-go-tip" . -sandbox-gotip: sandbox-build-gotip - docker run -i -t aws-sdk-go-tip bash -sandbox-test-gotip: sandbox-build-gotip - docker run -t aws-sdk-go-tip - -update-aws-golang-tip: - docker build --no-cache=true -f ./awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" . - -verify: get-deps-verify lint vet - -lint: - @echo "go lint SDK and vendor packages" - @lint=`if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then golint ./...; else echo "skipping golint"; fi`; \ - lint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOT} -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD} -e ${LINTIGNOREPKGCOMMENT}`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ] && [ "$$lint" != "skipping golint" ]; then exit 1; fi - -SDK_BASE_FOLDERS=$(shell ls -d */ | grep -v vendor | grep -v awsmigrate) -ifneq (,$(findstring go1.4, ${SDK_GO_VERSION})) - GO_VET_CMD=echo skipping go vet, ${SDK_GO_VERSION} -else ifneq (,$(findstring go1.6, ${SDK_GO_VERSION})) - GO_VET_CMD=go tool vet --all -shadow -example=false -else - GO_VET_CMD=go tool vet --all -shadow -endif - -vet: - ${GO_VET_CMD} ${SDK_BASE_FOLDERS} - -get-deps: get-deps-tests get-deps-verify - @echo "go get SDK dependencies" - @go get -v $(SDK_ONLY_PKGS) - -get-deps-tests: - @echo "go get SDK testing dependencies" - go get github.com/gucumber/gucumber/cmd/gucumber - go get github.com/stretchr/testify - go get github.com/smartystreets/goconvey - go get golang.org/x/net/html - go get golang.org/x/net/http2 - -get-deps-verify: - @echo "go get SDK verification utilities" - @if [ \( -z "${SDK_GO_1_4}" \) -a \( -z "${SDK_GO_1_5}" \) ]; then go get github.com/golang/lint/golint; else echo "skipped getting golint"; fi - -bench: - @echo "go bench SDK packages" - @go test -run NONE -bench . -benchmem -tags 'bench' $(SDK_ONLY_PKGS) - -bench-protocol: - @echo "go bench SDK protocol marshallers" - @go test -run NONE -bench . -benchmem -tags 'bench' ./private/protocol/... - -docs: - @echo "generate SDK docs" - @# This env variable, DOCS, is for internal use - @if [ -z ${AWS_DOC_GEN_TOOL} ]; then\ - rm -rf doc && bundle install && bundle exec yard;\ - else\ - $(AWS_DOC_GEN_TOOL) `pwd`;\ - fi - -api_info: - @go run private/model/cli/api-info/api-info.go diff --git a/vendor/github.com/aws/aws-sdk-go/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go/NOTICE.txt deleted file mode 100644 index 5f14d1162e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/NOTICE.txt +++ /dev/null @@ -1,3 +0,0 @@ -AWS SDK for Go -Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. -Copyright 2014-2015 Stripe, Inc. diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md deleted file mode 100644 index 559697f66b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/README.md +++ /dev/null @@ -1,449 +0,0 @@ -[![API Reference](http://img.shields.io/badge/api-reference-blue.svg)](http://docs.aws.amazon.com/sdk-for-go/api) [![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) [![Apache V2 License](http://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - -# AWS SDK for Go - -aws-sdk-go is the official AWS SDK for the Go programming language. - -Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for information about the latest bug fixes, updates, and features added to the SDK. - -## Installing - -If you are using Go 1.5 with the `GO15VENDOREXPERIMENT=1` vendoring flag, or 1.6 and higher you can use the following command to retrieve the SDK. The SDK's non-testing dependencies will be included and are vendored in the `vendor` folder. - - go get -u github.com/aws/aws-sdk-go - -Otherwise if your Go environment does not have vendoring support enabled, or you do not want to include the vendored SDK's dependencies you can use the following command to retrieve the SDK and its non-testing dependencies using `go get`. - - go get -u github.com/aws/aws-sdk-go/aws/... - go get -u github.com/aws/aws-sdk-go/service/... - -If you're looking to retrieve just the SDK without any dependencies use the following command. - - go get -d github.com/aws/aws-sdk-go/ - -These two processes will still include the `vendor` folder and it should be deleted if its not going to be used by your environment. - - rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor - -## Getting Help - -Please use these community resources for getting help. We use the GitHub issues for tracking bugs and feature requests. - -* Ask a question on [StackOverflow](http://stackoverflow.com/) and tag it with the [`aws-sdk-go`](http://stackoverflow.com/questions/tagged/aws-sdk-go) tag. -* Come join the AWS SDK for Go community chat on [gitter](https://gitter.im/aws/aws-sdk-go). -* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). -* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-sdk-go/issues/new). - -## Opening Issues - -If you encounter a bug with the AWS SDK for Go we would like to hear about it. Search the [existing issues](https://github.com/aws/aws-sdk-go/issues) and see if others are also experiencing the issue before opening a new issue. Please include the version of AWS SDK for Go, Go language, and OS you’re using. Please also include repro case when appropriate. - -The GitHub issues are intended for bug reports and feature requests. For help and questions with using AWS SDK for GO please make use of the resources listed in the [Getting Help](https://github.com/aws/aws-sdk-go#getting-help) section. Keeping the list of open issues lean will help us respond in a timely manner. - -## Reference Documentation - -[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document is a general introduction how to configure and make requests with the SDK. If this is your first time using the SDK, this documentation and the API documentation will help you get started. This document focuses on the syntax and behavior of the SDK. The [Service Developer Guide](https://aws.amazon.com/documentation/) will help you get started using specific AWS services. - -[`SDK API Reference Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this document to look up all API operation input and output parameters for AWS services supported by the SDK. The API reference also includes documentation of the SDK, and examples how to using the SDK, service client API operations, and API operation require parameters. - -[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this documentation to learn how to interface with an AWS service. These are great guides both, if you're getting started with a service, or looking for more information on a service. You should not need this document for coding, though in some cases, services may supply helpful samples that you might want to look out for. - -[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - Included in the SDK's repo are a several hand crafted examples using the SDK features and AWS services. - -## Overview of SDK's Packages - -The SDK is composed of two main components, SDK core, and service clients. -The SDK core packages are all available under the aws package at the root of -the SDK. Each client for a supported AWS service is available within its own -package under the service folder at the root of the SDK. - - * aws - SDK core, provides common shared types such as Config, Logger, - and utilities to make working with API parameters easier. - - * awserr - Provides the error interface that the SDK will use for all - errors that occur in the SDK's processing. This includes service API - response errors as well. The Error type is made up of a code and message. - Cast the SDK's returned error type to awserr.Error and call the Code - method to compare returned error to specific error codes. See the package's - documentation for additional values that can be extracted such as RequestID. - - * credentials - Provides the types and built in credentials providers - the SDK will use to retrieve AWS credentials to make API requests with. - Nested under this folder are also additional credentials providers such as - stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. - - * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. - Use this to lookup AWS service endpoint information such as which services - are in a region, and what regions a service is in. Constants are also provided - for all region identifiers, e.g UsWest2RegionID for "us-west-2". - - * session - Provides initial default configuration, and load - configuration from external sources such as environment and shared - credentials file. - - * request - Provides the API request sending, and retry logic for the SDK. - This package also includes utilities for defining your own request - retryer, and configuring how the SDK processes the request. - - * service - Clients for AWS services. All services supported by the SDK are - available under this folder. - -## How to Use the SDK's AWS Service Clients - -The SDK includes the Go types and utilities you can use to make requests to -AWS service APIs. Within the service folder at the root of the SDK you'll find -a package for each AWS service the SDK supports. All service clients follows -a common pattern of creation and usage. - -When creating a client for an AWS service you'll first need to have a Session -value constructed. The Session provides shared configuration that can be shared -between your service clients. When service clients are created you can pass -in additional configuration via the aws.Config type to override configuration -provided by in the Session to create service client instances with custom -configuration. - -Once the service's client is created you can use it to make API requests the -AWS service. These clients are safe to use concurrently. - -## Configuring the SDK - -In the AWS SDK for Go, you can configure settings for service clients, such -as the log level and maximum number of retries. Most settings are optional; -however, for each service client, you must specify a region and your credentials. -The SDK uses these values to send requests to the correct AWS region and sign -requests with the correct credentials. You can specify these values as part -of a session or as environment variables. - -See the SDK's [configuration guide][config_guide] for more information. - -See the [session][session_pkg] package documentation for more information on how to use Session -with the SDK. - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information on configuration -options. - -[config_guide]: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -[session_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -[config_typ]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -[aws_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/ - -### Configuring Credentials - -When using the SDK you'll generally need your AWS credentials to authenticate -with AWS services. The SDK supports multiple methods of supporting these -credentials. By default the SDK will source credentials automatically from -its default credential chain. See the session package for more information -on this chain, and how to configure it. The common items in the credential -chain are the following: - - * Environment Credentials - Set of environment variables that are useful - when sub processes are created for specific roles. - - * Shared Credentials file (~/.aws/credentials) - This file stores your - credentials based on a profile name and is useful for local development. - - * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials - to application running on an EC2 instance. This removes the need to manage - credential files in production. - -Credentials can be configured in code as well by setting the Config's Credentials -value to a custom provider or using one of the providers included with the -SDK to bypass the default credential chain and use a custom one. This is -helpful when you want to instruct the SDK to only use a specific set of -credentials or providers. - -This example creates a credential provider for assuming an IAM role, "myRoleARN" -and configures the S3 service client to use that role for API requests. - -```go - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds})/ -``` - -See the [credentials][credentials_pkg] package documentation for more information on credential -providers included with the SDK, and how to customize the SDK's usage of -credentials. - -The SDK has support for the shared configuration file (~/.aws/config). This -support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -or enabling the feature in code when creating a Session via the -Option's SharedConfigState parameter. - -```go - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) -``` - -[credentials_pkg]: ttps://docs.aws.amazon.com/sdk-for-go/api/aws/credentials - -### Configuring AWS Region - -In addition to the credentials you'll need to specify the region the SDK -will use to make AWS API requests to. In the SDK you can specify the region -either with an environment variable, or directly in code when a Session or -service client is created. The last value specified in code wins if the region -is specified multiple ways. - -To set the region via the environment variable set the "AWS_REGION" to the -region you want to the SDK to use. Using this method to set the region will -allow you to run your application in multiple regions without needing additional -code in the application to select the region. - - AWS_REGION=us-west-2 - -The endpoints package includes constants for all regions the SDK knows. The -values are all suffixed with RegionID. These values are helpful, because they -reduce the need to type the region string manually. - -To set the region on a Session use the aws package's Config struct parameter -Region to the AWS region you want the service clients created from the session to -use. This is helpful when you want to create multiple service clients, and -all of the clients make API requests to the same region. - -```go - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - })) -``` - -See the [endpoints][endpoints_pkg] package for the AWS Regions and Endpoints metadata. - -In addition to setting the region when creating a Session you can also set -the region on a per service client bases. This overrides the region of a -Session. This is helpful when you want to create service clients in specific -regions different from the Session's region. - -```go - svc := s3.New(sess, &aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - }) -``` - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information and additional -options such as setting the Endpoint, and other service client configuration options. - -[endpoints_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ - -## Making API Requests - -Once the client is created you can make an API request to the service. -Each API method takes a input parameter, and returns the service response -and an error. The SDK provides methods for making the API call in multiple ways. - -In this list we'll use the S3 ListObjects API as an example for the different -ways of making API requests. - - * ListObjects - Base API operation that will make the API request to the service. - - * ListObjectsRequest - API methods suffixed with Request will construct the - API request, but not send it. This is also helpful when you want to get a - presigned URL for a request, and share the presigned URL instead of your - application making the request directly. - - * ListObjectsPages - Same as the base API operation, but uses a callback to - automatically handle pagination of the API's response. - - * ListObjectsWithContext - Same as base API operation, but adds support for - the Context pattern. This is helpful for controlling the canceling of in - flight requests. See the Go standard library context package for more - information. This method also takes request package's Option functional - options as the variadic argument for modifying how the request will be - made, or extracting information from the raw HTTP response. - - * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for - the Context pattern. Similar to ListObjectsWithContext this method also - takes the request package's Option function option types as the variadic - argument. - -In addition to the API operations the SDK also includes several higher level -methods that abstract checking for and waiting for an AWS resource to be in -a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -the different forms of waiters. - - * WaitUntilBucketExists. - Method to make API request to query an AWS service for - a resource's state. Will return successfully when that state is accomplished. - - * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds - support for the Context pattern. In addition these methods take request - package's WaiterOptions to configure the waiter, and how underlying request - will be made by the SDK. - -The API method will document which error codes the service might return for -the operation. These errors will also be available as const strings prefixed -with "ErrCode" in the service client's package. If there are no errors listed -in the API's SDK documentation you'll need to consult the AWS service's API -documentation for the errors that could be returned. - -```go - ctx := context.Background() - - result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ - Bucket: aws.String("my-bucket"), - Key: aws.String("my-key"), - }) - if err != nil { - // Cast err to awserr.Error to handle specific error codes. - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == s3.ErrCodeNoSuchKey { - // Specific error code handling - } - return err - } - - // Make sure to close the body when done with it for S3 GetObject APIs or - // will leak connections. - defer result.Body.Close() - - fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -``` - -### API Request Pagination and Resource Waiters - -Pagination helper methods are suffixed with "Pages", and provide the -functionality needed to round trip API page requests. Pagination methods -take a callback function that will be called for each page of the API's response. - -```go - objects := []string{} - err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ - Bucket: aws.String(myBucket), - }, func(p *s3.ListObjectsOutput, lastPage bool) bool { - for _, o := range p.Contents { - objects = append(objects, aws.StringValue(o.Key)) - } - return true // continue paging - }) - if err != nil { - panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) - } - - fmt.Println("Objects in bucket:", objects) -``` - -Waiter helper methods provide the functionality to wait for an AWS resource -state. These methods abstract the logic needed to to check the state of an -AWS resource, and wait until that resource is in a desired state. The waiter -will block until the resource is in the state that is desired, an error occurs, -or the waiter times out. If a resource times out the error code returned will -be request.WaiterResourceNotReadyErrorCode. - -```go - err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ - Bucket: aws.String(myBucket), - }) - if err != nil { - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { - fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") - } - panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) - } - fmt.Println("Bucket", myBucket, "exists") -``` - -## Complete SDK Example - -This example shows a complete working Go file which will upload a file to S3 -and use the Context pattern to implement timeout logic that will cancel the -request if it takes too long. This example highlights how to use sessions, -create a service client, make a request, handle the error, and process the -response. - -```go - package main - - import ( - "context" - "flag" - "fmt" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - ) - - // Uploads a file to S3 given a bucket and object key. Also takes a duration - // value to terminate the update if it doesn't complete within that time. - // - // The AWS Region needs to be provided in the AWS shared config or on the - // environment variable as `AWS_REGION`. Credentials also must be provided - // Will default to shared config file, but can load from environment if provided. - // - // Usage: - // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail - // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt - func main() { - var bucket, key string - var timeout time.Duration - - flag.StringVar(&bucket, "b", "", "Bucket name.") - flag.StringVar(&key, "k", "", "Object key name.") - flag.DurationVar(&timeout, "d", 0, "Upload timeout.") - flag.Parse() - - // All clients require a Session. The Session provides the client with - // shared configuration such as region, endpoint, and credentials. A - // Session should be shared where possible to take advantage of - // configuration and credential caching. See the session package for - // more information. - sess := session.Must(session.NewSession()) - - // Create a new instance of the service's client with a Session. - // Optional aws.Config values can also be provided as variadic arguments - // to the New function. This option allows you to provide service - // specific configuration. - svc := s3.New(sess) - - // Create a context with a timeout that will abort the upload if it takes - // more than the passed in timeout. - ctx := context.Background() - var cancelFn func() - if timeout > 0 { - ctx, cancelFn = context.WithTimeout(ctx, timeout) - } - // Ensure the context is canceled to prevent leaking. - // See context package for more information, https://golang.org/pkg/context/ - defer cancelFn() - - // Uploads the object to S3. The Context will interrupt the request if the - // timeout expires. - _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(key), - Body: os.Stdin, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { - // If the SDK can determine the request or retry delay was canceled - // by a context the CanceledErrorCode error code will be returned. - fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) - } else { - fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) - } - os.Exit(1) - } - - fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) - } -``` - -## License - -This SDK is distributed under the -[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), -see LICENSE.txt and NOTICE.txt for more information. diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go deleted file mode 100644 index 56fdfc2bfc..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go +++ /dev/null @@ -1,145 +0,0 @@ -// Package awserr represents API error interface accessors for the SDK. -package awserr - -// An Error wraps lower level errors with code, message and an original error. -// The underlying concrete error type may also satisfy other interfaces which -// can be to used to obtain more specific information about the error. -// -// Calling Error() or String() will always include the full information about -// an error based on its underlying type. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Get error details -// log.Println("Error:", awsErr.Code(), awsErr.Message()) -// -// // Prints out full error message, including original error if there was one. -// log.Println("Error:", awsErr.Error()) -// -// // Get original error -// if origErr := awsErr.OrigErr(); origErr != nil { -// // operate on original error. -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type Error interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErr() error -} - -// BatchError is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Deprecated: Replaced with BatchedErrors. Only defined for backwards -// compatibility. -type BatchError interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// BatchedErrors is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Replaces BatchError -type BatchedErrors interface { - // Satisfy the base Error interface. - Error - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// New returns an Error object described by the code, message, and origErr. -// -// If origErr satisfies the Error interface it will not be wrapped within a new -// Error object and will instead be returned. -func New(code, message string, origErr error) Error { - var errs []error - if origErr != nil { - errs = append(errs, origErr) - } - return newBaseError(code, message, errs) -} - -// NewBatchError returns an BatchedErrors with a collection of errors as an -// array of errors. -func NewBatchError(code, message string, errs []error) BatchedErrors { - return newBaseError(code, message, errs) -} - -// A RequestFailure is an interface to extract request failure information from -// an Error such as the request ID of the failed request returned by a service. -// RequestFailures may not always have a requestID value if the request failed -// prior to reaching the service such as a connection error. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if reqerr, ok := err.(RequestFailure); ok { -// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) -// } else { -// log.Println("Error:", err.Error()) -// } -// } -// -// Combined with awserr.Error: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Generic AWS Error with Code, Message, and original error (if any) -// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) -// -// if reqErr, ok := err.(awserr.RequestFailure); ok { -// // A service error occurred -// fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type RequestFailure interface { - Error - - // The status code of the HTTP response. - StatusCode() int - - // The request ID returned by the service for a request failure. This will - // be empty if no request ID is available such as the request failed due - // to a connection error. - RequestID() string -} - -// NewRequestFailure returns a new request error wrapper for the given Error -// provided. -func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { - return newRequestError(err, statusCode, reqID) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go deleted file mode 100644 index 0202a008f5..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go +++ /dev/null @@ -1,194 +0,0 @@ -package awserr - -import "fmt" - -// SprintError returns a string of the formatted error code. -// -// Both extra and origErr are optional. If they are included their lines -// will be added, but if they are not included their lines will be ignored. -func SprintError(code, message, extra string, origErr error) string { - msg := fmt.Sprintf("%s: %s", code, message) - if extra != "" { - msg = fmt.Sprintf("%s\n\t%s", msg, extra) - } - if origErr != nil { - msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) - } - return msg -} - -// A baseError wraps the code and message which defines an error. It also -// can be used to wrap an original error object. -// -// Should be used as the root for errors satisfying the awserr.Error. Also -// for any error which does not fit into a specific error wrapper type. -type baseError struct { - // Classification of error - code string - - // Detailed information about error - message string - - // Optional original error this error is based off of. Allows building - // chained errors. - errs []error -} - -// newBaseError returns an error object for the code, message, and errors. -// -// code is a short no whitespace phrase depicting the classification of -// the error that is being created. -// -// message is the free flow string containing detailed information about the -// error. -// -// origErrs is the error objects which will be nested under the new errors to -// be returned. -func newBaseError(code, message string, origErrs []error) *baseError { - b := &baseError{ - code: code, - message: message, - errs: origErrs, - } - - return b -} - -// Error returns the string representation of the error. -// -// See ErrorWithExtra for formatting. -// -// Satisfies the error interface. -func (b baseError) Error() string { - size := len(b.errs) - if size > 0 { - return SprintError(b.code, b.message, "", errorList(b.errs)) - } - - return SprintError(b.code, b.message, "", nil) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (b baseError) String() string { - return b.Error() -} - -// Code returns the short phrase depicting the classification of the error. -func (b baseError) Code() string { - return b.code -} - -// Message returns the error details message. -func (b baseError) Message() string { - return b.message -} - -// OrigErr returns the original error if one was set. Nil is returned if no -// error was set. This only returns the first element in the list. If the full -// list is needed, use BatchedErrors. -func (b baseError) OrigErr() error { - switch len(b.errs) { - case 0: - return nil - case 1: - return b.errs[0] - default: - if err, ok := b.errs[0].(Error); ok { - return NewBatchError(err.Code(), err.Message(), b.errs[1:]) - } - return NewBatchError("BatchedErrors", - "multiple errors occurred", b.errs) - } -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (b baseError) OrigErrs() []error { - return b.errs -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError Error - -// A requestError wraps a request or service error. -// -// Composed of baseError for code, message, and original error. -type requestError struct { - awsError - statusCode int - requestID string -} - -// newRequestError returns a wrapped error with additional information for -// request status code, and service requestID. -// -// Should be used to wrap all request which involve service requests. Even if -// the request failed without a service response, but had an HTTP status code -// that may be meaningful. -// -// Also wraps original errors via the baseError. -func newRequestError(err Error, statusCode int, requestID string) *requestError { - return &requestError{ - awsError: err, - statusCode: statusCode, - requestID: requestID, - } -} - -// Error returns the string representation of the error. -// Satisfies the error interface. -func (r requestError) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s", - r.statusCode, r.requestID) - return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (r requestError) String() string { - return r.Error() -} - -// StatusCode returns the wrapped status code for the error -func (r requestError) StatusCode() int { - return r.statusCode -} - -// RequestID returns the wrapped requestID -func (r requestError) RequestID() string { - return r.requestID -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (r requestError) OrigErrs() []error { - if b, ok := r.awsError.(BatchedErrors); ok { - return b.OrigErrs() - } - return []error{r.OrigErr()} -} - -// An error list that satisfies the golang interface -type errorList []error - -// Error returns the string representation of the error. -// -// Satisfies the error interface. -func (e errorList) Error() string { - msg := "" - // How do we want to handle the array size being zero - if size := len(e); size > 0 { - for i := 0; i < size; i++ { - msg += fmt.Sprintf("%s", e[i].Error()) - // We check the next index to see if it is within the slice. - // If it is, then we append a newline. We do this, because unit tests - // could be broken with the additional '\n' - if i+1 < size { - msg += "\n" - } - } - } - return msg -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go deleted file mode 100644 index 1a3d106d5c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go +++ /dev/null @@ -1,108 +0,0 @@ -package awsutil - -import ( - "io" - "reflect" - "time" -) - -// Copy deeply copies a src structure to dst. Useful for copying request and -// response structures. -// -// Can copy between structs of different type, but will only copy fields which -// are assignable, and exist in both structs. Fields which are not assignable, -// or do not exist in both structs are ignored. -func Copy(dst, src interface{}) { - dstval := reflect.ValueOf(dst) - if !dstval.IsValid() { - panic("Copy dst cannot be nil") - } - - rcopy(dstval, reflect.ValueOf(src), true) -} - -// CopyOf returns a copy of src while also allocating the memory for dst. -// src must be a pointer type or this operation will fail. -func CopyOf(src interface{}) (dst interface{}) { - dsti := reflect.New(reflect.TypeOf(src).Elem()) - dst = dsti.Interface() - rcopy(dsti, reflect.ValueOf(src), true) - return -} - -// rcopy performs a recursive copy of values from the source to destination. -// -// root is used to skip certain aspects of the copy which are not valid -// for the root node of a object. -func rcopy(dst, src reflect.Value, root bool) { - if !src.IsValid() { - return - } - - switch src.Kind() { - case reflect.Ptr: - if _, ok := src.Interface().(io.Reader); ok { - if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { - dst.Elem().Set(src) - } else if dst.CanSet() { - dst.Set(src) - } - } else { - e := src.Type().Elem() - if dst.CanSet() && !src.IsNil() { - if _, ok := src.Interface().(*time.Time); !ok { - dst.Set(reflect.New(e)) - } else { - tempValue := reflect.New(e) - tempValue.Elem().Set(src.Elem()) - // Sets time.Time's unexported values - dst.Set(tempValue) - } - } - if src.Elem().IsValid() { - // Keep the current root state since the depth hasn't changed - rcopy(dst.Elem(), src.Elem(), root) - } - } - case reflect.Struct: - t := dst.Type() - for i := 0; i < t.NumField(); i++ { - name := t.Field(i).Name - srcVal := src.FieldByName(name) - dstVal := dst.FieldByName(name) - if srcVal.IsValid() && dstVal.CanSet() { - rcopy(dstVal, srcVal, false) - } - } - case reflect.Slice: - if src.IsNil() { - break - } - - s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) - dst.Set(s) - for i := 0; i < src.Len(); i++ { - rcopy(dst.Index(i), src.Index(i), false) - } - case reflect.Map: - if src.IsNil() { - break - } - - s := reflect.MakeMap(src.Type()) - dst.Set(s) - for _, k := range src.MapKeys() { - v := src.MapIndex(k) - v2 := reflect.New(v.Type()).Elem() - rcopy(v2, v, false) - dst.SetMapIndex(k, v2) - } - default: - // Assign the value if possible. If its not assignable, the value would - // need to be converted and the impact of that may be unexpected, or is - // not compatible with the dst type. - if src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go deleted file mode 100644 index 59fa4a558a..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go +++ /dev/null @@ -1,27 +0,0 @@ -package awsutil - -import ( - "reflect" -) - -// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. -// In addition to this, this method will also dereference the input values if -// possible so the DeepEqual performed will not fail if one parameter is a -// pointer and the other is not. -// -// DeepEqual will not perform indirection of nested values of the input parameters. -func DeepEqual(a, b interface{}) bool { - ra := reflect.Indirect(reflect.ValueOf(a)) - rb := reflect.Indirect(reflect.ValueOf(b)) - - if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { - // If the elements are both nil, and of the same type the are equal - // If they are of different types they are not equal - return reflect.TypeOf(a) == reflect.TypeOf(b) - } else if raValid != rbValid { - // Both values must be valid to be equal - return false - } - - return reflect.DeepEqual(ra.Interface(), rb.Interface()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go deleted file mode 100644 index 11c52c3896..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go +++ /dev/null @@ -1,222 +0,0 @@ -package awsutil - -import ( - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/jmespath/go-jmespath" -) - -var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) - -// rValuesAtPath returns a slice of values found in value v. The values -// in v are explored recursively so all nested values are collected. -func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { - pathparts := strings.Split(path, "||") - if len(pathparts) > 1 { - for _, pathpart := range pathparts { - vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) - if len(vals) > 0 { - return vals - } - } - return nil - } - - values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} - components := strings.Split(path, ".") - for len(values) > 0 && len(components) > 0 { - var index *int64 - var indexStar bool - c := strings.TrimSpace(components[0]) - if c == "" { // no actual component, illegal syntax - return nil - } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { - // TODO normalize case for user - return nil // don't support unexported fields - } - - // parse this component - if m := indexRe.FindStringSubmatch(c); m != nil { - c = m[1] - if m[2] == "" { - index = nil - indexStar = true - } else { - i, _ := strconv.ParseInt(m[2], 10, 32) - index = &i - indexStar = false - } - } - - nextvals := []reflect.Value{} - for _, value := range values { - // pull component name out of struct member - if value.Kind() != reflect.Struct { - continue - } - - if c == "*" { // pull all members - for i := 0; i < value.NumField(); i++ { - if f := reflect.Indirect(value.Field(i)); f.IsValid() { - nextvals = append(nextvals, f) - } - } - continue - } - - value = value.FieldByNameFunc(func(name string) bool { - if c == name { - return true - } else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) { - return true - } - return false - }) - - if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { - if !value.IsNil() { - value.Set(reflect.Zero(value.Type())) - } - return []reflect.Value{value} - } - - if createPath && value.Kind() == reflect.Ptr && value.IsNil() { - // TODO if the value is the terminus it should not be created - // if the value to be set to its position is nil. - value.Set(reflect.New(value.Type().Elem())) - value = value.Elem() - } else { - value = reflect.Indirect(value) - } - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - - if indexStar || index != nil { - nextvals = []reflect.Value{} - for _, valItem := range values { - value := reflect.Indirect(valItem) - if value.Kind() != reflect.Slice { - continue - } - - if indexStar { // grab all indices - for i := 0; i < value.Len(); i++ { - idx := reflect.Indirect(value.Index(i)) - if idx.IsValid() { - nextvals = append(nextvals, idx) - } - } - continue - } - - // pull out index - i := int(*index) - if i >= value.Len() { // check out of bounds - if createPath { - // TODO resize slice - } else { - continue - } - } else if i < 0 { // support negative indexing - i = value.Len() + i - } - value = reflect.Indirect(value.Index(i)) - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - } - - components = components[1:] - } - return values -} - -// ValuesAtPath returns a list of values at the case insensitive lexical -// path inside of a structure. -func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { - result, err := jmespath.Search(path, i) - if err != nil { - return nil, err - } - - v := reflect.ValueOf(result) - if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { - return nil, nil - } - if s, ok := result.([]interface{}); ok { - return s, err - } - if v.Kind() == reflect.Map && v.Len() == 0 { - return nil, nil - } - if v.Kind() == reflect.Slice { - out := make([]interface{}, v.Len()) - for i := 0; i < v.Len(); i++ { - out[i] = v.Index(i).Interface() - } - return out, nil - } - - return []interface{}{result}, nil -} - -// SetValueAtPath sets a value at the case insensitive lexical path inside -// of a structure. -func SetValueAtPath(i interface{}, path string, v interface{}) { - if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil { - for _, rval := range rvals { - if rval.Kind() == reflect.Ptr && rval.IsNil() { - continue - } - setValue(rval, v) - } - } -} - -func setValue(dstVal reflect.Value, src interface{}) { - if dstVal.Kind() == reflect.Ptr { - dstVal = reflect.Indirect(dstVal) - } - srcVal := reflect.ValueOf(src) - - if !srcVal.IsValid() { // src is literal nil - if dstVal.CanAddr() { - // Convert to pointer so that pointer's value can be nil'ed - // dstVal = dstVal.Addr() - } - dstVal.Set(reflect.Zero(dstVal.Type())) - - } else if srcVal.Kind() == reflect.Ptr { - if srcVal.IsNil() { - srcVal = reflect.Zero(dstVal.Type()) - } else { - srcVal = reflect.ValueOf(src).Elem() - } - dstVal.Set(srcVal) - } else { - dstVal.Set(srcVal) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go deleted file mode 100644 index 710eb432f8..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go +++ /dev/null @@ -1,113 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" -) - -// Prettify returns the string representation of a value. -func Prettify(i interface{}) string { - var buf bytes.Buffer - prettify(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -// prettify will recursively walk value v to build a textual -// representation of the value. -func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - prettify(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - strtype := v.Type().String() - if strtype == "[]uint8" { - fmt.Fprintf(buf, " len %d", v.Len()) - break - } - - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - prettify(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - prettify(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - if !v.IsValid() { - fmt.Fprint(buf, "") - return - } - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - case io.ReadSeeker, io.Reader: - format = "buffer(%p)" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go deleted file mode 100644 index b6432f1a11..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go +++ /dev/null @@ -1,89 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "reflect" - "strings" -) - -// StringValue returns the string representation of a value. -func StringValue(i interface{}) string { - var buf bytes.Buffer - stringValue(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - stringValue(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - stringValue(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - stringValue(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go deleted file mode 100644 index 788fe6e279..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ /dev/null @@ -1,90 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides configuration to a service client instance. -type Config struct { - Config *aws.Config - Handlers request.Handlers - Endpoint string - SigningRegion string - SigningName string -} - -// ConfigProvider provides a generic way for a service client to receive -// the ClientConfig without circular dependencies. -type ConfigProvider interface { - ClientConfig(serviceName string, cfgs ...*aws.Config) Config -} - -// ConfigNoResolveEndpointProvider same as ConfigProvider except it will not -// resolve the endpoint automatically. The service client's endpoint must be -// provided via the aws.Config.Endpoint field. -type ConfigNoResolveEndpointProvider interface { - ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config -} - -// A Client implements the base client request and response handling -// used by all service clients. -type Client struct { - request.Retryer - metadata.ClientInfo - - Config aws.Config - Handlers request.Handlers -} - -// New will return a pointer to a new initialized service client. -func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client { - svc := &Client{ - Config: cfg, - ClientInfo: info, - Handlers: handlers.Copy(), - } - - switch retryer, ok := cfg.Retryer.(request.Retryer); { - case ok: - svc.Retryer = retryer - case cfg.Retryer != nil && cfg.Logger != nil: - s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer) - cfg.Logger.Log(s) - fallthrough - default: - maxRetries := aws.IntValue(cfg.MaxRetries) - if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { - maxRetries = 3 - } - svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries} - } - - svc.AddDebugHandlers() - - for _, option := range options { - option(svc) - } - - return svc -} - -// NewRequest returns a new Request pointer for the service API -// operation and parameters. -func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { - return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data) -} - -// AddDebugHandlers injects debug logging handlers into the service to log request -// debug information. -func (c *Client) AddDebugHandlers() { - if !c.Config.LogLevel.AtLeast(aws.LogDebug) { - return - } - - c.Handlers.Send.PushFrontNamed(request.NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) - c.Handlers.Send.PushBackNamed(request.NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go deleted file mode 100644 index e25a460fba..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ /dev/null @@ -1,96 +0,0 @@ -package client - -import ( - "math/rand" - "sync" - "time" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// DefaultRetryer implements basic retry logic using exponential backoff for -// most services. If you want to implement custom retry logic, implement the -// request.Retryer interface or create a structure type that composes this -// struct and override the specific methods. For example, to override only -// the MaxRetries method: -// -// type retryer struct { -// client.DefaultRetryer -// } -// -// // This implementation always has 100 max retries -// func (d retryer) MaxRetries() int { return 100 } -type DefaultRetryer struct { - NumMaxRetries int -} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API request. -func (d DefaultRetryer) MaxRetries() int { - return d.NumMaxRetries -} - -var seededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) - -// RetryRules returns the delay duration before retrying this request again -func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { - // Set the upper limit of delay in retrying at ~five minutes - minTime := 30 - throttle := d.shouldThrottle(r) - if throttle { - minTime = 500 - } - - retryCount := r.RetryCount - if retryCount > 13 { - retryCount = 13 - } else if throttle && retryCount > 8 { - retryCount = 8 - } - - delay := (1 << uint(retryCount)) * (seededRand.Intn(minTime) + minTime) - return time.Duration(delay) * time.Millisecond -} - -// ShouldRetry returns true if the request should be retried. -func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable != nil { - return *r.Retryable - } - - if r.HTTPResponse.StatusCode >= 500 { - return true - } - return r.IsErrorRetryable() || d.shouldThrottle(r) -} - -// ShouldThrottle returns true if the request should be throttled. -func (d DefaultRetryer) shouldThrottle(r *request.Request) bool { - if r.HTTPResponse.StatusCode == 502 || - r.HTTPResponse.StatusCode == 503 || - r.HTTPResponse.StatusCode == 504 { - return true - } - return r.IsErrorThrottle() -} - -// lockedSource is a thread-safe implementation of rand.Source -type lockedSource struct { - lk sync.Mutex - src rand.Source -} - -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() - return -} - -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go deleted file mode 100644 index 1f39c91f2e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ /dev/null @@ -1,108 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http/httputil" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -const logReqMsg = `DEBUG: Request %s/%s Details: ----[ REQUEST POST-SIGN ]----------------------------- -%s ------------------------------------------------------` - -const logReqErrMsg = `DEBUG ERROR: Request %s/%s: ----[ REQUEST DUMP ERROR ]----------------------------- -%s -------------------------------------------------------` - -type logWriter struct { - // Logger is what we will use to log the payload of a response. - Logger aws.Logger - // buf stores the contents of what has been read - buf *bytes.Buffer -} - -func (logger *logWriter) Write(b []byte) (int, error) { - return logger.buf.Write(b) -} - -type teeReaderCloser struct { - // io.Reader will be a tee reader that is used during logging. - // This structure will read from a body and write the contents to a logger. - io.Reader - // Source is used just to close when we are done reading. - Source io.ReadCloser -} - -func (reader *teeReaderCloser) Close() error { - return reader.Source.Close() -} - -func logRequest(r *request.Request) { - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - if logBody { - // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's - // Body as a NoOpCloser and will not be reset after read by the HTTP - // client reader. - r.ResetBody() - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody))) -} - -const logRespMsg = `DEBUG: Response %s/%s Details: ----[ RESPONSE ]-------------------------------------- -%s ------------------------------------------------------` - -const logRespErrMsg = `DEBUG ERROR: Response %s/%s: ----[ RESPONSE DUMP ERROR ]----------------------------- -%s ------------------------------------------------------` - -func logResponse(r *request.Request) { - lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, - } - - handlerFn := func(req *request.Request) { - body, err := httputil.DumpResponse(req.HTTPResponse, false) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - lw.Logger.Log(fmt.Sprintf(logRespMsg, req.ClientInfo.ServiceName, req.Operation.Name, string(body))) - if req.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { - lw.Logger.Log(string(b)) - } - } - - const handlerName = "awsdk.client.LogResponse.ResponseBody" - - r.Handlers.Unmarshal.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) - r.Handlers.UnmarshalError.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go deleted file mode 100644 index 4778056ddf..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go +++ /dev/null @@ -1,12 +0,0 @@ -package metadata - -// ClientInfo wraps immutable data from the client.Client structure. -type ClientInfo struct { - ServiceName string - APIVersion string - Endpoint string - SigningName string - SigningRegion string - JSONVersion string - TargetPrefix string -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go deleted file mode 100644 index ae3a286960..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ /dev/null @@ -1,470 +0,0 @@ -package aws - -import ( - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/endpoints" -) - -// UseServiceDefaultRetries instructs the config to use the service's own -// default number of retries. This will be the default action if -// Config.MaxRetries is nil also. -const UseServiceDefaultRetries = -1 - -// RequestRetryer is an alias for a type that implements the request.Retryer -// interface. -type RequestRetryer interface{} - -// A Config provides service configuration for service clients. By default, -// all clients will use the defaults.DefaultConfig tructure. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(&aws.Config{ -// MaxRetries: aws.Int(3), -// })) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String("us-west-2"), -// }) -type Config struct { - // Enables verbose error printing of all credential chain errors. - // Should be used when wanting to see all errors while attempting to - // retrieve credentials. - CredentialsChainVerboseErrors *bool - - // The credentials object to use when signing requests. Defaults to a - // chain of credential providers to search for credentials in environment - // variables, shared credential file, and EC2 Instance Roles. - Credentials *credentials.Credentials - - // An optional endpoint URL (hostname only or fully qualified URI) - // that overrides the default generated endpoint for a client. Set this - // to `""` to use the default generated endpoint. - // - // @note You must still provide a `Region` value when specifying an - // endpoint for a client. - Endpoint *string - - // The resolver to use for looking up endpoints for AWS service clients - // to use based on region. - EndpointResolver endpoints.Resolver - - // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call - // ShouldRetry regardless of whether or not if request.Retryable is set. - // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck - // is not set, then ShouldRetry will only be called if request.Retryable is nil. - // Proper handling of the request.Retryable field is important when setting this field. - EnforceShouldRetryCheck *bool - - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // @see http://docs.aws.amazon.com/general/latest/gr/rande.html - // AWS Regions and Endpoints - Region *string - - // Set this to `true` to disable SSL when sending requests. Defaults - // to `false`. - DisableSSL *bool - - // The HTTP client to use when sending requests. Defaults to - // `http.DefaultClient`. - HTTPClient *http.Client - - // An integer value representing the logging level. The default log level - // is zero (LogOff), which represents no logging. To enable logging set - // to a LogLevel Value. - LogLevel *LogLevelType - - // The logger writer interface to write logging messages to. Defaults to - // standard out. - Logger Logger - - // The maximum number of times that a request will be retried for failures. - // Defaults to -1, which defers the max retry setting to the service - // specific configuration. - MaxRetries *int - - // Retryer guides how HTTP requests should be retried in case of - // recoverable failures. - // - // When nil or the value does not implement the request.Retryer interface, - // the client.DefaultRetryer will be used. - // - // When both Retryer and MaxRetries are non-nil, the former is used and - // the latter ignored. - // - // To set the Retryer field in a type-safe manner and with chaining, use - // the request.WithRetryer helper function: - // - // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) - // - Retryer RequestRetryer - - // Disables semantic parameter validation, which validates input for - // missing required fields and/or other semantic request input errors. - DisableParamValidation *bool - - // Disables the computation of request and response checksums, e.g., - // CRC32 checksums in Amazon DynamoDB. - DisableComputeChecksums *bool - - // Set this to `true` to force the request to use path-style addressing, - // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client - // will use virtual hosted bucket addressing when possible - // (`http://BUCKET.s3.amazonaws.com/KEY`). - // - // @note This configuration option is specific to the Amazon S3 service. - // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // Amazon S3: Virtual Hosting of Buckets - S3ForcePathStyle *bool - - // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` - // header to PUT requests over 2MB of content. 100-Continue instructs the - // HTTP client not to send the body until the service responds with a - // `continue` status. This is useful to prevent sending the request body - // until after the request is authenticated, and validated. - // - // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html - // - // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s - // `ExpectContinueTimeout` for information on adjusting the continue wait - // timeout. https://golang.org/pkg/net/http/#Transport - // - // You should use this flag to disble 100-Continue if you experience issues - // with proxies or third party S3 compatible services. - S3Disable100Continue *bool - - // Set this to `true` to enable S3 Accelerate feature. For all operations - // compatible with S3 Accelerate will use the accelerate endpoint for - // requests. Requests not compatible will fall back to normal S3 requests. - // - // The bucket must be enable for accelerate to be used with S3 client with - // accelerate enabled. If the bucket is not enabled for accelerate an error - // will be returned. The bucket name must be DNS compatible to also work - // with accelerate. - S3UseAccelerate *bool - - // Set this to `true` to disable the EC2Metadata client from overriding the - // default http.Client's Timeout. This is helpful if you do not want the - // EC2Metadata client to create a new http.Client. This options is only - // meaningful if you're not already using a custom HTTP client with the - // SDK. Enabled by default. - // - // Must be set and provided to the session.NewSession() in order to disable - // the EC2Metadata overriding the timeout for default credentials chain. - // - // Example: - // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDiableTimeoutOverride(true))) - // - // svc := s3.New(sess) - // - EC2MetadataDisableTimeoutOverride *bool - - // Instructs the endpiont to be generated for a service client to - // be the dual stack endpoint. The dual stack endpoint will support - // both IPv4 and IPv6 addressing. - // - // Setting this for a service which does not support dual stack will fail - // to make requets. It is not recommended to set this value on the session - // as it will apply to all service clients created with the session. Even - // services which don't support dual stack endpoints. - // - // If the Endpoint config value is also provided the UseDualStack flag - // will be ignored. - // - // Only supported with. - // - // sess := session.Must(session.NewSession()) - // - // svc := s3.New(sess, &aws.Config{ - // UseDualStack: aws.Bool(true), - // }) - UseDualStack *bool - - // SleepDelay is an override for the func the SDK will call when sleeping - // during the lifecycle of a request. Specifically this will be used for - // request delays. This value should only be used for testing. To adjust - // the delay of a request see the aws/client.DefaultRetryer and - // aws/request.Retryer. - // - // SleepDelay will prevent any Context from being used for canceling retry - // delay of an API operation. It is recommended to not use SleepDelay at all - // and specify a Retryer instead. - SleepDelay func(time.Duration) - - // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. - // Will default to false. This would only be used for empty directory names in s3 requests. - // - // Example: - // sess := session.Must(session.NewSession(&aws.Config{ - // DisableRestProtocolURICleaning: aws.Bool(true), - // })) - // - // svc := s3.New(sess) - // out, err := svc.GetObject(&s3.GetObjectInput { - // Bucket: aws.String("bucketname"), - // Key: aws.String("//foo//bar//moo"), - // }) - DisableRestProtocolURICleaning *bool -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(aws.NewConfig(). -// WithMaxRetries(3), -// )) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, aws.NewConfig(). -// WithRegion("us-west-2"), -// ) -func NewConfig() *Config { - return &Config{} -} - -// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning -// a Config pointer. -func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config { - c.CredentialsChainVerboseErrors = &verboseErrs - return c -} - -// WithCredentials sets a config Credentials value returning a Config pointer -// for chaining. -func (c *Config) WithCredentials(creds *credentials.Credentials) *Config { - c.Credentials = creds - return c -} - -// WithEndpoint sets a config Endpoint value returning a Config pointer for -// chaining. -func (c *Config) WithEndpoint(endpoint string) *Config { - c.Endpoint = &endpoint - return c -} - -// WithEndpointResolver sets a config EndpointResolver value returning a -// Config pointer for chaining. -func (c *Config) WithEndpointResolver(resolver endpoints.Resolver) *Config { - c.EndpointResolver = resolver - return c -} - -// WithRegion sets a config Region value returning a Config pointer for -// chaining. -func (c *Config) WithRegion(region string) *Config { - c.Region = ®ion - return c -} - -// WithDisableSSL sets a config DisableSSL value returning a Config pointer -// for chaining. -func (c *Config) WithDisableSSL(disable bool) *Config { - c.DisableSSL = &disable - return c -} - -// WithHTTPClient sets a config HTTPClient value returning a Config pointer -// for chaining. -func (c *Config) WithHTTPClient(client *http.Client) *Config { - c.HTTPClient = client - return c -} - -// WithMaxRetries sets a config MaxRetries value returning a Config pointer -// for chaining. -func (c *Config) WithMaxRetries(max int) *Config { - c.MaxRetries = &max - return c -} - -// WithDisableParamValidation sets a config DisableParamValidation value -// returning a Config pointer for chaining. -func (c *Config) WithDisableParamValidation(disable bool) *Config { - c.DisableParamValidation = &disable - return c -} - -// WithDisableComputeChecksums sets a config DisableComputeChecksums value -// returning a Config pointer for chaining. -func (c *Config) WithDisableComputeChecksums(disable bool) *Config { - c.DisableComputeChecksums = &disable - return c -} - -// WithLogLevel sets a config LogLevel value returning a Config pointer for -// chaining. -func (c *Config) WithLogLevel(level LogLevelType) *Config { - c.LogLevel = &level - return c -} - -// WithLogger sets a config Logger value returning a Config pointer for -// chaining. -func (c *Config) WithLogger(logger Logger) *Config { - c.Logger = logger - return c -} - -// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config -// pointer for chaining. -func (c *Config) WithS3ForcePathStyle(force bool) *Config { - c.S3ForcePathStyle = &force - return c -} - -// WithS3Disable100Continue sets a config S3Disable100Continue value returning -// a Config pointer for chaining. -func (c *Config) WithS3Disable100Continue(disable bool) *Config { - c.S3Disable100Continue = &disable - return c -} - -// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config -// pointer for chaining. -func (c *Config) WithS3UseAccelerate(enable bool) *Config { - c.S3UseAccelerate = &enable - return c -} - -// WithUseDualStack sets a config UseDualStack value returning a Config -// pointer for chaining. -func (c *Config) WithUseDualStack(enable bool) *Config { - c.UseDualStack = &enable - return c -} - -// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value -// returning a Config pointer for chaining. -func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { - c.EC2MetadataDisableTimeoutOverride = &enable - return c -} - -// WithSleepDelay overrides the function used to sleep while waiting for the -// next retry. Defaults to time.Sleep. -func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { - c.SleepDelay = fn - return c -} - -// MergeIn merges the passed in configs into the existing config object. -func (c *Config) MergeIn(cfgs ...*Config) { - for _, other := range cfgs { - mergeInConfig(c, other) - } -} - -func mergeInConfig(dst *Config, other *Config) { - if other == nil { - return - } - - if other.CredentialsChainVerboseErrors != nil { - dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors - } - - if other.Credentials != nil { - dst.Credentials = other.Credentials - } - - if other.Endpoint != nil { - dst.Endpoint = other.Endpoint - } - - if other.EndpointResolver != nil { - dst.EndpointResolver = other.EndpointResolver - } - - if other.Region != nil { - dst.Region = other.Region - } - - if other.DisableSSL != nil { - dst.DisableSSL = other.DisableSSL - } - - if other.HTTPClient != nil { - dst.HTTPClient = other.HTTPClient - } - - if other.LogLevel != nil { - dst.LogLevel = other.LogLevel - } - - if other.Logger != nil { - dst.Logger = other.Logger - } - - if other.MaxRetries != nil { - dst.MaxRetries = other.MaxRetries - } - - if other.Retryer != nil { - dst.Retryer = other.Retryer - } - - if other.DisableParamValidation != nil { - dst.DisableParamValidation = other.DisableParamValidation - } - - if other.DisableComputeChecksums != nil { - dst.DisableComputeChecksums = other.DisableComputeChecksums - } - - if other.S3ForcePathStyle != nil { - dst.S3ForcePathStyle = other.S3ForcePathStyle - } - - if other.S3Disable100Continue != nil { - dst.S3Disable100Continue = other.S3Disable100Continue - } - - if other.S3UseAccelerate != nil { - dst.S3UseAccelerate = other.S3UseAccelerate - } - - if other.UseDualStack != nil { - dst.UseDualStack = other.UseDualStack - } - - if other.EC2MetadataDisableTimeoutOverride != nil { - dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride - } - - if other.SleepDelay != nil { - dst.SleepDelay = other.SleepDelay - } - - if other.DisableRestProtocolURICleaning != nil { - dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning - } - - if other.EnforceShouldRetryCheck != nil { - dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck - } -} - -// Copy will return a shallow copy of the Config object. If any additional -// configurations are provided they will be merged into the new config returned. -func (c *Config) Copy(cfgs ...*Config) *Config { - dst := &Config{} - dst.MergeIn(c) - - for _, cfg := range cfgs { - dst.MergeIn(cfg) - } - - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/aws/aws-sdk-go/aws/context.go deleted file mode 100644 index 79f426853b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context.go +++ /dev/null @@ -1,71 +0,0 @@ -package aws - -import ( - "time" -) - -// Context is an copy of the Go v1.7 stdlib's context.Context interface. -// It is represented as a SDK interface to enable you to use the "WithContext" -// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. -// -// See https://golang.org/pkg/context on how to use contexts. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - Value(key interface{}) interface{} -} - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return backgroundCtx -} - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// Expects Context to always return a non-nil error if the Done channel is closed. -func SleepWithContext(ctx Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go deleted file mode 100644 index e8cf93d269..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !go1.7 - -package aws - -import "time" - -// An emptyCtx is a copy of the the Go 1.7 context.emptyCtx type. This -// is copied to provide a 1.6 and 1.5 safe version of context that is compatible -// with Go 1.7's Context. -// -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case backgroundCtx: - return "aws.BackgroundContext" - } - return "unknown empty Context" -} - -var ( - backgroundCtx = new(emptyCtx) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go deleted file mode 100644 index 064f75c925..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.7 - -package aws - -import "context" - -var ( - backgroundCtx = context.Background() -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go deleted file mode 100644 index 3b73a7da7f..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go +++ /dev/null @@ -1,369 +0,0 @@ -package aws - -import "time" - -// String returns a pointer to the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float64 returns a pointer to the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". -// The result is undefined if the Unix time cannot be represented by an int64. -// Which includes calling TimeUnixMilli on a zero Time is undefined. -// -// This utility is useful for service API's such as CloudWatch Logs which require -// their unix time values to be in milliseconds. -// -// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. -func TimeUnixMilli(t time.Time) int64 { - return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go deleted file mode 100644 index 495e3ef62c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ /dev/null @@ -1,242 +0,0 @@ -package corehandlers - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "runtime" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// Interface for matching types which also have a Len method. -type lener interface { - Len() int -} - -// BuildContentLengthHandler builds the content length of a request based on the body, -// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable -// to determine request body length and no "Content-Length" was specified it will panic. -// -// The Content-Length will only be added to the request if the length of the body -// is greater than 0. If the body is empty or the current `Content-Length` -// header is <= 0, the header will also be stripped. -var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { - var length int64 - - if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { - length, _ = strconv.ParseInt(slength, 10, 64) - } else { - switch body := r.Body.(type) { - case nil: - length = 0 - case lener: - length = int64(body.Len()) - case io.Seeker: - r.BodyStart, _ = body.Seek(0, 1) - end, _ := body.Seek(0, 2) - body.Seek(r.BodyStart, 0) // make sure to seek back to original location - length = end - r.BodyStart - default: - panic("Cannot get length of body, must provide `ContentLength`") - } - } - - if length > 0 { - r.HTTPRequest.ContentLength = length - r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) - } else { - r.HTTPRequest.ContentLength = 0 - r.HTTPRequest.Header.Del("Content-Length") - } -}} - -// SDKVersionUserAgentHandler is a request handler for adding the SDK Version to the user agent. -var SDKVersionUserAgentHandler = request.NamedHandler{ - Name: "core.SDKVersionUserAgentHandler", - Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, - runtime.Version(), runtime.GOOS, runtime.GOARCH), -} - -var reStatusCode = regexp.MustCompile(`^(\d{3})`) - -// ValidateReqSigHandler is a request handler to ensure that the request's -// signature doesn't expire before it is sent. This can happen when a request -// is built and signed significantly before it is sent. Or significant delays -// occur when retrying requests that would cause the signature to expire. -var ValidateReqSigHandler = request.NamedHandler{ - Name: "core.ValidateReqSigHandler", - Fn: func(r *request.Request) { - // Unsigned requests are not signed - if r.Config.Credentials == credentials.AnonymousCredentials { - return - } - - signedTime := r.Time - if !r.LastSignedAt.IsZero() { - signedTime = r.LastSignedAt - } - - // 10 minutes to allow for some clock skew/delays in transmission. - // Would be improved with aws/aws-sdk-go#423 - if signedTime.Add(10 * time.Minute).After(time.Now()) { - return - } - - fmt.Println("request expired, resigning") - r.Sign() - }, -} - -// SendHandler is a request handler to send service request using HTTP client. -var SendHandler = request.NamedHandler{ - Name: "core.SendHandler", - Fn: func(r *request.Request) { - sender := sendFollowRedirects - if r.DisableFollowRedirects { - sender = sendWithoutFollowRedirects - } - - if request.NoBody == r.HTTPRequest.Body { - // Strip off the request body if the NoBody reader was used as a - // place holder for a request body. This prevents the SDK from - // making requests with a request body when it would be invalid - // to do so. - // - // Use a shallow copy of the http.Request to ensure the race condition - // of transport on Body will not trigger - reqOrig, reqCopy := r.HTTPRequest, *r.HTTPRequest - reqCopy.Body = nil - r.HTTPRequest = &reqCopy - defer func() { - r.HTTPRequest = reqOrig - }() - } - - var err error - r.HTTPResponse, err = sender(r) - if err != nil { - handleSendError(r, err) - } - }, -} - -func sendFollowRedirects(r *request.Request) (*http.Response, error) { - return r.Config.HTTPClient.Do(r.HTTPRequest) -} - -func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { - transport := r.Config.HTTPClient.Transport - if transport == nil { - transport = http.DefaultTransport - } - - return transport.RoundTrip(r.HTTPRequest) -} - -func handleSendError(r *request.Request, err error) { - // Prevent leaking if an HTTPResponse was returned. Clean up - // the body. - if r.HTTPResponse != nil { - r.HTTPResponse.Body.Close() - } - // Capture the case where url.Error is returned for error processing - // response. e.g. 301 without location header comes back as string - // error and r.HTTPResponse is nil. Other URL redirect errors will - // comeback in a similar method. - if e, ok := err.(*url.Error); ok && e.Err != nil { - if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { - code, _ := strconv.ParseInt(s[1], 10, 64) - r.HTTPResponse = &http.Response{ - StatusCode: int(code), - Status: http.StatusText(int(code)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - return - } - } - if r.HTTPResponse == nil { - // Add a dummy request response object to ensure the HTTPResponse - // value is consistent. - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - } - // Catch all other request errors. - r.Error = awserr.New("RequestError", "send request failed", err) - r.Retryable = aws.Bool(true) // network errors are retryable - - // Override the error with a context canceled error, if that was canceled. - ctx := r.Context() - select { - case <-ctx.Done(): - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", ctx.Err()) - r.Retryable = aws.Bool(false) - default: - } -} - -// ValidateResponseHandler is a request handler to validate service response. -var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { - if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { - // this may be replaced by an UnmarshalError handler - r.Error = awserr.New("UnknownError", "unknown error", nil) - } -}} - -// AfterRetryHandler performs final checks to determine if the request should -// be retried and how long to delay. -var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { - r.Retryable = aws.Bool(r.ShouldRetry(r)) - } - - if r.WillRetry() { - r.RetryDelay = r.RetryRules(r) - - if sleepFn := r.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(r.RetryDelay) - } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", err) - r.Retryable = aws.Bool(false) - return - } - - // when the expired token exception occurs the credentials - // need to be expired locally so that the next request to - // get credentials will trigger a credentials refresh. - if r.IsErrorExpired() { - r.Config.Credentials.Expire() - } - - r.RetryCount++ - r.Error = nil - } -}} - -// ValidateEndpointHandler is a request handler to validate a request had the -// appropriate Region and Endpoint set. Will set r.Error if the endpoint or -// region is not valid. -var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) { - if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { - r.Error = aws.ErrMissingRegion - } else if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go deleted file mode 100644 index 7d50b1557c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go +++ /dev/null @@ -1,17 +0,0 @@ -package corehandlers - -import "github.com/aws/aws-sdk-go/aws/request" - -// ValidateParametersHandler is a request handler to validate the input parameters. -// Validating parameters only has meaning if done prior to the request being sent. -var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) { - if !r.ParamsFilled() { - return - } - - if v, ok := r.Params.(request.Validator); ok { - if err := v.Validate(); err != nil { - r.Error = err - } - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go deleted file mode 100644 index f298d65962..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var ( - // ErrNoValidProvidersFoundInChain Is returned when there are no valid - // providers in the ChainProvider. - // - // This has been deprecated. For verbose error messaging set - // aws.Config.CredentialsChainVerboseErrors to true - // - // @readonly - ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", - `no valid providers in chain. Deprecated. - For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, - nil) -) - -// A ChainProvider will search for a provider which returns credentials -// and cache that provider until Retrieve is called again. -// -// The ChainProvider provides a way of chaining multiple providers together -// which will pick the first available using priority order of the Providers -// in the list. -// -// If none of the Providers retrieve valid credentials Value, ChainProvider's -// Retrieve() will return the error ErrNoValidProvidersFoundInChain. -// -// If a Provider is found which returns valid credentials Value ChainProvider -// will cache that Provider for all calls to IsExpired(), until Retrieve is -// called again. -// -// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. -// In this example EnvProvider will first check if any credentials are available -// via the environment variables. If there are none ChainProvider will check -// the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider -// does not return any credentials ChainProvider will return the error -// ErrNoValidProvidersFoundInChain -// -// creds := credentials.NewChainCredentials( -// []credentials.Provider{ -// &credentials.EnvProvider{}, -// &ec2rolecreds.EC2RoleProvider{ -// Client: ec2metadata.New(sess), -// }, -// }) -// -// // Usage of ChainCredentials with aws.Config -// svc := ec2.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: creds, -// }))) -// -type ChainProvider struct { - Providers []Provider - curr Provider - VerboseErrors bool -} - -// NewChainCredentials returns a pointer to a new Credentials object -// wrapping a chain of providers. -func NewChainCredentials(providers []Provider) *Credentials { - return NewCredentials(&ChainProvider{ - Providers: append([]Provider{}, providers...), - }) -} - -// Retrieve returns the credentials value or error if no provider returned -// without error. -// -// If a provider is found it will be cached and any calls to IsExpired() -// will return the expired state of the cached provider. -func (c *ChainProvider) Retrieve() (Value, error) { - var errs []error - for _, p := range c.Providers { - creds, err := p.Retrieve() - if err == nil { - c.curr = p - return creds, nil - } - errs = append(errs, err) - } - c.curr = nil - - var err error - err = ErrNoValidProvidersFoundInChain - if c.VerboseErrors { - err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) - } - return Value{}, err -} - -// IsExpired will returned the expired state of the currently cached provider -// if there is one. If there is no current provider, true will be returned. -func (c *ChainProvider) IsExpired() bool { - if c.curr != nil { - return c.curr.IsExpired() - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go deleted file mode 100644 index 42416fc2f0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ /dev/null @@ -1,246 +0,0 @@ -// Package credentials provides credential retrieval and management -// -// The Credentials is the primary method of getting access to and managing -// credentials Values. Using dependency injection retrieval of the credential -// values is handled by a object which satisfies the Provider interface. -// -// By default the Credentials.Get() will cache the successful result of a -// Provider's Retrieve() until Provider.IsExpired() returns true. At which -// point Credentials will call Provider's Retrieve() to get new credential Value. -// -// The Provider is responsible for determining when credentials Value have expired. -// It is also important to note that Credentials will always call Retrieve the -// first time Credentials.Get() is called. -// -// Example of using the environment variable credentials. -// -// creds := credentials.NewEnvCredentials() -// -// // Retrieve the credentials value -// credValue, err := creds.Get() -// if err != nil { -// // handle error -// } -// -// Example of forcing credentials to expire and be refreshed on the next Get(). -// This may be helpful to proactively expire credentials and refresh them sooner -// than they would naturally expire on their own. -// -// creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) -// creds.Expire() -// credsValue, err := creds.Get() -// // New credentials will be retrieved instead of from cache. -// -// -// Custom Provider -// -// Each Provider built into this package also provides a helper method to generate -// a Credentials pointer setup with the provider. To use a custom Provider just -// create a type which satisfies the Provider interface and pass it to the -// NewCredentials method. -// -// type MyProvider struct{} -// func (m *MyProvider) Retrieve() (Value, error) {...} -// func (m *MyProvider) IsExpired() bool {...} -// -// creds := credentials.NewCredentials(&MyProvider{}) -// credValue, err := creds.Get() -// -package credentials - -import ( - "sync" - "time" -) - -// AnonymousCredentials is an empty Credential object that can be used as -// dummy placeholder credentials for requests that do not need signed. -// -// This Credentials can be used to configure a service to not sign requests -// when making service API calls. For example, when accessing public -// s3 buckets. -// -// svc := s3.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: credentials.AnonymousCredentials, -// }))) -// // Access public S3 buckets. -// -// @readonly -var AnonymousCredentials = NewStaticCredentials("", "", "") - -// A Value is the AWS credentials value for individual credential fields. -type Value struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Provider used to get credentials - ProviderName string -} - -// A Provider is the interface for any component which will provide credentials -// Value. A provider is required to manage its own Expired state, and what to -// be expired means. -// -// The Provider should not need to implement its own mutexes, because -// that will be managed by Credentials. -type Provider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve() (Value, error) - - // IsExpired returns if the credentials are no longer valid, and need - // to be retrieved. - IsExpired() bool -} - -// An ErrorProvider is a stub credentials provider that always returns an error -// this is used by the SDK when construction a known provider is not possible -// due to an error. -type ErrorProvider struct { - // The error to be returned from Retrieve - Err error - - // The provider name to set on the Retrieved returned Value - ProviderName string -} - -// Retrieve will always return the error that the ErrorProvider was created with. -func (p ErrorProvider) Retrieve() (Value, error) { - return Value{ProviderName: p.ProviderName}, p.Err -} - -// IsExpired will always return not expired. -func (p ErrorProvider) IsExpired() bool { - return false -} - -// A Expiry provides shared expiration logic to be used by credentials -// providers to implement expiry functionality. -// -// The best method to use this struct is as an anonymous field within the -// provider's struct. -// -// Example: -// type EC2RoleProvider struct { -// Expiry -// ... -// } -type Expiry struct { - // The date/time when to expire on - expiration time.Time - - // If set will be used by IsExpired to determine the current time. - // Defaults to time.Now if CurrentTime is not set. Available for testing - // to be able to mock out the current time. - CurrentTime func() time.Time -} - -// SetExpiration sets the expiration IsExpired will check when called. -// -// If window is greater than 0 the expiration time will be reduced by the -// window value. -// -// Using a window is helpful to trigger credentials to expire sooner than -// the expiration time given to ensure no requests are made with expired -// tokens. -func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { - e.expiration = expiration - if window > 0 { - e.expiration = e.expiration.Add(-window) - } -} - -// IsExpired returns if the credentials are expired. -func (e *Expiry) IsExpired() bool { - if e.CurrentTime == nil { - e.CurrentTime = time.Now - } - return e.expiration.Before(e.CurrentTime()) -} - -// A Credentials provides synchronous safe retrieval of AWS credentials Value. -// Credentials will cache the credentials value until they expire. Once the value -// expires the next Get will attempt to retrieve valid credentials. -// -// Credentials is safe to use across multiple goroutines and will manage the -// synchronous state so the Providers do not need to implement their own -// synchronization. -// -// The first Credentials.Get() will always call Provider.Retrieve() to get the -// first instance of the credentials Value. All calls to Get() after that -// will return the cached credentials Value until IsExpired() returns true. -type Credentials struct { - creds Value - forceRefresh bool - m sync.Mutex - - provider Provider -} - -// NewCredentials returns a pointer to a new Credentials with the provider set. -func NewCredentials(provider Provider) *Credentials { - return &Credentials{ - provider: provider, - forceRefresh: true, - } -} - -// Get returns the credentials value, or error if the credentials Value failed -// to be retrieved. -// -// Will return the cached credentials Value if it has not expired. If the -// credentials Value has expired the Provider's Retrieve() will be called -// to refresh the credentials. -// -// If Credentials.Expire() was called the credentials Value will be force -// expired, and the next call to Get() will cause them to be refreshed. -func (c *Credentials) Get() (Value, error) { - c.m.Lock() - defer c.m.Unlock() - - if c.isExpired() { - creds, err := c.provider.Retrieve() - if err != nil { - return Value{}, err - } - c.creds = creds - c.forceRefresh = false - } - - return c.creds, nil -} - -// Expire expires the credentials and forces them to be retrieved on the -// next call to Get(). -// -// This will override the Provider's expired state, and force Credentials -// to call the Provider's Retrieve(). -func (c *Credentials) Expire() { - c.m.Lock() - defer c.m.Unlock() - - c.forceRefresh = true -} - -// IsExpired returns if the credentials are no longer valid, and need -// to be retrieved. -// -// If the Credentials were forced to be expired with Expire() this will -// reflect that override. -func (c *Credentials) IsExpired() bool { - c.m.Lock() - defer c.m.Unlock() - - return c.isExpired() -} - -// isExpired helper method wrapping the definition of expired credentials. -func (c *Credentials) isExpired() bool { - return c.forceRefresh || c.provider.IsExpired() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go deleted file mode 100644 index c39749524e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go +++ /dev/null @@ -1,178 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "encoding/json" - "fmt" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/ec2metadata" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// Example how to configure the EC2RoleProvider with custom http Client, Endpoint -// or ExpiryWindow -// -// p := &ec2rolecreds.EC2RoleProvider{ -// // Pass in a custom timeout to be used when requesting -// // IAM EC2 Role credentials. -// Client: ec2metadata.New(sess, aws.Config{ -// HTTPClient: &http.Client{Timeout: 10 * time.Second}, -// }), -// -// // Do not use early expiry of credentials. If a non zero value is -// // specified the credentials will be expired early -// ExpiryWindow: 0, -// } -type EC2RoleProvider struct { - credentials.Expiry - - // Required EC2Metadata client to use when connecting to EC2 metadata service. - Client *ec2metadata.EC2Metadata - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client. -// The ConfigProvider is satisfied by the session.Session type. -func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: ec2metadata.New(c), - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 -// metadata service. -func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: client, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve retrieves credentials from the EC2 service. -// Error will be returned if the request fails, or unable to extract -// the desired credentials. -func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) { - credsList, err := requestCredList(m.Client) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - if len(credsList) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) - } - credsName := credsList[0] - - roleCreds, err := requestCred(m.Client, credsName) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - ProviderName: ProviderName, - }, nil -} - -// A ec2RoleCredRespBody provides the shape for unmarshaling credential -// request responses. -type ec2RoleCredRespBody struct { - // Success State - Expiration time.Time - AccessKeyID string - SecretAccessKey string - Token string - - // Error state - Code string - Message string -} - -const iamSecurityCredsPath = "/iam/security-credentials" - -// requestCredList requests a list of credentials from the EC2 service. -// If there are no credentials, or there is an error making or receiving the request -func requestCredList(client *ec2metadata.EC2Metadata) ([]string, error) { - resp, err := client.GetMetadata(iamSecurityCredsPath) - if err != nil { - return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err) - } - - credsList := []string{} - s := bufio.NewScanner(strings.NewReader(resp)) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, awserr.New("SerializationError", "failed to read EC2 instance role from metadata service", err) - } - - return credsList, nil -} - -// requestCred requests the credentials for a specific credentials from the EC2 service. -// -// If the credentials cannot be found, or there is an error reading the response -// and error will be returned. -func requestCred(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName)) - if err != nil { - return ec2RoleCredRespBody{}, - awserr.New("EC2RoleRequestError", - fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName), - err) - } - - respCreds := ec2RoleCredRespBody{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - awserr.New("SerializationError", - fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName), - err) - } - - if respCreds.Code != "Success" { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil) - } - - return respCreds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go deleted file mode 100644 index a4cec5c553..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package endpointcreds provides support for retrieving credentials from an -// arbitrary HTTP endpoint. -// -// The credentials endpoint Provider can receive both static and refreshable -// credentials that will expire. Credentials are static when an "Expiration" -// value is not provided in the endpoint's response. -// -// Static credentials will never expire once they have been retrieved. The format -// of the static credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// } -// -// Refreshable credentials will expire within the "ExpiryWindow" of the Expiration -// value in the response. The format of the refreshable credentials response: -// { -// "AccessKeyId" : "MUA...", -// "SecretAccessKey" : "/7PC5om....", -// "Token" : "AQoDY....=", -// "Expiration" : "2016-02-25T06:03:31Z" -// } -// -// Errors should be returned in the following format and only returned with 400 -// or 500 HTTP status codes. -// { -// "code": "ErrorCode", -// "message": "Helpful error message." -// } -package endpointcreds - -import ( - "encoding/json" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -// Provider satisfies the credentials.Provider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - staticCreds bool - credentials.Expiry - - // Requires a AWS Client to make HTTP requests to the endpoint with. - // the Endpoint the request will be made to is provided by the aws.Config's - // Endpoint value. - Client *client.Client - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewProviderClient returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider { - p := &Provider{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "CredentialsEndpoint", - Endpoint: endpoint, - }, - handlers, - ), - } - - p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler) - p.Client.Handlers.UnmarshalError.PushBack(unmarshalError) - p.Client.Handlers.Validate.Clear() - p.Client.Handlers.Validate.PushBack(validateEndpointHandler) - - for _, option := range options { - option(p) - } - - return p -} - -// NewCredentialsClient returns a Credentials wrapper for retrieving credentials -// from an arbitrary endpoint concurrently. The client will request the -func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials { - return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...)) -} - -// IsExpired returns true if the credentials retrieved are expired, or not yet -// retrieved. -func (p *Provider) IsExpired() bool { - if p.staticCreds { - return false - } - return p.Expiry.IsExpired() -} - -// Retrieve will attempt to request the credentials from the endpoint the Provider -// was configured for. And error will be returned if the retrieval fails. -func (p *Provider) Retrieve() (credentials.Value, error) { - resp, err := p.getCredentials() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("CredentialsEndpointError", "failed to load credentials", err) - } - - if resp.Expiration != nil { - p.SetExpiration(*resp.Expiration, p.ExpiryWindow) - } else { - p.staticCreds = true - } - - return credentials.Value{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - ProviderName: ProviderName, - }, nil -} - -type getCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -type errorOutput struct { - Code string `json:"code"` - Message string `json:"message"` -} - -func (p *Provider) getCredentials() (*getCredentialsOutput, error) { - op := &request.Operation{ - Name: "GetCredentials", - HTTPMethod: "GET", - } - - out := &getCredentialsOutput{} - req := p.Client.NewRequest(op, nil, out) - req.HTTPRequest.Header.Set("Accept", "application/json") - - return out, req.Send() -} - -func validateEndpointHandler(r *request.Request) { - if len(r.ClientInfo.Endpoint) == 0 { - r.Error = aws.ErrMissingEndpoint - } -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - out := r.Data.(*getCredentialsOutput) - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - var errOut errorOutput - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&errOut); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New(errOut.Code, errOut.Message, nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go deleted file mode 100644 index c14231a16f..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ /dev/null @@ -1,78 +0,0 @@ -package credentials - -import ( - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// EnvProviderName provides a name of Env provider -const EnvProviderName = "EnvProvider" - -var ( - // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be - // found in the process's environment. - // - // @readonly - ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) - - // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key - // can't be found in the process's environment. - // - // @readonly - ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) -) - -// A EnvProvider retrieves credentials from the environment variables of the -// running process. Environment credentials never expire. -// -// Environment variables used: -// -// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY -// -// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY -type EnvProvider struct { - retrieved bool -} - -// NewEnvCredentials returns a pointer to a new Credentials object -// wrapping the environment variable provider. -func NewEnvCredentials() *Credentials { - return NewCredentials(&EnvProvider{}) -} - -// Retrieve retrieves the keys from the environment. -func (e *EnvProvider) Retrieve() (Value, error) { - e.retrieved = false - - id := os.Getenv("AWS_ACCESS_KEY_ID") - if id == "" { - id = os.Getenv("AWS_ACCESS_KEY") - } - - secret := os.Getenv("AWS_SECRET_ACCESS_KEY") - if secret == "" { - secret = os.Getenv("AWS_SECRET_KEY") - } - - if id == "" { - return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound - } - - if secret == "" { - return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound - } - - e.retrieved = true - return Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: os.Getenv("AWS_SESSION_TOKEN"), - ProviderName: EnvProviderName, - }, nil -} - -// IsExpired returns if the credentials have been retrieved. -func (e *EnvProvider) IsExpired() bool { - return !e.retrieved -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini b/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini deleted file mode 100644 index 7fc91d9d20..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/example.ini +++ /dev/null @@ -1,12 +0,0 @@ -[default] -aws_access_key_id = accessKey -aws_secret_access_key = secret -aws_session_token = token - -[no_token] -aws_access_key_id = accessKey -aws_secret_access_key = secret - -[with_colon] -aws_access_key_id: accessKey -aws_secret_access_key: secret diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go deleted file mode 100644 index 51e21e0f38..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ /dev/null @@ -1,150 +0,0 @@ -package credentials - -import ( - "fmt" - "os" - - "github.com/go-ini/ini" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredsProviderName provides a name of SharedCreds provider -const SharedCredsProviderName = "SharedCredentialsProvider" - -var ( - // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. - ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) -) - -// A SharedCredentialsProvider retrieves credentials from the current user's home -// directory, and keeps track if those credentials are expired. -// -// Profile ini file example: $HOME/.aws/credentials -type SharedCredentialsProvider struct { - // Path to the shared credentials file. - // - // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the - // env value is empty will default to current user's home directory. - // Linux/OSX: "$HOME/.aws/credentials" - // Windows: "%USERPROFILE%\.aws\credentials" - Filename string - - // AWS Profile to extract credentials from the shared credentials file. If empty - // will default to environment variable "AWS_PROFILE" or "default" if - // environment variable is also not set. - Profile string - - // retrieved states if the credentials have been successfully retrieved. - retrieved bool -} - -// NewSharedCredentials returns a pointer to a new Credentials object -// wrapping the Profile file provider. -func NewSharedCredentials(filename, profile string) *Credentials { - return NewCredentials(&SharedCredentialsProvider{ - Filename: filename, - Profile: profile, - }) -} - -// Retrieve reads and extracts the shared credentials from the current -// users home directory. -func (p *SharedCredentialsProvider) Retrieve() (Value, error) { - p.retrieved = false - - filename, err := p.filename() - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - creds, err := loadProfile(filename, p.profile()) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - p.retrieved = true - return creds, nil -} - -// IsExpired returns if the shared credentials have expired. -func (p *SharedCredentialsProvider) IsExpired() bool { - return !p.retrieved -} - -// loadProfiles loads from the file pointed to by shared credentials filename for profile. -// The credentials retrieved from the profile will be returned or error. Error will be -// returned if it fails to read from the file, or the data is invalid. -func loadProfile(filename, profile string) (Value, error) { - config, err := ini.Load(filename) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) - } - iniProfile, err := config.GetSection(profile) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", err) - } - - id, err := iniProfile.GetKey("aws_access_key_id") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", - fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), - err) - } - - secret, err := iniProfile.GetKey("aws_secret_access_key") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", - fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), - nil) - } - - // Default to empty string if not found - token := iniProfile.Key("aws_session_token") - - return Value{ - AccessKeyID: id.String(), - SecretAccessKey: secret.String(), - SessionToken: token.String(), - ProviderName: SharedCredsProviderName, - }, nil -} - -// filename returns the filename to use to read AWS shared credentials. -// -// Will return an error if the user's home directory path cannot be found. -func (p *SharedCredentialsProvider) filename() (string, error) { - if len(p.Filename) != 0 { - return p.Filename, nil - } - - if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(p.Filename) != 0 { - return p.Filename, nil - } - - if home := shareddefaults.UserHomeDir(); len(home) == 0 { - // Backwards compatibility of home directly not found error being returned. - // This error is too verbose, failure when opening the file would of been - // a better error to return. - return "", ErrSharedCredentialsHomeNotFound - } - - p.Filename = shareddefaults.SharedCredentialsFilename() - - return p.Filename, nil -} - -// profile returns the AWS shared credentials profile. If empty will read -// environment variable "AWS_PROFILE". If that is not set profile will -// return "default". -func (p *SharedCredentialsProvider) profile() string { - if p.Profile == "" { - p.Profile = os.Getenv("AWS_PROFILE") - } - if p.Profile == "" { - p.Profile = "default" - } - - return p.Profile -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go deleted file mode 100644 index 4f5dab3fcc..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ /dev/null @@ -1,57 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// StaticProviderName provides a name of Static provider -const StaticProviderName = "StaticProvider" - -var ( - // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - // - // @readonly - ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) -) - -// A StaticProvider is a set of credentials which are set programmatically, -// and will never expire. -type StaticProvider struct { - Value -} - -// NewStaticCredentials returns a pointer to a new Credentials object -// wrapping a static credentials value provider. -func NewStaticCredentials(id, secret, token string) *Credentials { - return NewCredentials(&StaticProvider{Value: Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: token, - }}) -} - -// NewStaticCredentialsFromCreds returns a pointer to a new Credentials object -// wrapping the static credentials value provide. Same as NewStaticCredentials -// but takes the creds Value instead of individual fields -func NewStaticCredentialsFromCreds(creds Value) *Credentials { - return NewCredentials(&StaticProvider{Value: creds}) -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s *StaticProvider) Retrieve() (Value, error) { - if s.AccessKeyID == "" || s.SecretAccessKey == "" { - return Value{ProviderName: StaticProviderName}, ErrStaticCredentialsEmpty - } - - if len(s.Value.ProviderName) == 0 { - s.Value.ProviderName = StaticProviderName - } - return s.Value, nil -} - -// IsExpired returns if the credentials are expired. -// -// For StaticProvider, the credentials never expired. -func (s *StaticProvider) IsExpired() bool { - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 4108e433e6..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,298 +0,0 @@ -/* -Package stscreds are credential Providers to retrieve STS AWS credentials. - -STS provides multiple ways to retrieve credentials which can be used when making -future AWS service API operation calls. - -The SDK will ensure that per instance of credentials.Credentials all requests -to refresh the credentials will be synchronized. But, the SDK is unable to -ensure synchronous usage of the AssumeRoleProvider if the value is shared -between multiple Credentials, Sessions or service clients. - -Assume Role - -To assume an IAM role using STS with the SDK you can create a new Credentials -with the SDKs's stscreds package. - - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with static MFA Token - -To assume an IAM role with a MFA token you can either specify a MFA token code -directly or provide a function to prompt the user each time the credentials -need to refresh the role's credentials. Specifying the TokenCode should be used -for short lived operations that will not need to be refreshed, and when you do -not want to have direct control over the user provides their MFA token. - -With TokenCode the AssumeRoleProvider will be not be able to refresh the role's -credentials. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN using the MFA token code provided. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenCode = aws.String("00000000") - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with MFA Token Provider - -To assume an IAM role with MFA for longer running tasks where the credentials -may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -will allow the credential provider to prompt for new MFA token code when the -role's credentials need to be refreshed. - -The StdinTokenProvider function is available to prompt on stdin to retrieve -the MFA token code from the user. You can also implement custom prompts by -satisfing the TokenProvider function signature. - -Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -have undesirable results as the StdinTokenProvider will not be synchronized. A -single Credentials with an AssumeRoleProvider can be shared safely. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenProvider = stscreds.StdinTokenProvider - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -*/ -package stscreds - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/service/sts" -) - -// StdinTokenProvider will prompt on stdout and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function go read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Printf("Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoler represents the minimal subset of the STS client API used by this provider. -type AssumeRoler interface { - AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the credentials -// will be valid for. -var DefaultDuration = time.Duration(15) * time.Minute - -// AssumeRoleProvider retrieves temporary credentials from the STS service, and -// keeps track of their expiration time. -// -// This credential provider will be used by the SDKs default credential change -// when shared configuration is enabled, and the shared config or shared credentials -// file configure assume role. See Session docs for how to do this. -// -// AssumeRoleProvider does not provide any synchronization and it is not safe -// to share this value across multiple Credentials, Sessions, or service clients -// without also sharing the same Credentials instance. -type AssumeRoleProvider struct { - credentials.Expiry - - // STS client to make assume role request with. - Client AssumeRoler - - // Role to be assumed. - RoleARN string - - // Session name, if you wish to reuse the credentials elsewhere. - RoleSessionName string - - // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. - Duration time.Duration - - // Optional ExternalID to pass along, defaults to nil if not set. - ExternalID *string - - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - SerialNumber *string - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // If SerialNumber is set and neither TokenCode nor TokenProvider are also - // set an error will be returned. - TokenCode *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is also set and - // TokenCode is not set. - // - // If both TokenCode and TokenProvider is set, TokenProvider will be used and - // TokenCode is ignored. - TokenProvider func() (string, error) - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes a Config provider to create the STS client. The ConfigProvider is -// satisfied by the session.Session type. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: sts.New(c), - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes an AssumeRoler which can be satisfied by the STS client. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: svc, - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { - - // Apply defaults where parameters are not set. - if p.RoleSessionName == "" { - // Try to work out a role name that will hopefully end up unique. - p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano()) - } - if p.Duration == 0 { - // Expire as often as AWS permits. - p.Duration = DefaultDuration - } - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(int64(p.Duration / time.Second)), - RoleArn: aws.String(p.RoleARN), - RoleSessionName: aws.String(p.RoleSessionName), - ExternalId: p.ExternalID, - } - if p.Policy != nil { - input.Policy = p.Policy - } - if p.SerialNumber != nil { - if p.TokenCode != nil { - input.SerialNumber = p.SerialNumber - input.TokenCode = p.TokenCode - } else if p.TokenProvider != nil { - input.SerialNumber = p.SerialNumber - code, err := p.TokenProvider() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - input.TokenCode = aws.String(code) - } else { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("AssumeRoleTokenNotAvailable", - "assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil) - } - } - - roleOutput, err := p.Client.AssumeRole(input) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - // We will proactively generate new credentials before they expire. - p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: *roleOutput.Credentials.AccessKeyId, - SecretAccessKey: *roleOutput.Credentials.SecretAccessKey, - SessionToken: *roleOutput.Credentials.SessionToken, - ProviderName: ProviderName, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go deleted file mode 100644 index 07afe3b8e6..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ /dev/null @@ -1,163 +0,0 @@ -// Package defaults is a collection of helpers to retrieve the SDK's default -// configuration and handlers. -// -// Generally this package shouldn't be used directly, but session.Session -// instead. This package is useful when you need to reset the defaults -// of a session or service client to the SDK defaults before setting -// additional parameters. -package defaults - -import ( - "fmt" - "net/http" - "net/url" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Defaults provides a collection of default values for SDK clients. -type Defaults struct { - Config *aws.Config - Handlers request.Handlers -} - -// Get returns the SDK's default values with Config and handlers pre-configured. -func Get() Defaults { - cfg := Config() - handlers := Handlers() - cfg.Credentials = CredChain(cfg, handlers) - - return Defaults{ - Config: cfg, - Handlers: handlers, - } -} - -// Config returns the default configuration without credentials. -// To retrieve a config with credentials also included use -// `defaults.Get().Config` instead. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the configuration of an -// existing service client or session. -func Config() *aws.Config { - return aws.NewConfig(). - WithCredentials(credentials.AnonymousCredentials). - WithRegion(os.Getenv("AWS_REGION")). - WithHTTPClient(http.DefaultClient). - WithMaxRetries(aws.UseServiceDefaultRetries). - WithLogger(aws.NewDefaultLogger()). - WithLogLevel(aws.LogOff). - WithEndpointResolver(endpoints.DefaultResolver()) -} - -// Handlers returns the default request handlers. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the request handlers of an -// existing service client or session. -func Handlers() request.Handlers { - var handlers request.Handlers - - handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - handlers.Validate.AfterEachFn = request.HandlerListStopOnError - handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) - handlers.Build.AfterEachFn = request.HandlerListStopOnError - handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) - handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler) - handlers.Send.PushBackNamed(corehandlers.SendHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) - - return handlers -} - -// CredChain returns the default credential chain. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the credentials of an -// existing service client or session's Config. -func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { - return credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credentials.EnvProvider{}, - &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, - RemoteCredProvider(*cfg, handlers), - }, - }) -} - -const ( - httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - ecsCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -) - -// RemoteCredProvider returns a credentials provider for the default remote -// endpoints such as EC2 or ECS Roles. -func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - if u := os.Getenv(httpProviderEnvVar); len(u) > 0 { - return localHTTPCredProvider(cfg, handlers, u) - } - - if uri := os.Getenv(ecsCredsProviderEnvVar); len(uri) > 0 { - u := fmt.Sprintf("http://169.254.170.2%s", uri) - return httpCredProvider(cfg, handlers, u) - } - - return ec2RoleProvider(cfg, handlers) -} - -func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - var errMsg string - - parsed, err := url.Parse(u) - if err != nil { - errMsg = fmt.Sprintf("invalid URL, %v", err) - } else if host := aws.URLHostname(parsed); !(host == "localhost" || host == "127.0.0.1") { - errMsg = fmt.Sprintf("invalid host address, %q, only localhost and 127.0.0.1 are valid.", host) - } - - if len(errMsg) > 0 { - if cfg.Logger != nil { - cfg.Logger.Log("Ignoring, HTTP credential provider", errMsg, err) - } - return credentials.ErrorProvider{ - Err: awserr.New("CredentialsEndpointError", errMsg, err), - ProviderName: endpointcreds.ProviderName, - } - } - - return httpCredProvider(cfg, handlers, u) -} - -func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - return endpointcreds.NewProviderClient(cfg, handlers, u, - func(p *endpointcreds.Provider) { - p.ExpiryWindow = 5 * time.Minute - }, - ) -} - -func ec2RoleProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - resolver := cfg.EndpointResolver - if resolver == nil { - resolver = endpoints.DefaultResolver() - } - - e, _ := resolver.EndpointFor(endpoints.Ec2metadataServiceID, "") - return &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.NewClient(cfg, handlers, e.URL, e.SigningRegion), - ExpiryWindow: 5 * time.Minute, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go deleted file mode 100644 index ca0ee1dcc7..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go +++ /dev/null @@ -1,27 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return shareddefaults.SharedCredentialsFilename() -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return shareddefaults.SharedConfigFilename() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/doc.go deleted file mode 100644 index 4fcb616184..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/doc.go +++ /dev/null @@ -1,56 +0,0 @@ -// Package aws provides the core SDK's utilities and shared types. Use this package's -// utilities to simplify setting and reading API operations parameters. -// -// Value and Pointer Conversion Utilities -// -// This package includes a helper conversion utility for each scalar type the SDK's -// API use. These utilities make getting a pointer of the scalar, and dereferencing -// a pointer easier. -// -// Each conversion utility comes in two forms. Value to Pointer and Pointer to Value. -// The Pointer to value will safely dereference the pointer and return its value. -// If the pointer was nil, the scalar's zero value will be returned. -// -// The value to pointer functions will be named after the scalar type. So get a -// *string from a string value use the "String" function. This makes it easy to -// to get pointer of a literal string value, because getting the address of a -// literal requires assigning the value to a variable first. -// -// var strPtr *string -// -// // Without the SDK's conversion functions -// str := "my string" -// strPtr = &str -// -// // With the SDK's conversion functions -// strPtr = aws.String("my string") -// -// // Convert *string to string value -// str = aws.StringValue(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.StringValueSlice(strPtrs) -// -// SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go deleted file mode 100644 index 984407a580..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ /dev/null @@ -1,162 +0,0 @@ -package ec2metadata - -import ( - "encoding/json" - "fmt" - "net/http" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// GetMetadata uses the path provided to request information from the EC2 -// instance metdata service. The content will be returned as a string, or -// error if the request failed. -func (c *EC2Metadata) GetMetadata(p string) (string, error) { - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetUserData returns the userdata that was configured for the service. If -// there is no user-data setup for the EC2 instance a "NotFoundError" error -// code will be returned. -func (c *EC2Metadata) GetUserData() (string, error) { - op := &request.Operation{ - Name: "GetUserData", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "user-data"), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - req.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - if r.HTTPResponse.StatusCode == http.StatusNotFound { - r.Error = awserr.New("NotFoundError", "user-data not found", r.Error) - } - }) - - return output.Content, req.Send() -} - -// GetDynamicData uses the path provided to request information from the EC2 -// instance metadata service for dynamic data. The content will be returned -// as a string, or error if the request failed. -func (c *EC2Metadata) GetDynamicData(p string) (string, error) { - op := &request.Operation{ - Name: "GetDynamicData", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "dynamic", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *EC2Metadata) GetInstanceIdentityDocument() (EC2InstanceIdentityDocument, error) { - resp, err := c.GetDynamicData("instance-identity/document") - if err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 instance identity document", err) - } - - doc := EC2InstanceIdentityDocument{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&doc); err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("SerializationError", - "failed to decode EC2 instance identity document", err) - } - - return doc, nil -} - -// IAMInfo retrieves IAM info from the metadata API -func (c *EC2Metadata) IAMInfo() (EC2IAMInfo, error) { - resp, err := c.GetMetadata("iam/info") - if err != nil { - return EC2IAMInfo{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 IAM info", err) - } - - info := EC2IAMInfo{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&info); err != nil { - return EC2IAMInfo{}, - awserr.New("SerializationError", - "failed to decode EC2 IAM info", err) - } - - if info.Code != "Success" { - errMsg := fmt.Sprintf("failed to get EC2 IAM Info (%s)", info.Code) - return EC2IAMInfo{}, - awserr.New("EC2MetadataError", errMsg, nil) - } - - return info, nil -} - -// Region returns the region the instance is running in. -func (c *EC2Metadata) Region() (string, error) { - resp, err := c.GetMetadata("placement/availability-zone") - if err != nil { - return "", err - } - - // returns region without the suffix. Eg: us-west-2a becomes us-west-2 - return resp[:len(resp)-1], nil -} - -// Available returns if the application has access to the EC2 Metadata service. -// Can be used to determine if application is running within an EC2 Instance and -// the metadata service is available. -func (c *EC2Metadata) Available() bool { - if _, err := c.GetMetadata("instance-id"); err != nil { - return false - } - - return true -} - -// An EC2IAMInfo provides the shape for unmarshaling -// an IAM info from the metadata API -type EC2IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} - -// An EC2InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type EC2InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - AvailabilityZone string `json:"availabilityZone"` - PrivateIP string `json:"privateIp"` - Version string `json:"version"` - Region string `json:"region"` - InstanceID string `json:"instanceId"` - BillingProducts []string `json:"billingProducts"` - InstanceType string `json:"instanceType"` - AccountID string `json:"accountId"` - PendingTime time.Time `json:"pendingTime"` - ImageID string `json:"imageId"` - KernelID string `json:"kernelId"` - RamdiskID string `json:"ramdiskId"` - Architecture string `json:"architecture"` -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go deleted file mode 100644 index 5b4379dbd8..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ /dev/null @@ -1,124 +0,0 @@ -// Package ec2metadata provides the client for making API calls to the -// EC2 Metadata service. -package ec2metadata - -import ( - "bytes" - "errors" - "io" - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ServiceName is the name of the service. -const ServiceName = "ec2metadata" - -// A EC2Metadata is an EC2 Metadata service Client. -type EC2Metadata struct { - *client.Client -} - -// New creates a new instance of the EC2Metadata client with a session. -// This client is safe to use across multiple goroutines. -// -// -// Example: -// // Create a EC2Metadata client from just a session. -// svc := ec2metadata.New(mySession) -// -// // Create a EC2Metadata client with additional configuration -// svc := ec2metadata.New(mySession, aws.NewConfig().WithLogLevel(aws.LogDebugHTTPBody)) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata { - c := p.ClientConfig(ServiceName, cfgs...) - return NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion) -} - -// NewClient returns a new EC2Metadata client. Should be used to create -// a client when not using a session. Generally using just New with a session -// is preferred. -// -// If an unmodified HTTP client is provided from the stdlib default, or no client -// the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened. -// To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default. -func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata { - if !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) { - // If the http client is unmodified and this feature is not disabled - // set custom timeouts for EC2Metadata requests. - cfg.HTTPClient = &http.Client{ - // use a shorter timeout than default because the metadata - // service is local if it is running, and to fail faster - // if not running on an ec2 instance. - Timeout: 5 * time.Second, - } - } - - svc := &EC2Metadata{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - Endpoint: endpoint, - APIVersion: "latest", - }, - handlers, - ), - } - - svc.Handlers.Unmarshal.PushBack(unmarshalHandler) - svc.Handlers.UnmarshalError.PushBack(unmarshalError) - svc.Handlers.Validate.Clear() - svc.Handlers.Validate.PushBack(validateEndpointHandler) - - // Add additional options to the service config - for _, option := range opts { - option(svc.Client) - } - - return svc -} - -func httpClientZero(c *http.Client) bool { - return c == nil || (c.Transport == nil && c.CheckRedirect == nil && c.Jar == nil && c.Timeout == 0) -} - -type metadataOutput struct { - Content string -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata respose", err) - return - } - - if data, ok := r.Data.(*metadataOutput); ok { - data.Content = b.String() - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err) - return - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String())) -} - -func validateEndpointHandler(r *request.Request) { - if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go deleted file mode 100644 index 74f72de073..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ /dev/null @@ -1,133 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type modelDefinition map[string]json.RawMessage - -// A DecodeModelOptions are the options for how the endpoints model definition -// are decoded. -type DecodeModelOptions struct { - SkipCustomizations bool -} - -// Set combines all of the option functions together. -func (d *DecodeModelOptions) Set(optFns ...func(*DecodeModelOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// DecodeModel unmarshals a Regions and Endpoint model definition file into -// a endpoint Resolver. If the file format is not supported, or an error occurs -// when unmarshaling the model an error will be returned. -// -// Casting the return value of this func to a EnumPartitions will -// allow you to get a list of the partitions in the order the endpoints -// will be resolved in. -// -// resolver, err := endpoints.DecodeModel(reader) -// -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// for _, p := range partitions { -// // ... inspect partitions -// } -func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) { - var opts DecodeModelOptions - opts.Set(optFns...) - - // Get the version of the partition file to determine what - // unmarshaling model to use. - modelDef := modelDefinition{} - if err := json.NewDecoder(r).Decode(&modelDef); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - var version string - if b, ok := modelDef["version"]; ok { - version = string(b) - } else { - return nil, newDecodeModelError("endpoints version not found in model", nil) - } - - if version == "3" { - return decodeV3Endpoints(modelDef, opts) - } - - return nil, newDecodeModelError( - fmt.Sprintf("endpoints version %s, not supported", version), nil) -} - -func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resolver, error) { - b, ok := modelDef["partitions"] - if !ok { - return nil, newDecodeModelError("endpoints model missing partitions", nil) - } - - ps := partitions{} - if err := json.Unmarshal(b, &ps); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - if opts.SkipCustomizations { - return ps, nil - } - - // Customization - for i := 0; i < len(ps); i++ { - p := &ps[i] - custAddEC2Metadata(p) - custAddS3DualStack(p) - custRmIotDataService(p) - } - - return ps, nil -} - -func custAddS3DualStack(p *partition) { - if p.ID != "aws" { - return - } - - s, ok := p.Services["s3"] - if !ok { - return - } - - s.Defaults.HasDualStack = boxedTrue - s.Defaults.DualStackHostname = "{service}.dualstack.{region}.{dnsSuffix}" - - p.Services["s3"] = s -} - -func custAddEC2Metadata(p *partition) { - p.Services["ec2metadata"] = service{ - IsRegionalized: boxedFalse, - PartitionEndpoint: "aws-global", - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - } -} - -func custRmIotDataService(p *partition) { - delete(p.Services, "data.iot") -} - -type decodeModelError struct { - awsError -} - -func newDecodeModelError(msg string, err error) decodeModelError { - return decodeModelError{ - awsError: awserr.New("DecodeEndpointsModelError", msg, err), - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go deleted file mode 100644 index ba0c07b25b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ /dev/null @@ -1,2331 +0,0 @@ -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - -// Partition identifiers -const ( - AwsPartitionID = "aws" // AWS Standard partition. - AwsCnPartitionID = "aws-cn" // AWS China partition. - AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. -) - -// AWS Standard partition's regions. -const ( - ApNortheast1RegionID = "ap-northeast-1" // Asia Pacific (Tokyo). - ApNortheast2RegionID = "ap-northeast-2" // Asia Pacific (Seoul). - ApSouth1RegionID = "ap-south-1" // Asia Pacific (Mumbai). - ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). - ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). - CaCentral1RegionID = "ca-central-1" // Canada (Central). - EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). - EuWest1RegionID = "eu-west-1" // EU (Ireland). - EuWest2RegionID = "eu-west-2" // EU (London). - SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). - UsEast1RegionID = "us-east-1" // US East (N. Virginia). - UsEast2RegionID = "us-east-2" // US East (Ohio). - UsWest1RegionID = "us-west-1" // US West (N. California). - UsWest2RegionID = "us-west-2" // US West (Oregon). -) - -// AWS China partition's regions. -const ( - CnNorth1RegionID = "cn-north-1" // China (Beijing). -) - -// AWS GovCloud (US) partition's regions. -const ( - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). -) - -// Service identifiers -const ( - AcmServiceID = "acm" // Acm. - ApigatewayServiceID = "apigateway" // Apigateway. - ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - Appstream2ServiceID = "appstream2" // Appstream2. - AthenaServiceID = "athena" // Athena. - AutoscalingServiceID = "autoscaling" // Autoscaling. - BatchServiceID = "batch" // Batch. - BudgetsServiceID = "budgets" // Budgets. - ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. - CloudformationServiceID = "cloudformation" // Cloudformation. - CloudfrontServiceID = "cloudfront" // Cloudfront. - CloudhsmServiceID = "cloudhsm" // Cloudhsm. - CloudsearchServiceID = "cloudsearch" // Cloudsearch. - CloudtrailServiceID = "cloudtrail" // Cloudtrail. - CodebuildServiceID = "codebuild" // Codebuild. - CodecommitServiceID = "codecommit" // Codecommit. - CodedeployServiceID = "codedeploy" // Codedeploy. - CodepipelineServiceID = "codepipeline" // Codepipeline. - CodestarServiceID = "codestar" // Codestar. - CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. - CognitoIdpServiceID = "cognito-idp" // CognitoIdp. - CognitoSyncServiceID = "cognito-sync" // CognitoSync. - ConfigServiceID = "config" // Config. - CurServiceID = "cur" // Cur. - DatapipelineServiceID = "datapipeline" // Datapipeline. - DevicefarmServiceID = "devicefarm" // Devicefarm. - DirectconnectServiceID = "directconnect" // Directconnect. - DiscoveryServiceID = "discovery" // Discovery. - DmsServiceID = "dms" // Dms. - DsServiceID = "ds" // Ds. - DynamodbServiceID = "dynamodb" // Dynamodb. - Ec2ServiceID = "ec2" // Ec2. - Ec2metadataServiceID = "ec2metadata" // Ec2metadata. - EcrServiceID = "ecr" // Ecr. - EcsServiceID = "ecs" // Ecs. - ElasticacheServiceID = "elasticache" // Elasticache. - ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. - ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. - ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. - ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. - ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. - EmailServiceID = "email" // Email. - EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. - EsServiceID = "es" // Es. - EventsServiceID = "events" // Events. - FirehoseServiceID = "firehose" // Firehose. - GameliftServiceID = "gamelift" // Gamelift. - GlacierServiceID = "glacier" // Glacier. - GreengrassServiceID = "greengrass" // Greengrass. - HealthServiceID = "health" // Health. - IamServiceID = "iam" // Iam. - ImportexportServiceID = "importexport" // Importexport. - InspectorServiceID = "inspector" // Inspector. - IotServiceID = "iot" // Iot. - KinesisServiceID = "kinesis" // Kinesis. - KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. - KmsServiceID = "kms" // Kms. - LambdaServiceID = "lambda" // Lambda. - LightsailServiceID = "lightsail" // Lightsail. - LogsServiceID = "logs" // Logs. - MachinelearningServiceID = "machinelearning" // Machinelearning. - MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. - MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. - MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. - ModelsLexServiceID = "models.lex" // ModelsLex. - MonitoringServiceID = "monitoring" // Monitoring. - MturkRequesterServiceID = "mturk-requester" // MturkRequester. - OpsworksServiceID = "opsworks" // Opsworks. - OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. - OrganizationsServiceID = "organizations" // Organizations. - PinpointServiceID = "pinpoint" // Pinpoint. - PollyServiceID = "polly" // Polly. - RdsServiceID = "rds" // Rds. - RedshiftServiceID = "redshift" // Redshift. - RekognitionServiceID = "rekognition" // Rekognition. - Route53ServiceID = "route53" // Route53. - Route53domainsServiceID = "route53domains" // Route53domains. - RuntimeLexServiceID = "runtime.lex" // RuntimeLex. - S3ServiceID = "s3" // S3. - SdbServiceID = "sdb" // Sdb. - ServicecatalogServiceID = "servicecatalog" // Servicecatalog. - ShieldServiceID = "shield" // Shield. - SmsServiceID = "sms" // Sms. - SnowballServiceID = "snowball" // Snowball. - SnsServiceID = "sns" // Sns. - SqsServiceID = "sqs" // Sqs. - SsmServiceID = "ssm" // Ssm. - StatesServiceID = "states" // States. - StoragegatewayServiceID = "storagegateway" // Storagegateway. - StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. - StsServiceID = "sts" // Sts. - SupportServiceID = "support" // Support. - SwfServiceID = "swf" // Swf. - TaggingServiceID = "tagging" // Tagging. - WafServiceID = "waf" // Waf. - WafRegionalServiceID = "waf-regional" // WafRegional. - WorkdocsServiceID = "workdocs" // Workdocs. - WorkspacesServiceID = "workspaces" // Workspaces. - XrayServiceID = "xray" // Xray. -) - -// DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, and AWS GovCloud (US). -// -// Use DefaultPartitions() to get the list of the default partitions. -func DefaultResolver() Resolver { - return defaultPartitions -} - -// DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, and AWS GovCloud (US). -// -// partitions := endpoints.DefaultPartitions -// for _, p := range partitions { -// // ... inspect partitions -// } -func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() -} - -var defaultPartitions = partitions{ - awsPartition, - awscnPartition, - awsusgovPartition, -} - -// AwsPartition returns the Resolver for AWS Standard. -func AwsPartition() Partition { - return awsPartition.Partition() -} - -var awsPartition = partition{ - ID: "aws", - Name: "AWS Standard", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "ap-northeast-1": region{ - Description: "Asia Pacific (Tokyo)", - }, - "ap-northeast-2": region{ - Description: "Asia Pacific (Seoul)", - }, - "ap-south-1": region{ - Description: "Asia Pacific (Mumbai)", - }, - "ap-southeast-1": region{ - Description: "Asia Pacific (Singapore)", - }, - "ap-southeast-2": region{ - Description: "Asia Pacific (Sydney)", - }, - "ca-central-1": region{ - Description: "Canada (Central)", - }, - "eu-central-1": region{ - Description: "EU (Frankfurt)", - }, - "eu-west-1": region{ - Description: "EU (Ireland)", - }, - "eu-west-2": region{ - Description: "EU (London)", - }, - "sa-east-1": region{ - Description: "South America (Sao Paulo)", - }, - "us-east-1": region{ - Description: "US East (N. Virginia)", - }, - "us-east-2": region{ - Description: "US East (Ohio)", - }, - "us-west-1": region{ - Description: "US West (N. California)", - }, - "us-west-2": region{ - Description: "US West (Oregon)", - }, - }, - Services: services{ - "acm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "apigateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "appstream2": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "appstream", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "athena": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "batch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "budgets.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "clouddirectory": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudfront": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "cloudfront.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudsearch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codebuild": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codecommit": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codepipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codestar": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-identity": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-idp": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-sync": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cur": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "datapipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "devicefarm": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "discovery": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "dms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticfilesystem": service{ - - Endpoints: endpoints{ - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.{service}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elastictranscoder": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "email": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "entitlement.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "firehose": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "gamelift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "health": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "iam.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "importexport": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "importexport.amazonaws.com", - SignatureVersions: []string{"v2", "v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - Service: "IngestionService", - }, - }, - }, - }, - "inspector": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesisanalytics": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lightsail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "machinelearning": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "marketplacecommerceanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mobileanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "models.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mturk-requester": service{ - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "sandbox": endpoint{ - Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", - }, - "us-east-1": endpoint{}, - }, - }, - "opsworks": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "opsworks-cm": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "organizations.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "pinpoint": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "polly": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "route53.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "route53domains": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "s3": service{ - PartitionEndpoint: "us-east-1", - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "s3-ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{ - Hostname: "s3-ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-southeast-2": endpoint{ - Hostname: "s3-ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{ - Hostname: "s3-eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "eu-west-2": endpoint{}, - "s3-external-1": endpoint{ - Hostname: "s3-external-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{ - Hostname: "s3-sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-1": endpoint{ - Hostname: "s3.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{ - Hostname: "s3-us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-west-2": endpoint{ - Hostname: "s3-us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - }, - }, - "sdb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v2"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - Hostname: "sdb.amazonaws.com", - }, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "servicecatalog": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "shield": service{ - IsRegionalized: boxedFalse, - Defaults: endpoint{ - SSLCommonName: "Shield.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "queue.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "states": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sts": service{ - PartitionEndpoint: "aws-global", - Defaults: endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{ - Hostname: "sts.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "aws-global": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "support": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "waf": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "waf.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "waf-regional": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workdocs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workspaces": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "xray": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - }, -} - -// AwsCnPartition returns the Resolver for AWS China. -func AwsCnPartition() Partition { - return awscnPartition.Partition() -} - -var awscnPartition = partition{ - ID: "aws-cn", - Name: "AWS China", - DNSSuffix: "amazonaws.com.cn", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^cn\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "cn-north-1": region{ - Description: "China (Beijing)", - }, - }, - Services: services{ - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-cn-global": endpoint{ - Hostname: "iam.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - }, -} - -// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). -func AwsUsGovPartition() Partition { - return awsusgovPartition.Partition() -} - -var awsusgovPartition = partition{ - ID: "aws-us-gov", - Name: "AWS GovCloud (US)", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", - }, - }, - Services: services{ - "autoscaling": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "dynamodb": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ec2": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "elasticmapreduce": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "glacier": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-us-gov-global": endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "monitoring": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - SignatureVersions: []string{"s3", "s3v4"}, - }, - Endpoints: endpoints{ - "fips-us-gov-west-1": endpoint{ - Hostname: "s3-fips-us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - "us-gov-west-1": endpoint{ - Hostname: "s3-us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "sns": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "sqs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go deleted file mode 100644 index 84316b92c0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package endpoints provides the types and functionality for defining regions -// and endpoints, as well as querying those definitions. -// -// The SDK's Regions and Endpoints metadata is code generated into the endpoints -// package, and is accessible via the DefaultResolver function. This function -// returns a endpoint Resolver will search the metadata and build an associated -// endpoint if one is found. The default resolver will search all partitions -// known by the SDK. e.g AWS Standard (aws), AWS China (aws-cn), and -// AWS GovCloud (US) (aws-us-gov). -// . -// -// Enumerating Regions and Endpoint Metadata -// -// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface -// will allow you to get access to the list of underlying Partitions with the -// Partitions method. This is helpful if you want to limit the SDK's endpoint -// resolving to a single partition, or enumerate regions, services, and endpoints -// in the partition. -// -// resolver := endpoints.DefaultResolver() -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// -// for _, p := range partitions { -// fmt.Println("Regions for", p.ID()) -// for id, _ := range p.Regions() { -// fmt.Println("*", id) -// } -// -// fmt.Println("Services for", p.ID()) -// for id, _ := range p.Services() { -// fmt.Println("*", id) -// } -// } -// -// Using Custom Endpoints -// -// The endpoints package also gives you the ability to use your own logic how -// endpoints are resolved. This is a great way to define a custom endpoint -// for select services, without passing that logic down through your code. -// -// If a type implements the Resolver interface it can be used to resolve -// endpoints. To use this with the SDK's Session and Config set the value -// of the type to the EndpointsResolver field of aws.Config when initializing -// the session, or service client. -// -// In addition the ResolverFunc is a wrapper for a func matching the signature -// of Resolver.EndpointFor, converting it to a type that satisfies the -// Resolver interface. -// -// -// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { -// if service == endpoints.S3ServiceID { -// return endpoints.ResolvedEndpoint{ -// URL: "s3.custom.endpoint.com", -// SigningRegion: "custom-signing-region", -// }, nil -// } -// -// return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) -// } -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String("us-west-2"), -// EndpointResolver: endpoints.ResolverFunc(myCustomResolver), -// })) -package endpoints diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go deleted file mode 100644 index 9c3eedb48d..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ /dev/null @@ -1,439 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Options provide the configuration needed to direct how the -// endpoints will be resolved. -type Options struct { - // DisableSSL forces the endpoint to be resolved as HTTP. - // instead of HTTPS if the service supports it. - DisableSSL bool - - // Sets the resolver to resolve the endpoint as a dualstack endpoint - // for the service. If dualstack support for a service is not known and - // StrictMatching is not enabled a dualstack endpoint for the service will - // be returned. This endpoint may not be valid. If StrictMatching is - // enabled only services that are known to support dualstack will return - // dualstack endpoints. - UseDualStack bool - - // Enables strict matching of services and regions resolved endpoints. - // If the partition doesn't enumerate the exact service and region an - // error will be returned. This option will prevent returning endpoints - // that look valid, but may not resolve to any real endpoint. - StrictMatching bool - - // Enables resolving a service endpoint based on the region provided if the - // service does not exist. The service endpoint ID will be used as the service - // domain name prefix. By default the endpoint resolver requires the service - // to be known when resolving endpoints. - // - // If resolving an endpoint on the partition list the provided region will - // be used to determine which partition's domain name pattern to the service - // endpoint ID with. If both the service and region are unkonwn and resolving - // the endpoint on partition list an UnknownEndpointError error will be returned. - // - // If resolving and endpoint on a partition specific resolver that partition's - // domain name pattern will be used with the service endpoint ID. If both - // region and service do not exist when resolving an endpoint on a specific - // partition the partition's domain pattern will be used to combine the - // endpoint and region together. - // - // This option is ignored if StrictMatching is enabled. - ResolveUnknownService bool -} - -// Set combines all of the option functions together. -func (o *Options) Set(optFns ...func(*Options)) { - for _, fn := range optFns { - fn(o) - } -} - -// DisableSSLOption sets the DisableSSL options. Can be used as a functional -// option when resolving endpoints. -func DisableSSLOption(o *Options) { - o.DisableSSL = true -} - -// UseDualStackOption sets the UseDualStack option. Can be used as a functional -// option when resolving endpoints. -func UseDualStackOption(o *Options) { - o.UseDualStack = true -} - -// StrictMatchingOption sets the StrictMatching option. Can be used as a functional -// option when resolving endpoints. -func StrictMatchingOption(o *Options) { - o.StrictMatching = true -} - -// ResolveUnknownServiceOption sets the ResolveUnknownService option. Can be used -// as a functional option when resolving endpoints. -func ResolveUnknownServiceOption(o *Options) { - o.ResolveUnknownService = true -} - -// A Resolver provides the interface for functionality to resolve endpoints. -// The build in Partition and DefaultResolver return value satisfy this interface. -type Resolver interface { - EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) -} - -// ResolverFunc is a helper utility that wraps a function so it satisfies the -// Resolver interface. This is useful when you want to add additional endpoint -// resolving logic, or stub out specific endpoints with custom values. -type ResolverFunc func(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) - -// EndpointFor wraps the ResolverFunc function to satisfy the Resolver interface. -func (fn ResolverFunc) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return fn(service, region, opts...) -} - -var schemeRE = regexp.MustCompile("^([^:]+)://") - -// AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no -// scheme. If disableSSL is true HTTP will set HTTP instead of the default HTTPS. -// -// If disableSSL is set, it will only set the URL's scheme if the URL does not -// contain a scheme. -func AddScheme(endpoint string, disableSSL bool) string { - if !schemeRE.MatchString(endpoint) { - scheme := "https" - if disableSSL { - scheme = "http" - } - endpoint = fmt.Sprintf("%s://%s", scheme, endpoint) - } - - return endpoint -} - -// EnumPartitions a provides a way to retrieve the underlying partitions that -// make up the SDK's default Resolver, or any resolver decoded from a model -// file. -// -// Use this interface with DefaultResolver and DecodeModels to get the list of -// Partitions. -type EnumPartitions interface { - Partitions() []Partition -} - -// RegionsForService returns a map of regions for the partition and service. -// If either the partition or service does not exist false will be returned -// as the second parameter. -// -// This example shows how to get the regions for DynamoDB in the AWS partition. -// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) -// -// This is equivalent to using the partition directly. -// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() -func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { - for _, p := range ps { - if p.ID() != partitionID { - continue - } - if _, ok := p.p.Services[serviceID]; !ok { - break - } - - s := Service{ - id: serviceID, - p: p.p, - } - return s.Regions(), true - } - - return map[string]Region{}, false -} - -// PartitionForRegion returns the first partition which includes the region -// passed in. This includes both known regions and regions which match -// a pattern supported by the partition which may include regions that are -// not explicitly known by the partition. Use the Regions method of the -// returned Partition if explicit support is needed. -func PartitionForRegion(ps []Partition, regionID string) (Partition, bool) { - for _, p := range ps { - if _, ok := p.p.Regions[regionID]; ok || p.p.RegionRegex.MatchString(regionID) { - return p, true - } - } - - return Partition{}, false -} - -// A Partition provides the ability to enumerate the partition's regions -// and services. -type Partition struct { - id string - p *partition -} - -// ID returns the identifier of the partition. -func (p Partition) ID() string { return p.id } - -// EndpointFor attempts to resolve the endpoint based on service and region. -// See Options for information on configuring how the endpoint is resolved. -// -// If the service cannot be found in the metadata the UnknownServiceError -// error will be returned. This validation will occur regardless if -// StrictMatching is enabled. To enable resolving unknown services set the -// "ResolveUnknownService" option to true. When StrictMatching is disabled -// this option allows the partition resolver to resolve a endpoint based on -// the service endpoint ID provided. -// -// When resolving endpoints you can choose to enable StrictMatching. This will -// require the provided service and region to be known by the partition. -// If the endpoint cannot be strictly resolved an error will be returned. This -// mode is useful to ensure the endpoint resolved is valid. Without -// StrictMatching enabled the endpoint returned my look valid but may not work. -// StrictMatching requires the SDK to be updated if you want to take advantage -// of new regions and services expansions. -// -// Errors that can be returned. -// * UnknownServiceError -// * UnknownEndpointError -func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return p.p.EndpointFor(service, region, opts...) -} - -// Regions returns a map of Regions indexed by their ID. This is useful for -// enumerating over the regions in a partition. -func (p Partition) Regions() map[string]Region { - rs := map[string]Region{} - for id := range p.p.Regions { - rs[id] = Region{ - id: id, - p: p.p, - } - } - - return rs -} - -// Services returns a map of Service indexed by their ID. This is useful for -// enumerating over the services in a partition. -func (p Partition) Services() map[string]Service { - ss := map[string]Service{} - for id := range p.p.Services { - ss[id] = Service{ - id: id, - p: p.p, - } - } - - return ss -} - -// A Region provides information about a region, and ability to resolve an -// endpoint from the context of a region, given a service. -type Region struct { - id, desc string - p *partition -} - -// ID returns the region's identifier. -func (r Region) ID() string { return r.id } - -// ResolveEndpoint resolves an endpoint from the context of the region given -// a service. See Partition.EndpointFor for usage and errors that can be returned. -func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return r.p.EndpointFor(service, r.id, opts...) -} - -// Services returns a list of all services that are known to be in this region. -func (r Region) Services() map[string]Service { - ss := map[string]Service{} - for id, s := range r.p.Services { - if _, ok := s.Endpoints[r.id]; ok { - ss[id] = Service{ - id: id, - p: r.p, - } - } - } - - return ss -} - -// A Service provides information about a service, and ability to resolve an -// endpoint from the context of a service, given a region. -type Service struct { - id string - p *partition -} - -// ID returns the identifier for the service. -func (s Service) ID() string { return s.id } - -// ResolveEndpoint resolves an endpoint from the context of a service given -// a region. See Partition.EndpointFor for usage and errors that can be returned. -func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return s.p.EndpointFor(s.id, region, opts...) -} - -// Regions returns a map of Regions that the service is present in. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Regions() map[string]Region { - rs := map[string]Region{} - for id := range s.p.Services[s.id].Endpoints { - if _, ok := s.p.Regions[id]; ok { - rs[id] = Region{ - id: id, - p: s.p, - } - } - } - - return rs -} - -// Endpoints returns a map of Endpoints indexed by their ID for all known -// endpoints for a service. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Endpoints() map[string]Endpoint { - es := map[string]Endpoint{} - for id := range s.p.Services[s.id].Endpoints { - es[id] = Endpoint{ - id: id, - serviceID: s.id, - p: s.p, - } - } - - return es -} - -// A Endpoint provides information about endpoints, and provides the ability -// to resolve that endpoint for the service, and the region the endpoint -// represents. -type Endpoint struct { - id string - serviceID string - p *partition -} - -// ID returns the identifier for an endpoint. -func (e Endpoint) ID() string { return e.id } - -// ServiceID returns the identifier the endpoint belongs to. -func (e Endpoint) ServiceID() string { return e.serviceID } - -// ResolveEndpoint resolves an endpoint from the context of a service and -// region the endpoint represents. See Partition.EndpointFor for usage and -// errors that can be returned. -func (e Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { - return e.p.EndpointFor(e.serviceID, e.id, opts...) -} - -// A ResolvedEndpoint is an endpoint that has been resolved based on a partition -// service, and region. -type ResolvedEndpoint struct { - // The endpoint URL - URL string - - // The region that should be used for signing requests. - SigningRegion string - - // The service name that should be used for signing requests. - SigningName string - - // The signing method that should be used for signing requests. - SigningMethod string -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError awserr.Error - -// A EndpointNotFoundError is returned when in StrictMatching mode, and the -// endpoint for the service and region cannot be found in any of the partitions. -type EndpointNotFoundError struct { - awsError - Partition string - Service string - Region string -} - -// A UnknownServiceError is returned when the service does not resolve to an -// endpoint. Includes a list of all known services for the partition. Returned -// when a partition does not support the service. -type UnknownServiceError struct { - awsError - Partition string - Service string - Known []string -} - -// NewUnknownServiceError builds and returns UnknownServiceError. -func NewUnknownServiceError(p, s string, known []string) UnknownServiceError { - return UnknownServiceError{ - awsError: awserr.New("UnknownServiceError", - "could not resolve endpoint for unknown service", nil), - Partition: p, - Service: s, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownServiceError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q", - e.Partition, e.Service) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownServiceError) String() string { - return e.Error() -} - -// A UnknownEndpointError is returned when in StrictMatching mode and the -// service is valid, but the region does not resolve to an endpoint. Includes -// a list of all known endpoints for the service. -type UnknownEndpointError struct { - awsError - Partition string - Service string - Region string - Known []string -} - -// NewUnknownEndpointError builds and returns UnknownEndpointError. -func NewUnknownEndpointError(p, s, r string, known []string) UnknownEndpointError { - return UnknownEndpointError{ - awsError: awserr.New("UnknownEndpointError", - "could not resolve endpoint", nil), - Partition: p, - Service: s, - Region: r, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q, region: %q", - e.Partition, e.Service, e.Region) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) String() string { - return e.Error() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go deleted file mode 100644 index 13d968a249..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ /dev/null @@ -1,303 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -type partitions []partition - -func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - var opt Options - opt.Set(opts...) - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(service, region, opt.StrictMatching) { - continue - } - - return ps[i].EndpointFor(service, region, opts...) - } - - // If loose matching fallback to first partition format to use - // when resolving the endpoint. - if !opt.StrictMatching && len(ps) > 0 { - return ps[0].EndpointFor(service, region, opts...) - } - - return ResolvedEndpoint{}, NewUnknownEndpointError("all partitions", service, region, []string{}) -} - -// Partitions satisfies the EnumPartitions interface and returns a list -// of Partitions representing each partition represented in the SDK's -// endpoints model. -func (ps partitions) Partitions() []Partition { - parts := make([]Partition, 0, len(ps)) - for i := 0; i < len(ps); i++ { - parts = append(parts, ps[i].Partition()) - } - - return parts -} - -type partition struct { - ID string `json:"partition"` - Name string `json:"partitionName"` - DNSSuffix string `json:"dnsSuffix"` - RegionRegex regionRegex `json:"regionRegex"` - Defaults endpoint `json:"defaults"` - Regions regions `json:"regions"` - Services services `json:"services"` -} - -func (p partition) Partition() Partition { - return Partition{ - id: p.ID, - p: &p, - } -} - -func (p partition) canResolveEndpoint(service, region string, strictMatch bool) bool { - s, hasService := p.Services[service] - _, hasEndpoint := s.Endpoints[region] - - if hasEndpoint && hasService { - return true - } - - if strictMatch { - return false - } - - return p.RegionRegex.MatchString(region) -} - -func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (resolved ResolvedEndpoint, err error) { - var opt Options - opt.Set(opts...) - - s, hasService := p.Services[service] - if !(hasService || opt.ResolveUnknownService) { - // Only return error if the resolver will not fallback to creating - // endpoint based on service endpoint ID passed in. - return resolved, NewUnknownServiceError(p.ID, service, serviceList(p.Services)) - } - - e, hasEndpoint := s.endpointForRegion(region) - if !hasEndpoint && opt.StrictMatching { - return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(s.Endpoints)) - } - - defs := []endpoint{p.Defaults, s.Defaults} - return e.resolve(service, region, p.DNSSuffix, defs, opt), nil -} - -func serviceList(ss services) []string { - list := make([]string, 0, len(ss)) - for k := range ss { - list = append(list, k) - } - return list -} -func endpointList(es endpoints) []string { - list := make([]string, 0, len(es)) - for k := range es { - list = append(list, k) - } - return list -} - -type regionRegex struct { - *regexp.Regexp -} - -func (rr *regionRegex) UnmarshalJSON(b []byte) (err error) { - // Strip leading and trailing quotes - regex, err := strconv.Unquote(string(b)) - if err != nil { - return fmt.Errorf("unable to strip quotes from regex, %v", err) - } - - rr.Regexp, err = regexp.Compile(regex) - if err != nil { - return fmt.Errorf("unable to unmarshal region regex, %v", err) - } - return nil -} - -type regions map[string]region - -type region struct { - Description string `json:"description"` -} - -type services map[string]service - -type service struct { - PartitionEndpoint string `json:"partitionEndpoint"` - IsRegionalized boxedBool `json:"isRegionalized,omitempty"` - Defaults endpoint `json:"defaults"` - Endpoints endpoints `json:"endpoints"` -} - -func (s *service) endpointForRegion(region string) (endpoint, bool) { - if s.IsRegionalized == boxedFalse { - return s.Endpoints[s.PartitionEndpoint], region == s.PartitionEndpoint - } - - if e, ok := s.Endpoints[region]; ok { - return e, true - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return endpoint{}, false -} - -type endpoints map[string]endpoint - -type endpoint struct { - Hostname string `json:"hostname"` - Protocols []string `json:"protocols"` - CredentialScope credentialScope `json:"credentialScope"` - - // Custom fields not modeled - HasDualStack boxedBool `json:"-"` - DualStackHostname string `json:"-"` - - // Signature Version not used - SignatureVersions []string `json:"signatureVersions"` - - // SSLCommonName not used. - SSLCommonName string `json:"sslCommonName"` -} - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "v2"} -) - -func getByPriority(s []string, p []string, def string) string { - if len(s) == 0 { - return def - } - - for i := 0; i < len(p); i++ { - for j := 0; j < len(s); j++ { - if s[j] == p[i] { - return s[j] - } - } - } - - return s[0] -} - -func (e endpoint) resolve(service, region, dnsSuffix string, defs []endpoint, opts Options) ResolvedEndpoint { - var merged endpoint - for _, def := range defs { - merged.mergeIn(def) - } - merged.mergeIn(e) - e = merged - - hostname := e.Hostname - - // Offset the hostname for dualstack if enabled - if opts.UseDualStack && e.HasDualStack == boxedTrue { - hostname = e.DualStackHostname - } - - u := strings.Replace(hostname, "{service}", service, 1) - u = strings.Replace(u, "{region}", region, 1) - u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) - - scheme := getEndpointScheme(e.Protocols, opts.DisableSSL) - u = fmt.Sprintf("%s://%s", scheme, u) - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - signingName := e.CredentialScope.Service - if len(signingName) == 0 { - signingName = service - } - - return ResolvedEndpoint{ - URL: u, - SigningRegion: signingRegion, - SigningName: signingName, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } -} - -func getEndpointScheme(protocols []string, disableSSL bool) string { - if disableSSL { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func (e *endpoint) mergeIn(other endpoint) { - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - if len(other.CredentialScope.Region) > 0 { - e.CredentialScope.Region = other.CredentialScope.Region - } - if len(other.CredentialScope.Service) > 0 { - e.CredentialScope.Service = other.CredentialScope.Service - } - if len(other.SSLCommonName) > 0 { - e.SSLCommonName = other.SSLCommonName - } - if other.HasDualStack != boxedBoolUnset { - e.HasDualStack = other.HasDualStack - } - if len(other.DualStackHostname) > 0 { - e.DualStackHostname = other.DualStackHostname - } -} - -type credentialScope struct { - Region string `json:"region"` - Service string `json:"service"` -} - -type boxedBool int - -func (b *boxedBool) UnmarshalJSON(buf []byte) error { - v, err := strconv.ParseBool(string(buf)) - if err != nil { - return err - } - - if v { - *b = boxedTrue - } else { - *b = boxedFalse - } - - return nil -} - -const ( - boxedBoolUnset boxedBool = iota - boxedFalse - boxedTrue -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go deleted file mode 100644 index 05e92df22a..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build codegen - -package endpoints - -import ( - "fmt" - "io" - "reflect" - "strings" - "text/template" - "unicode" -) - -// A CodeGenOptions are the options for code generating the endpoints into -// Go code from the endpoints model definition. -type CodeGenOptions struct { - // Options for how the model will be decoded. - DecodeModelOptions DecodeModelOptions -} - -// Set combines all of the option functions together -func (d *CodeGenOptions) Set(optFns ...func(*CodeGenOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// CodeGenModel given a endpoints model file will decode it and attempt to -// generate Go code from the model definition. Error will be returned if -// the code is unable to be generated, or decoded. -func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error { - var opts CodeGenOptions - opts.Set(optFns...) - - resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) { - *d = opts.DecodeModelOptions - }) - if err != nil { - return err - } - - tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl)) - if err := tmpl.ExecuteTemplate(outFile, "defaults", resolver); err != nil { - return fmt.Errorf("failed to execute template, %v", err) - } - - return nil -} - -func toSymbol(v string) string { - out := []rune{} - for _, c := range strings.Title(v) { - if !(unicode.IsNumber(c) || unicode.IsLetter(c)) { - continue - } - - out = append(out, c) - } - - return string(out) -} - -func quoteString(v string) string { - return fmt.Sprintf("%q", v) -} - -func regionConstName(p, r string) string { - return toSymbol(p) + toSymbol(r) -} - -func partitionGetter(id string) string { - return fmt.Sprintf("%sPartition", toSymbol(id)) -} - -func partitionVarName(id string) string { - return fmt.Sprintf("%sPartition", strings.ToLower(toSymbol(id))) -} - -func listPartitionNames(ps partitions) string { - names := []string{} - switch len(ps) { - case 1: - return ps[0].Name - case 2: - return fmt.Sprintf("%s and %s", ps[0].Name, ps[1].Name) - default: - for i, p := range ps { - if i == len(ps)-1 { - names = append(names, "and "+p.Name) - } else { - names = append(names, p.Name) - } - } - return strings.Join(names, ", ") - } -} - -func boxedBoolIfSet(msg string, v boxedBool) string { - switch v { - case boxedTrue: - return fmt.Sprintf(msg, "boxedTrue") - case boxedFalse: - return fmt.Sprintf(msg, "boxedFalse") - default: - return "" - } -} - -func stringIfSet(msg, v string) string { - if len(v) == 0 { - return "" - } - - return fmt.Sprintf(msg, v) -} - -func stringSliceIfSet(msg string, vs []string) string { - if len(vs) == 0 { - return "" - } - - names := []string{} - for _, v := range vs { - names = append(names, `"`+v+`"`) - } - - return fmt.Sprintf(msg, strings.Join(names, ",")) -} - -func endpointIsSet(v endpoint) bool { - return !reflect.DeepEqual(v, endpoint{}) -} - -func serviceSet(ps partitions) map[string]struct{} { - set := map[string]struct{}{} - for _, p := range ps { - for id := range p.Services { - set[id] = struct{}{} - } - } - - return set -} - -var funcMap = template.FuncMap{ - "ToSymbol": toSymbol, - "QuoteString": quoteString, - "RegionConst": regionConstName, - "PartitionGetter": partitionGetter, - "PartitionVarName": partitionVarName, - "ListPartitionNames": listPartitionNames, - "BoxedBoolIfSet": boxedBoolIfSet, - "StringIfSet": stringIfSet, - "StringSliceIfSet": stringSliceIfSet, - "EndpointIsSet": endpointIsSet, - "ServicesSet": serviceSet, -} - -const v3Tmpl = ` -{{ define "defaults" -}} -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - - {{ template "partition consts" . }} - - {{ range $_, $partition := . }} - {{ template "partition region consts" $partition }} - {{ end }} - - {{ template "service consts" . }} - - {{ template "endpoint resolvers" . }} -{{- end }} - -{{ define "partition consts" }} - // Partition identifiers - const ( - {{ range $_, $p := . -}} - {{ ToSymbol $p.ID }}PartitionID = {{ QuoteString $p.ID }} // {{ $p.Name }} partition. - {{ end -}} - ) -{{- end }} - -{{ define "partition region consts" }} - // {{ .Name }} partition's regions. - const ( - {{ range $id, $region := .Regions -}} - {{ ToSymbol $id }}RegionID = {{ QuoteString $id }} // {{ $region.Description }}. - {{ end -}} - ) -{{- end }} - -{{ define "service consts" }} - // Service identifiers - const ( - {{ $serviceSet := ServicesSet . -}} - {{ range $id, $_ := $serviceSet -}} - {{ ToSymbol $id }}ServiceID = {{ QuoteString $id }} // {{ ToSymbol $id }}. - {{ end -}} - ) -{{- end }} - -{{ define "endpoint resolvers" }} - // DefaultResolver returns an Endpoint resolver that will be able - // to resolve endpoints for: {{ ListPartitionNames . }}. - // - // Use DefaultPartitions() to get the list of the default partitions. - func DefaultResolver() Resolver { - return defaultPartitions - } - - // DefaultPartitions returns a list of the partitions the SDK is bundled - // with. The available partitions are: {{ ListPartitionNames . }}. - // - // partitions := endpoints.DefaultPartitions - // for _, p := range partitions { - // // ... inspect partitions - // } - func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() - } - - var defaultPartitions = partitions{ - {{ range $_, $partition := . -}} - {{ PartitionVarName $partition.ID }}, - {{ end }} - } - - {{ range $_, $partition := . -}} - {{ $name := PartitionGetter $partition.ID -}} - // {{ $name }} returns the Resolver for {{ $partition.Name }}. - func {{ $name }}() Partition { - return {{ PartitionVarName $partition.ID }}.Partition() - } - var {{ PartitionVarName $partition.ID }} = {{ template "gocode Partition" $partition }} - {{ end }} -{{ end }} - -{{ define "default partitions" }} - func DefaultPartitions() []Partition { - return []partition{ - {{ range $_, $partition := . -}} - // {{ ToSymbol $partition.ID}}Partition(), - {{ end }} - } - } -{{ end }} - -{{ define "gocode Partition" -}} -partition{ - {{ StringIfSet "ID: %q,\n" .ID -}} - {{ StringIfSet "Name: %q,\n" .Name -}} - {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} - RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }}, - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults }}, - {{- end }} - Regions: {{ template "gocode Regions" .Regions }}, - Services: {{ template "gocode Services" .Services }}, -} -{{- end }} - -{{ define "gocode RegionRegex" -}} -regionRegex{ - Regexp: func() *regexp.Regexp{ - reg, _ := regexp.Compile({{ QuoteString .Regexp.String }}) - return reg - }(), -} -{{- end }} - -{{ define "gocode Regions" -}} -regions{ - {{ range $id, $region := . -}} - "{{ $id }}": {{ template "gocode Region" $region }}, - {{ end -}} -} -{{- end }} - -{{ define "gocode Region" -}} -region{ - {{ StringIfSet "Description: %q,\n" .Description -}} -} -{{- end }} - -{{ define "gocode Services" -}} -services{ - {{ range $id, $service := . -}} - "{{ $id }}": {{ template "gocode Service" $service }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Service" -}} -service{ - {{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}} - {{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}} - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults -}}, - {{- end }} - {{ if .Endpoints -}} - Endpoints: {{ template "gocode Endpoints" .Endpoints }}, - {{- end }} -} -{{- end }} - -{{ define "gocode Endpoints" -}} -endpoints{ - {{ range $id, $endpoint := . -}} - "{{ $id }}": {{ template "gocode Endpoint" $endpoint }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Endpoint" -}} -endpoint{ - {{ StringIfSet "Hostname: %q,\n" .Hostname -}} - {{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}} - {{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}} - {{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}} - {{ if or .CredentialScope.Region .CredentialScope.Service -}} - CredentialScope: credentialScope{ - {{ StringIfSet "Region: %q,\n" .CredentialScope.Region -}} - {{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}} - }, - {{- end }} - {{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}} - {{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}} - -} -{{- end }} -` diff --git a/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/aws/aws-sdk-go/aws/errors.go deleted file mode 100644 index 5766361686..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package aws - -import "github.com/aws/aws-sdk-go/aws/awserr" - -var ( - // ErrMissingRegion is an error that is returned if region configuration is - // not found. - // - // @readonly - ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) - - // ErrMissingEndpoint is an error that is returned if an endpoint cannot be - // resolved for a service. - // - // @readonly - ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go deleted file mode 100644 index 91a6f277a7..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go +++ /dev/null @@ -1,12 +0,0 @@ -package aws - -// JSONValue is a representation of a grab bag type that will be marshaled -// into a json string. This type can be used just like any other map. -// -// Example: -// -// values := aws.JSONValue{ -// "Foo": "Bar", -// } -// values["Baz"] = "Qux" -type JSONValue map[string]interface{} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/logger.go deleted file mode 100644 index 3babb5abdb..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/logger.go +++ /dev/null @@ -1,112 +0,0 @@ -package aws - -import ( - "log" - "os" -) - -// A LogLevelType defines the level logging should be performed at. Used to instruct -// the SDK which statements should be logged. -type LogLevelType uint - -// LogLevel returns the pointer to a LogLevel. Should be used to workaround -// not being able to take the address of a non-composite literal. -func LogLevel(l LogLevelType) *LogLevelType { - return &l -} - -// Value returns the LogLevel value or the default value LogOff if the LogLevel -// is nil. Safe to use on nil value LogLevelTypes. -func (l *LogLevelType) Value() LogLevelType { - if l != nil { - return *l - } - return LogOff -} - -// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be -// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If -// LogLevel is nil, will default to LogOff comparison. -func (l *LogLevelType) Matches(v LogLevelType) bool { - c := l.Value() - return c&v == v -} - -// AtLeast returns true if this LogLevel is at least high enough to satisfies v. -// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default -// to LogOff comparison. -func (l *LogLevelType) AtLeast(v LogLevelType) bool { - c := l.Value() - return c >= v -} - -const ( - // LogOff states that no logging should be performed by the SDK. This is the - // default state of the SDK, and should be use to disable all logging. - LogOff LogLevelType = iota * 0x1000 - - // LogDebug state that debug output should be logged by the SDK. This should - // be used to inspect request made and responses received. - LogDebug -) - -// Debug Logging Sub Levels -const ( - // LogDebugWithSigning states that the SDK should log request signing and - // presigning events. This should be used to log the signing details of - // requests for debugging. Will also enable LogDebug. - LogDebugWithSigning LogLevelType = LogDebug | (1 << iota) - - // LogDebugWithHTTPBody states the SDK should log HTTP request and response - // HTTP bodys in addition to the headers and path. This should be used to - // see the body content of requests and responses made while using the SDK - // Will also enable LogDebug. - LogDebugWithHTTPBody - - // LogDebugWithRequestRetries states the SDK should log when service requests will - // be retried. This should be used to log when you want to log when service - // requests are being retried. Will also enable LogDebug. - LogDebugWithRequestRetries - - // LogDebugWithRequestErrors states the SDK should log when service requests fail - // to build, send, validate, or unmarshal. - LogDebugWithRequestErrors -) - -// A Logger is a minimalistic interface for the SDK to log messages to. Should -// be used to provide custom logging writers for the SDK to use. -type Logger interface { - Log(...interface{}) -} - -// A LoggerFunc is a convenience type to convert a function taking a variadic -// list of arguments and wrap it so the Logger interface can be used. -// -// Example: -// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { -// fmt.Fprintln(os.Stdout, args...) -// })}) -type LoggerFunc func(...interface{}) - -// Log calls the wrapped function with the arguments provided -func (f LoggerFunc) Log(args ...interface{}) { - f(args...) -} - -// NewDefaultLogger returns a Logger which will write log messages to stdout, and -// use same formatting runes as the stdlib log.Logger -func NewDefaultLogger() Logger { - return &defaultLogger{ - logger: log.New(os.Stdout, "", log.LstdFlags), - } -} - -// A defaultLogger provides a minimalistic logger satisfying the Logger interface. -type defaultLogger struct { - logger *log.Logger -} - -// Log logs the parameters to the stdlib logger. See log.Println. -func (l defaultLogger) Log(args ...interface{}) { - l.logger.Println(args...) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go deleted file mode 100644 index 271da432ce..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !appengine,!plan9 - -package request - -import ( - "net" - "os" - "syscall" -) - -func isErrConnectionReset(err error) bool { - if opErr, ok := err.(*net.OpError); ok { - if sysErr, ok := opErr.Err.(*os.SyscallError); ok { - return sysErr.Err == syscall.ECONNRESET - } - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go deleted file mode 100644 index daf9eca437..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine plan9 - -package request - -import ( - "strings" -) - -func isErrConnectionReset(err error) bool { - return strings.Contains(err.Error(), "connection reset") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go deleted file mode 100644 index 802ac88ad5..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ /dev/null @@ -1,256 +0,0 @@ -package request - -import ( - "fmt" - "strings" -) - -// A Handlers provides a collection of request handlers for various -// stages of handling requests. -type Handlers struct { - Validate HandlerList - Build HandlerList - Sign HandlerList - Send HandlerList - ValidateResponse HandlerList - Unmarshal HandlerList - UnmarshalMeta HandlerList - UnmarshalError HandlerList - Retry HandlerList - AfterRetry HandlerList - Complete HandlerList -} - -// Copy returns of this handler's lists. -func (h *Handlers) Copy() Handlers { - return Handlers{ - Validate: h.Validate.copy(), - Build: h.Build.copy(), - Sign: h.Sign.copy(), - Send: h.Send.copy(), - ValidateResponse: h.ValidateResponse.copy(), - Unmarshal: h.Unmarshal.copy(), - UnmarshalError: h.UnmarshalError.copy(), - UnmarshalMeta: h.UnmarshalMeta.copy(), - Retry: h.Retry.copy(), - AfterRetry: h.AfterRetry.copy(), - Complete: h.Complete.copy(), - } -} - -// Clear removes callback functions for all handlers -func (h *Handlers) Clear() { - h.Validate.Clear() - h.Build.Clear() - h.Send.Clear() - h.Sign.Clear() - h.Unmarshal.Clear() - h.UnmarshalMeta.Clear() - h.UnmarshalError.Clear() - h.ValidateResponse.Clear() - h.Retry.Clear() - h.AfterRetry.Clear() - h.Complete.Clear() -} - -// A HandlerListRunItem represents an entry in the HandlerList which -// is being run. -type HandlerListRunItem struct { - Index int - Handler NamedHandler - Request *Request -} - -// A HandlerList manages zero or more handlers in a list. -type HandlerList struct { - list []NamedHandler - - // Called after each request handler in the list is called. If set - // and the func returns true the HandlerList will continue to iterate - // over the request handlers. If false is returned the HandlerList - // will stop iterating. - // - // Should be used if extra logic to be performed between each handler - // in the list. This can be used to terminate a list's iteration - // based on a condition such as error like, HandlerListStopOnError. - // Or for logging like HandlerListLogItem. - AfterEachFn func(item HandlerListRunItem) bool -} - -// A NamedHandler is a struct that contains a name and function callback. -type NamedHandler struct { - Name string - Fn func(*Request) -} - -// copy creates a copy of the handler list. -func (l *HandlerList) copy() HandlerList { - n := HandlerList{ - AfterEachFn: l.AfterEachFn, - } - if len(l.list) == 0 { - return n - } - - n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) - return n -} - -// Clear clears the handler list. -func (l *HandlerList) Clear() { - l.list = l.list[0:0] -} - -// Len returns the number of handlers in the list. -func (l *HandlerList) Len() int { - return len(l.list) -} - -// PushBack pushes handler f to the back of the handler list. -func (l *HandlerList) PushBack(f func(*Request)) { - l.PushBackNamed(NamedHandler{"__anonymous", f}) -} - -// PushBackNamed pushes named handler f to the back of the handler list. -func (l *HandlerList) PushBackNamed(n NamedHandler) { - if cap(l.list) == 0 { - l.list = make([]NamedHandler, 0, 5) - } - l.list = append(l.list, n) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.PushFrontNamed(NamedHandler{"__anonymous", f}) -} - -// PushFrontNamed pushes named handler f to the front of the handler list. -func (l *HandlerList) PushFrontNamed(n NamedHandler) { - if cap(l.list) == len(l.list) { - // Allocating new list required - l.list = append([]NamedHandler{n}, l.list...) - } else { - // Enough room to prepend into list. - l.list = append(l.list, NamedHandler{}) - copy(l.list[1:], l.list) - l.list[0] = n - } -} - -// Remove removes a NamedHandler n -func (l *HandlerList) Remove(n NamedHandler) { - l.RemoveByName(n.Name) -} - -// RemoveByName removes a NamedHandler by name. -func (l *HandlerList) RemoveByName(name string) { - for i := 0; i < len(l.list); i++ { - m := l.list[i] - if m.Name == name { - // Shift array preventing creating new arrays - copy(l.list[i:], l.list[i+1:]) - l.list[len(l.list)-1] = NamedHandler{} - l.list = l.list[:len(l.list)-1] - - // decrement list so next check to length is correct - i-- - } - } -} - -// SwapNamed will swap out any existing handlers with the same name as the -// passed in NamedHandler returning true if handlers were swapped. False is -// returned otherwise. -func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == n.Name { - l.list[i].Fn = n.Fn - swapped = true - } - } - - return swapped -} - -// SetBackNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the end of the list. -func (l *HandlerList) SetBackNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushBackNamed(n) - } -} - -// SetFrontNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the beginning of -// the list. -func (l *HandlerList) SetFrontNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushFrontNamed(n) - } -} - -// Run executes all handlers in the list with a given request object. -func (l *HandlerList) Run(r *Request) { - for i, h := range l.list { - h.Fn(r) - item := HandlerListRunItem{ - Index: i, Handler: h, Request: r, - } - if l.AfterEachFn != nil && !l.AfterEachFn(item) { - return - } - } -} - -// HandlerListLogItem logs the request handler and the state of the -// request's Error value. Always returns true to continue iterating -// request handlers in a HandlerList. -func HandlerListLogItem(item HandlerListRunItem) bool { - if item.Request.Config.Logger == nil { - return true - } - item.Request.Config.Logger.Log("DEBUG: RequestHandler", - item.Index, item.Handler.Name, item.Request.Error) - - return true -} - -// HandlerListStopOnError returns false to stop the HandlerList iterating -// over request handlers if Request.Error is not nil. True otherwise -// to continue iterating. -func HandlerListStopOnError(item HandlerListRunItem) bool { - return item.Request.Error == nil -} - -// WithAppendUserAgent will add a string to the user agent prefixed with a -// single white space. -func WithAppendUserAgent(s string) Option { - return func(r *Request) { - r.Handlers.Build.PushBack(func(r2 *Request) { - AddToUserAgent(r, s) - }) - } -} - -// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request -// header. If the extra parameters are provided they will be added as metadata to the -// name/version pair resulting in the following format. -// "name/version (extra0; extra1; ...)" -// The user agent part will be concatenated with this current request's user agent string. -func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) { - ua := fmt.Sprintf("%s/%s", name, version) - if len(extra) > 0 { - ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; ")) - } - return func(r *Request) { - AddToUserAgent(r, ua) - } -} - -// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header. -// The input string will be concatenated with the current request's user agent string. -func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) { - return func(r *Request) { - AddToUserAgent(r, s) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go deleted file mode 100644 index 79f79602b0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package request - -import ( - "io" - "net/http" - "net/url" -) - -func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request { - req := new(http.Request) - *req = *r - req.URL = &url.URL{} - *req.URL = *r.URL - req.Body = body - - req.Header = http.Header{} - for k, v := range r.Header { - for _, vv := range v { - req.Header.Add(k, vv) - } - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go deleted file mode 100644 index 02f07f4a46..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go +++ /dev/null @@ -1,58 +0,0 @@ -package request - -import ( - "io" - "sync" -) - -// offsetReader is a thread-safe io.ReadCloser to prevent racing -// with retrying requests -type offsetReader struct { - buf io.ReadSeeker - lock sync.Mutex - closed bool -} - -func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader { - reader := &offsetReader{} - buf.Seek(offset, 0) - - reader.buf = buf - return reader -} - -// Close will close the instance of the offset reader's access to -// the underlying io.ReadSeeker. -func (o *offsetReader) Close() error { - o.lock.Lock() - defer o.lock.Unlock() - o.closed = true - return nil -} - -// Read is a thread-safe read of the underlying io.ReadSeeker -func (o *offsetReader) Read(p []byte) (int, error) { - o.lock.Lock() - defer o.lock.Unlock() - - if o.closed { - return 0, io.EOF - } - - return o.buf.Read(p) -} - -// Seek is a thread-safe seeking operation. -func (o *offsetReader) Seek(offset int64, whence int) (int64, error) { - o.lock.Lock() - defer o.lock.Unlock() - - return o.buf.Seek(offset, whence) -} - -// CloseAndCopy will return a new offsetReader with a copy of the old buffer -// and close the old buffer. -func (o *offsetReader) CloseAndCopy(offset int64) *offsetReader { - o.Close() - return newOffsetReader(o.buf, offset) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go deleted file mode 100644 index 299dc379d1..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ /dev/null @@ -1,575 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - "io" - "net" - "net/http" - "net/url" - "reflect" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client/metadata" -) - -const ( - // ErrCodeSerialization is the serialization error code that is received - // during protocol unmarshaling. - ErrCodeSerialization = "SerializationError" - - // ErrCodeRead is an error that is returned during HTTP reads. - ErrCodeRead = "ReadError" - - // ErrCodeResponseTimeout is the connection timeout error that is recieved - // during body reads. - ErrCodeResponseTimeout = "ResponseTimeout" - - // CanceledErrorCode is the error code that will be returned by an - // API request that was canceled. Requests given a aws.Context may - // return this error when canceled. - CanceledErrorCode = "RequestCanceled" -) - -// A Request is the service request to be made. -type Request struct { - Config aws.Config - ClientInfo metadata.ClientInfo - Handlers Handlers - - Retryer - Time time.Time - ExpireTime time.Duration - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - BodyStart int64 // offset from beginning of Body that the request body starts - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount int - Retryable *bool - RetryDelay time.Duration - NotHoist bool - SignedHeaderVals http.Header - LastSignedAt time.Time - DisableFollowRedirects bool - - context aws.Context - - built bool - - // Need to persist an intermediate body between the input Body and HTTP - // request body because the HTTP Client's transport can maintain a reference - // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and wrap the input Body for each HTTP request. - safeBody *offsetReader -} - -// An Operation is the service API operation to be made. -type Operation struct { - Name string - HTTPMethod string - HTTPPath string - *Paginator - - BeforePresignFn func(r *Request) error -} - -// New returns a new Request pointer for the service API -// operation and parameters. -// -// Params is any value of input parameters to be the request payload. -// Data is pointer value to an object which the request's response -// payload will be deserialized to. -func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, - retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { - - method := operation.HTTPMethod - if method == "" { - method = "POST" - } - - httpReq, _ := http.NewRequest(method, "", nil) - - var err error - httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath) - if err != nil { - httpReq.URL = &url.URL{} - err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) - } - - r := &Request{ - Config: cfg, - ClientInfo: clientInfo, - Handlers: handlers.Copy(), - - Retryer: retryer, - Time: time.Now(), - ExpireTime: 0, - Operation: operation, - HTTPRequest: httpReq, - Body: nil, - Params: params, - Error: err, - Data: data, - } - r.SetBufferBody([]byte{}) - - return r -} - -// A Option is a functional option that can augment or modify a request when -// using a WithContext API operation method. -type Option func(*Request) - -// WithGetResponseHeader builds a request Option which will retrieve a single -// header value from the HTTP Response. If there are multiple values for the -// header key use WithGetResponseHeaders instead to access the http.Header -// map directly. The passed in val pointer must be non-nil. -// -// This Option can be used multiple times with a single API operation. -// -// var id2, versionID string -// svc.PutObjectWithContext(ctx, params, -// request.WithGetResponseHeader("x-amz-id-2", &id2), -// request.WithGetResponseHeader("x-amz-version-id", &versionID), -// ) -func WithGetResponseHeader(key string, val *string) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *val = req.HTTPResponse.Header.Get(key) - }) - } -} - -// WithGetResponseHeaders builds a request Option which will retrieve the -// headers from the HTTP response and assign them to the passed in headers -// variable. The passed in headers pointer must be non-nil. -// -// var headers http.Header -// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) -func WithGetResponseHeaders(headers *http.Header) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *headers = req.HTTPResponse.Header - }) - } -} - -// WithLogLevel is a request option that will set the request to use a specific -// log level when the request is made. -// -// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) -func WithLogLevel(l aws.LogLevelType) Option { - return func(r *Request) { - r.Config.LogLevel = aws.LogLevel(l) - } -} - -// ApplyOptions will apply each option to the request calling them in the order -// the were provided. -func (r *Request) ApplyOptions(opts ...Option) { - for _, opt := range opts { - opt(r) - } -} - -// Context will always returns a non-nil context. If Request does not have a -// context aws.BackgroundContext will be returned. -func (r *Request) Context() aws.Context { - if r.context != nil { - return r.context - } - return aws.BackgroundContext() -} - -// SetContext adds a Context to the current request that can be used to cancel -// a in-flight request. The Context value must not be nil, or this method will -// panic. -// -// Unlike http.Request.WithContext, SetContext does not return a copy of the -// Request. It is not safe to use use a single Request value for multiple -// requests. A new Request should be created for each API operation request. -// -// Go 1.6 and below: -// The http.Request's Cancel field will be set to the Done() value of -// the context. This will overwrite the Cancel field's value. -// -// Go 1.7 and above: -// The http.Request.WithContext will be used to set the context on the underlying -// http.Request. This will create a shallow copy of the http.Request. The SDK -// may create sub contexts in the future for nested requests such as retries. -func (r *Request) SetContext(ctx aws.Context) { - if ctx == nil { - panic("context cannot be nil") - } - setRequestContext(r, ctx) -} - -// WillRetry returns if the request's can be retried. -func (r *Request) WillRetry() bool { - return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() -} - -// ParamsFilled returns if the request's parameters have been populated -// and the parameters are valid. False is returned if no parameters are -// provided or invalid. -func (r *Request) ParamsFilled() bool { - return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() -} - -// DataFilled returns true if the request's data for response deserialization -// target has been set and is a valid. False is returned if data is not -// set, or is invalid. -func (r *Request) DataFilled() bool { - return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid() -} - -// SetBufferBody will set the request's body bytes that will be sent to -// the service API. -func (r *Request) SetBufferBody(buf []byte) { - r.SetReaderBody(bytes.NewReader(buf)) -} - -// SetStringBody sets the body of the request to be backed by a string. -func (r *Request) SetStringBody(s string) { - r.SetReaderBody(strings.NewReader(s)) -} - -// SetReaderBody will set the request's body reader. -func (r *Request) SetReaderBody(reader io.ReadSeeker) { - r.Body = reader - r.ResetBody() -} - -// Presign returns the request's signed URL. Error will be returned -// if the signing fails. -func (r *Request) Presign(expireTime time.Duration) (string, error) { - r.ExpireTime = expireTime - r.NotHoist = false - - if r.Operation.BeforePresignFn != nil { - r = r.copy() - err := r.Operation.BeforePresignFn(r) - if err != nil { - return "", err - } - } - - r.Sign() - if r.Error != nil { - return "", r.Error - } - return r.HTTPRequest.URL.String(), nil -} - -// PresignRequest behaves just like presign, but hoists all headers and signs them. -// Also returns the signed hash back to the user -func (r *Request) PresignRequest(expireTime time.Duration) (string, http.Header, error) { - r.ExpireTime = expireTime - r.NotHoist = true - r.Sign() - if r.Error != nil { - return "", nil, r.Error - } - return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil -} - -func debugLogReqError(r *Request, stage string, retrying bool, err error) { - if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { - return - } - - retryStr := "not retrying" - if retrying { - retryStr = "will retry" - } - - r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", - stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err)) -} - -// Build will build the request's object so it can be signed and sent -// to the service. Build will also validate all the request's parameters. -// Anny additional build Handlers set on this request will be run -// in the order they were set. -// -// The request will only be built once. Multiple calls to build will have -// no effect. -// -// If any Validate or Build errors occur the build will stop and the error -// which occurred will be returned. -func (r *Request) Build() error { - if !r.built { - r.Handlers.Validate.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Request", false, r.Error) - return r.Error - } - r.Handlers.Build.Run(r) - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - r.built = true - } - - return r.Error -} - -// Sign will sign the request returning error if errors are encountered. -// -// Send will build the request prior to signing. All Sign Handlers will -// be executed in the order they were set. -func (r *Request) Sign() error { - r.Build() - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - - r.Handlers.Sign.Run(r) - return r.Error -} - -func (r *Request) getNextRequestBody() (io.ReadCloser, error) { - if r.safeBody != nil { - r.safeBody.Close() - } - - r.safeBody = newOffsetReader(r.Body, r.BodyStart) - - // Go 1.8 tightened and clarified the rules code needs to use when building - // requests with the http package. Go 1.8 removed the automatic detection - // of if the Request.Body was empty, or actually had bytes in it. The SDK - // always sets the Request.Body even if it is empty and should not actually - // be sent. This is incorrect. - // - // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http - // client that the request really should be sent without a body. The - // Request.Body cannot be set to nil, which is preferable, because the - // field is exported and could introduce nil pointer dereferences for users - // of the SDK if they used that field. - // - // Related golang/go#18257 - l, err := computeBodyLength(r.Body) - if err != nil { - return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err) - } - - var body io.ReadCloser - if l == 0 { - body = NoBody - } else if l > 0 { - body = r.safeBody - } else { - // Hack to prevent sending bodies for methods where the body - // should be ignored by the server. Sending bodies on these - // methods without an associated ContentLength will cause the - // request to socket timeout because the server does not handle - // Transfer-Encoding: chunked bodies for these methods. - // - // This would only happen if a aws.ReaderSeekerCloser was used with - // a io.Reader that was not also an io.Seeker. - switch r.Operation.HTTPMethod { - case "GET", "HEAD", "DELETE": - body = NoBody - default: - body = r.safeBody - } - } - - return body, nil -} - -// Attempts to compute the length of the body of the reader using the -// io.Seeker interface. If the value is not seekable because of being -// a ReaderSeekerCloser without an unerlying Seeker -1 will be returned. -// If no error occurs the length of the body will be returned. -func computeBodyLength(r io.ReadSeeker) (int64, error) { - seekable := true - // Determine if the seeker is actually seekable. ReaderSeekerCloser - // hides the fact that a io.Readers might not actually be seekable. - switch v := r.(type) { - case aws.ReaderSeekerCloser: - seekable = v.IsSeeker() - case *aws.ReaderSeekerCloser: - seekable = v.IsSeeker() - } - if !seekable { - return -1, nil - } - - curOffset, err := r.Seek(0, 1) - if err != nil { - return 0, err - } - - endOffset, err := r.Seek(0, 2) - if err != nil { - return 0, err - } - - _, err = r.Seek(curOffset, 0) - if err != nil { - return 0, err - } - - return endOffset - curOffset, nil -} - -// GetBody will return an io.ReadSeeker of the Request's underlying -// input body with a concurrency safe wrapper. -func (r *Request) GetBody() io.ReadSeeker { - return r.safeBody -} - -// Send will send the request returning error if errors are encountered. -// -// Send will sign the request prior to sending. All Send Handlers will -// be executed in the order they were set. -// -// Canceling a request is non-deterministic. If a request has been canceled, -// then the transport will choose, randomly, one of the state channels during -// reads or getting the connection. -// -// readLoop() and getConn(req *Request, cm connectMethod) -// https://github.com/golang/go/blob/master/src/net/http/transport.go -// -// Send will not close the request.Request's body. -func (r *Request) Send() error { - defer func() { - // Regardless of success or failure of the request trigger the Complete - // request handlers. - r.Handlers.Complete.Run(r) - }() - - for { - if aws.BoolValue(r.Retryable) { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) - } - - // The previous http.Request will have a reference to the r.Body - // and the HTTP Client's Transport may still be reading from - // the request's body even though the Client's Do returned. - r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) - r.ResetBody() - - // Closing response body to ensure that no response body is leaked - // between retry attempts. - if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { - r.HTTPResponse.Body.Close() - } - } - - r.Sign() - if r.Error != nil { - return r.Error - } - - r.Retryable = nil - - r.Handlers.Send.Run(r) - if r.Error != nil { - if !shouldRetryCancel(r) { - return r.Error - } - - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Send Request", false, err) - return r.Error - } - debugLogReqError(r, "Send Request", true, err) - continue - } - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - err := r.Error - - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Response", false, err) - return r.Error - } - debugLogReqError(r, "Validate Response", true, err) - continue - } - - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Unmarshal Response", false, err) - return r.Error - } - debugLogReqError(r, "Unmarshal Response", true, err) - continue - } - - break - } - - return nil -} - -// copy will copy a request which will allow for local manipulation of the -// request. -func (r *Request) copy() *Request { - req := &Request{} - *req = *r - req.Handlers = r.Handlers.Copy() - op := *r.Operation - req.Operation = &op - return req -} - -// AddToUserAgent adds the string to the end of the request's current user agent. -func AddToUserAgent(r *Request, s string) { - curUA := r.HTTPRequest.Header.Get("User-Agent") - if len(curUA) > 0 { - s = curUA + " " + s - } - r.HTTPRequest.Header.Set("User-Agent", s) -} - -func shouldRetryCancel(r *Request) bool { - awsErr, ok := r.Error.(awserr.Error) - timeoutErr := false - errStr := r.Error.Error() - if ok { - if awsErr.Code() == CanceledErrorCode { - return false - } - err := awsErr.OrigErr() - netErr, netOK := err.(net.Error) - timeoutErr = netOK && netErr.Temporary() - if urlErr, ok := err.(*url.Error); !timeoutErr && ok { - errStr = urlErr.Err.Error() - } - } - - // There can be two types of canceled errors here. - // The first being a net.Error and the other being an error. - // If the request was timed out, we want to continue the retry - // process. Otherwise, return the canceled error. - return timeoutErr || - (errStr != "net/http: request canceled" && - errStr != "net/http: request canceled while waiting for connection") - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go deleted file mode 100644 index 869b97a1a0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build !go1.8 - -package request - -import "io" - -// NoBody is an io.ReadCloser with no bytes. Read always returns EOF -// and Close always returns nil. It can be used in an outgoing client -// request to explicitly signal that a request has zero bytes. -// An alternative, however, is to simply set Request.Body to nil. -// -// Copy of Go 1.8 NoBody type from net/http/http.go -type noBody struct{} - -func (noBody) Read([]byte) (int, error) { return 0, io.EOF } -func (noBody) Close() error { return nil } -func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } - -// NoBody is an empty reader that will trigger the Go HTTP client to not include -// and body in the HTTP request. -var NoBody = noBody{} - -// ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go deleted file mode 100644 index c32fc69bc5..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.8 - -package request - -import ( - "net/http" -) - -// NoBody is a http.NoBody reader instructing Go HTTP client to not include -// and body in the HTTP request. -var NoBody = http.NoBody - -// ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -// -// Will also set the Go 1.8's http.Request.GetBody member to allow retrying -// PUT/POST redirects. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body - r.HTTPRequest.GetBody = r.getNextRequestBody -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go deleted file mode 100644 index a7365cd1e4..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest = r.HTTPRequest.WithContext(ctx) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go deleted file mode 100644 index 307fa0705b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest.Cancel = ctx.Done() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go deleted file mode 100644 index 59de6736b6..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ /dev/null @@ -1,236 +0,0 @@ -package request - -import ( - "reflect" - "sync/atomic" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// A Pagination provides paginating of SDK API operations which are paginatable. -// Generally you should not use this type directly, but use the "Pages" API -// operations method to automatically perform pagination for you. Such as, -// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. -// -// Pagination differs from a Paginator type in that pagination is the type that -// does the pagination between API operations, and Paginator defines the -// configuration that will be used per page request. -// -// cont := true -// for p.Next() && cont { -// data := p.Page().(*s3.ListObjectsOutput) -// // process the page's data -// } -// return p.Err() -// -// See service client API operation Pages methods for examples how the SDK will -// use the Pagination type. -type Pagination struct { - // Function to return a Request value for each pagination request. - // Any configuration or handlers that need to be applied to the request - // prior to getting the next page should be done here before the request - // returned. - // - // NewRequest should always be built from the same API operations. It is - // undefined if different API operations are returned on subsequent calls. - NewRequest func() (*Request, error) - - started bool - nextTokens []interface{} - - err error - curPage interface{} -} - -// HasNextPage will return true if Pagination is able to determine that the API -// operation has additional pages. False will be returned if there are no more -// pages remaining. -// -// Will always return true if Next has not been called yet. -func (p *Pagination) HasNextPage() bool { - return !(p.started && len(p.nextTokens) == 0) -} - -// Err returns the error Pagination encountered when retrieving the next page. -func (p *Pagination) Err() error { - return p.err -} - -// Page returns the current page. Page should only be called after a successful -// call to Next. It is undefined what Page will return if Page is called after -// Next returns false. -func (p *Pagination) Page() interface{} { - return p.curPage -} - -// Next will attempt to retrieve the next page for the API operation. When a page -// is retrieved true will be returned. If the page cannot be retrieved, or there -// are no more pages false will be returned. -// -// Use the Page method to retrieve the current page data. The data will need -// to be cast to the API operation's output type. -// -// Use the Err method to determine if an error occurred if Page returns false. -func (p *Pagination) Next() bool { - if !p.HasNextPage() { - return false - } - - req, err := p.NewRequest() - if err != nil { - p.err = err - return false - } - - if p.started { - for i, intok := range req.Operation.InputTokens { - awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) - } - } - p.started = true - - err = req.Send() - if err != nil { - p.err = err - return false - } - - p.nextTokens = req.nextPageTokens() - p.curPage = req.Data - - return true -} - -// A Paginator is the configuration data that defines how an API operation -// should be paginated. This type is used by the API service models to define -// the generated pagination config for service APIs. -// -// The Pagination type is what provides iterating between pages of an API. It -// is only used to store the token metadata the SDK should use for performing -// pagination. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - -// nextPageTokens returns the tokens to use when asking for the next page of data. -func (r *Request) nextPageTokens() []interface{} { - if r.Operation.Paginator == nil { - return nil - } - if r.Operation.TruncationToken != "" { - tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) - if len(tr) == 0 { - return nil - } - - switch v := tr[0].(type) { - case *bool: - if !aws.BoolValue(v) { - return nil - } - case bool: - if v == false { - return nil - } - } - } - - tokens := []interface{}{} - tokenAdded := false - for _, outToken := range r.Operation.OutputTokens { - v, _ := awsutil.ValuesAtPath(r.Data, outToken) - if len(v) > 0 { - tokens = append(tokens, v[0]) - tokenAdded = true - } else { - tokens = append(tokens, nil) - } - } - if !tokenAdded { - return nil - } - - return tokens -} - -// Ensure a deprecated item is only logged once instead of each time its used. -func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { - if logger == nil { - return - } - if atomic.CompareAndSwapInt32(flag, 0, 1) { - logger.Log(msg) - } -} - -var ( - logDeprecatedHasNextPage int32 - logDeprecatedNextPage int32 - logDeprecatedEachPage int32 -) - -// HasNextPage returns true if this request has more pages of data available. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) HasNextPage() bool { - logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, - "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") - - return len(r.nextPageTokens()) > 0 -} - -// NextPage returns a new Request that can be executed to return the next -// page of result data. Call .Send() on this request to execute it. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) NextPage() *Request { - logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, - "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") - - tokens := r.nextPageTokens() - if len(tokens) == 0 { - return nil - } - - data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() - nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data) - for i, intok := range nr.Operation.InputTokens { - awsutil.SetValueAtPath(nr.Params, intok, tokens[i]) - } - return nr -} - -// EachPage iterates over each page of a paginated request object. The fn -// parameter should be a function with the following sample signature: -// -// func(page *T, lastPage bool) bool { -// return true // return false to stop iterating -// } -// -// Where "T" is the structure type matching the output structure of the given -// operation. For example, a request object generated by -// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput -// as the structure "T". The lastPage value represents whether the page is -// the last page of data or not. The return value of this function should -// return true to keep iterating or false to stop. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { - logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, - "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") - - for page := r; page != nil; page = page.NextPage() { - if err := page.Send(); err != nil { - return err - } - if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage { - return page.Error - } - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go deleted file mode 100644 index 2c05dbdc2e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ /dev/null @@ -1,161 +0,0 @@ -package request - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Retryer is an interface to control retry logic for a given service. -// The default implementation used by most services is the client.DefaultRetryer -// structure, which contains basic retry logic using exponential backoff. -type Retryer interface { - RetryRules(*Request) time.Duration - ShouldRetry(*Request) bool - MaxRetries() int -} - -// WithRetryer sets a config Retryer value to the given Config returning it -// for chaining. -func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { - cfg.Retryer = retryer - return cfg -} - -// retryableCodes is a collection of service response codes which are retry-able -// without any further action. -var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "RequestTimeout": {}, - ErrCodeResponseTimeout: {}, - "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout -} - -var throttleCodes = map[string]struct{}{ - "ProvisionedThroughputExceededException": {}, - "Throttling": {}, - "ThrottlingException": {}, - "RequestLimitExceeded": {}, - "RequestThrottled": {}, - "TooManyRequestsException": {}, // Lambda functions - "PriorRequestNotComplete": {}, // Route53 -} - -// credsExpiredCodes is a collection of error codes which signify the credentials -// need to be refreshed. Expired tokens require refreshing of credentials, and -// resigning before the request can be retried. -var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": {}, - "ExpiredTokenException": {}, - "RequestExpired": {}, // EC2 Only -} - -func isCodeThrottle(code string) bool { - _, ok := throttleCodes[code] - return ok -} - -func isCodeRetryable(code string) bool { - if _, ok := retryableCodes[code]; ok { - return true - } - - return isCodeExpiredCreds(code) -} - -func isCodeExpiredCreds(code string) bool { - _, ok := credsExpiredCodes[code] - return ok -} - -var validParentCodes = map[string]struct{}{ - ErrCodeSerialization: struct{}{}, - ErrCodeRead: struct{}{}, -} - -type temporaryError interface { - Temporary() bool -} - -func isNestedErrorRetryable(parentErr awserr.Error) bool { - if parentErr == nil { - return false - } - - if _, ok := validParentCodes[parentErr.Code()]; !ok { - return false - } - - err := parentErr.OrigErr() - if err == nil { - return false - } - - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) - } - - if t, ok := err.(temporaryError); ok { - return t.Temporary() - } - - return isErrConnectionReset(err) -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if error is nil. -func IsErrorRetryable(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) || isNestedErrorRetryable(aerr) - } - } - return false -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if error is nil. -func IsErrorThrottle(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeThrottle(aerr.Code()) - } - } - return false -} - -// IsErrorExpiredCreds returns whether the error code is a credential expiry error. -// Returns false if error is nil. -func IsErrorExpiredCreds(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeExpiredCreds(aerr.Code()) - } - } - return false -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorRetryable -func (r *Request) IsErrorRetryable() bool { - return IsErrorRetryable(r.Error) -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if the request has no Error set -// -// Alias for the utility function IsErrorThrottle -func (r *Request) IsErrorThrottle() bool { - return IsErrorThrottle(r.Error) -} - -// IsErrorExpired returns whether the error code is a credential expiry error. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorExpiredCreds -func (r *Request) IsErrorExpired() bool { - return IsErrorExpiredCreds(r.Error) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go deleted file mode 100644 index 09a44eb987..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go +++ /dev/null @@ -1,94 +0,0 @@ -package request - -import ( - "io" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var timeoutErr = awserr.New( - ErrCodeResponseTimeout, - "read on body has reached the timeout limit", - nil, -) - -type readResult struct { - n int - err error -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, timeoutErr - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -const ( - // HandlerResponseTimeout is what we use to signify the name of the - // response timeout handler. - HandlerResponseTimeout = "ResponseTimeoutHandler" -) - -// adaptToResponseTimeoutError is a handler that will replace any top level error -// to a ErrCodeResponseTimeout, if its child is that. -func adaptToResponseTimeoutError(req *Request) { - if err, ok := req.Error.(awserr.Error); ok { - aerr, ok := err.OrigErr().(awserr.Error) - if ok && aerr.Code() == ErrCodeResponseTimeout { - req.Error = aerr - } - } -} - -// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. -// This will allow for per read timeouts. If a timeout occurred, we will return the -// ErrCodeResponseTimeout. -// -// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) -func WithResponseReadTimeout(duration time.Duration) Option { - return func(r *Request) { - - var timeoutHandler = NamedHandler{ - HandlerResponseTimeout, - func(req *Request) { - req.HTTPResponse.Body = &timeoutReadCloser{ - reader: req.HTTPResponse.Body, - duration: duration, - } - }} - - // remove the handler so we are not stomping over any new durations. - r.Handlers.Send.RemoveByName(HandlerResponseTimeout) - r.Handlers.Send.PushBackNamed(timeoutHandler) - - r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) - r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go deleted file mode 100644 index 4012462282..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go +++ /dev/null @@ -1,234 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -const ( - // InvalidParameterErrCode is the error code for invalid parameters errors - InvalidParameterErrCode = "InvalidParameter" - // ParamRequiredErrCode is the error code for required parameter errors - ParamRequiredErrCode = "ParamRequiredError" - // ParamMinValueErrCode is the error code for fields with too low of a - // number value. - ParamMinValueErrCode = "ParamMinValueError" - // ParamMinLenErrCode is the error code for fields without enough elements. - ParamMinLenErrCode = "ParamMinLenError" -) - -// Validator provides a way for types to perform validation logic on their -// input values that external code can use to determine if a type's values -// are valid. -type Validator interface { - Validate() error -} - -// An ErrInvalidParams provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type ErrInvalidParams struct { - // Context is the base context of the invalid parameter group. - Context string - errs []ErrInvalidParam -} - -// Add adds a new invalid parameter error to the collection of invalid -// parameters. The context of the invalid parameter will be updated to reflect -// this collection. -func (e *ErrInvalidParams) Add(err ErrInvalidParam) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another ErrInvalidParams -// value into this collection. The nested errors will have their nested context -// updated and base context to reflect the merging. -// -// Use for nested validations errors. -func (e *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) { - for _, err := range nested.errs { - err.SetContext(e.Context) - err.AddNestedContext(nestedCtx) - e.errs = append(e.errs, err) - } -} - -// Len returns the number of invalid parameter errors -func (e ErrInvalidParams) Len() int { - return len(e.errs) -} - -// Code returns the code of the error -func (e ErrInvalidParams) Code() string { - return InvalidParameterErrCode -} - -// Message returns the message of the error -func (e ErrInvalidParams) Message() string { - return fmt.Sprintf("%d validation error(s) found.", len(e.errs)) -} - -// Error returns the string formatted form of the invalid parameters. -func (e ErrInvalidParams) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message()) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Message()) - } - - return w.String() -} - -// OrigErr returns the invalid parameters as a awserr.BatchedErrors value -func (e ErrInvalidParams) OrigErr() error { - return awserr.NewBatchError( - InvalidParameterErrCode, e.Message(), e.OrigErrs()) -} - -// OrigErrs returns a slice of the invalid parameters -func (e ErrInvalidParams) OrigErrs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An ErrInvalidParam represents an invalid parameter error type. -type ErrInvalidParam interface { - awserr.Error - - // Field name the error occurred on. - Field() string - - // SetContext updates the context of the error. - SetContext(string) - - // AddNestedContext updates the error's context to include a nested level. - AddNestedContext(string) -} - -type errInvalidParam struct { - context string - nestedContext string - field string - code string - msg string -} - -// Code returns the error code for the type of invalid parameter. -func (e *errInvalidParam) Code() string { - return e.code -} - -// Message returns the reason the parameter was invalid, and its context. -func (e *errInvalidParam) Message() string { - return fmt.Sprintf("%s, %s.", e.msg, e.Field()) -} - -// Error returns the string version of the invalid parameter error. -func (e *errInvalidParam) Error() string { - return fmt.Sprintf("%s: %s", e.code, e.Message()) -} - -// OrigErr returns nil, Implemented for awserr.Error interface. -func (e *errInvalidParam) OrigErr() error { - return nil -} - -// Field Returns the field and context the error occurred. -func (e *errInvalidParam) Field() string { - field := e.context - if len(field) > 0 { - field += "." - } - if len(e.nestedContext) > 0 { - field += fmt.Sprintf("%s.", e.nestedContext) - } - field += e.field - - return field -} - -// SetContext updates the base context of the error. -func (e *errInvalidParam) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *errInvalidParam) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - } else { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - } - -} - -// An ErrParamRequired represents an required parameter error. -type ErrParamRequired struct { - errInvalidParam -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ErrParamRequired { - return &ErrParamRequired{ - errInvalidParam{ - code: ParamRequiredErrCode, - field: field, - msg: fmt.Sprintf("missing required field"), - }, - } -} - -// An ErrParamMinValue represents a minimum value parameter error. -type ErrParamMinValue struct { - errInvalidParam - min float64 -} - -// NewErrParamMinValue creates a new minimum value parameter error. -func NewErrParamMinValue(field string, min float64) *ErrParamMinValue { - return &ErrParamMinValue{ - errInvalidParam: errInvalidParam{ - code: ParamMinValueErrCode, - field: field, - msg: fmt.Sprintf("minimum field value of %v", min), - }, - min: min, - } -} - -// MinValue returns the field's require minimum value. -// -// float64 is returned for both int and float min values. -func (e *ErrParamMinValue) MinValue() float64 { - return e.min -} - -// An ErrParamMinLen represents a minimum length parameter error. -type ErrParamMinLen struct { - errInvalidParam - min int -} - -// NewErrParamMinLen creates a new minimum length parameter error. -func NewErrParamMinLen(field string, min int) *ErrParamMinLen { - return &ErrParamMinLen{ - errInvalidParam: errInvalidParam{ - code: ParamMinLenErrCode, - field: field, - msg: fmt.Sprintf("minimum field size of %v", min), - }, - min: min, - } -} - -// MinLen returns the field's required minimum length. -func (e *ErrParamMinLen) MinLen() int { - return e.min -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go deleted file mode 100644 index 4601f883cc..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go +++ /dev/null @@ -1,295 +0,0 @@ -package request - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when -// the waiter's max attempts have been exhausted. -const WaiterResourceNotReadyErrorCode = "ResourceNotReady" - -// A WaiterOption is a function that will update the Waiter value's fields to -// configure the waiter. -type WaiterOption func(*Waiter) - -// WithWaiterMaxAttempts returns the maximum number of times the waiter should -// attempt to check the resource for the target state. -func WithWaiterMaxAttempts(max int) WaiterOption { - return func(w *Waiter) { - w.MaxAttempts = max - } -} - -// WaiterDelay will return a delay the waiter should pause between attempts to -// check the resource state. The passed in attempt is the number of times the -// Waiter has checked the resource state. -// -// Attempt is the number of attempts the Waiter has made checking the resource -// state. -type WaiterDelay func(attempt int) time.Duration - -// ConstantWaiterDelay returns a WaiterDelay that will always return a constant -// delay the waiter should use between attempts. It ignores the number of -// attempts made. -func ConstantWaiterDelay(delay time.Duration) WaiterDelay { - return func(attempt int) time.Duration { - return delay - } -} - -// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. -func WithWaiterDelay(delayer WaiterDelay) WaiterOption { - return func(w *Waiter) { - w.Delay = delayer - } -} - -// WithWaiterLogger returns a waiter option to set the logger a waiter -// should use to log warnings and errors to. -func WithWaiterLogger(logger aws.Logger) WaiterOption { - return func(w *Waiter) { - w.Logger = logger - } -} - -// WithWaiterRequestOptions returns a waiter option setting the request -// options for each request the waiter makes. Appends to waiter's request -// options already set. -func WithWaiterRequestOptions(opts ...Option) WaiterOption { - return func(w *Waiter) { - w.RequestOptions = append(w.RequestOptions, opts...) - } -} - -// A Waiter provides the functionality to perform a blocking call which will -// wait for a resource state to be satisfied by a service. -// -// This type should not be used directly. The API operations provided in the -// service packages prefixed with "WaitUntil" should be used instead. -type Waiter struct { - Name string - Acceptors []WaiterAcceptor - Logger aws.Logger - - MaxAttempts int - Delay WaiterDelay - - RequestOptions []Option - NewRequest func([]Option) (*Request, error) - SleepWithContext func(aws.Context, time.Duration) error -} - -// ApplyOptions updates the waiter with the list of waiter options provided. -func (w *Waiter) ApplyOptions(opts ...WaiterOption) { - for _, fn := range opts { - fn(w) - } -} - -// WaiterState are states the waiter uses based on WaiterAcceptor definitions -// to identify if the resource state the waiter is waiting on has occurred. -type WaiterState int - -// String returns the string representation of the waiter state. -func (s WaiterState) String() string { - switch s { - case SuccessWaiterState: - return "success" - case FailureWaiterState: - return "failure" - case RetryWaiterState: - return "retry" - default: - return "unknown waiter state" - } -} - -// States the waiter acceptors will use to identify target resource states. -const ( - SuccessWaiterState WaiterState = iota // waiter successful - FailureWaiterState // waiter failed - RetryWaiterState // waiter needs to be retried -) - -// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor -// definition's Expected attribute. -type WaiterMatchMode int - -// Modes the waiter will use when inspecting API response to identify target -// resource states. -const ( - PathAllWaiterMatch WaiterMatchMode = iota // match on all paths - PathWaiterMatch // match on specific path - PathAnyWaiterMatch // match on any path - PathListWaiterMatch // match on list of paths - StatusWaiterMatch // match on status code - ErrorWaiterMatch // match on error -) - -// String returns the string representation of the waiter match mode. -func (m WaiterMatchMode) String() string { - switch m { - case PathAllWaiterMatch: - return "pathAll" - case PathWaiterMatch: - return "path" - case PathAnyWaiterMatch: - return "pathAny" - case PathListWaiterMatch: - return "pathList" - case StatusWaiterMatch: - return "status" - case ErrorWaiterMatch: - return "error" - default: - return "unknown waiter match mode" - } -} - -// WaitWithContext will make requests for the API operation using NewRequest to -// build API requests. The request's response will be compared against the -// Waiter's Acceptors to determine the successful state of the resource the -// waiter is inspecting. -// -// The passed in context must not be nil. If it is nil a panic will occur. The -// Context will be used to cancel the waiter's pending requests and retry delays. -// Use aws.BackgroundContext if no context is available. -// -// The waiter will continue until the target state defined by the Acceptors, -// or the max attempts expires. -// -// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's -// retryer ShouldRetry returns false. This normally will happen when the max -// wait attempts expires. -func (w Waiter) WaitWithContext(ctx aws.Context) error { - - for attempt := 1; ; attempt++ { - req, err := w.NewRequest(w.RequestOptions) - if err != nil { - waiterLogf(w.Logger, "unable to create request %v", err) - return err - } - req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) - err = req.Send() - - // See if any of the acceptors match the request's response, or error - for _, a := range w.Acceptors { - if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { - return matchErr - } - } - - // The Waiter should only check the resource state MaxAttempts times - // This is here instead of in the for loop above to prevent delaying - // unnecessary when the waiter will not retry. - if attempt == w.MaxAttempts { - break - } - - // Delay to wait before inspecting the resource again - delay := w.Delay(attempt) - if sleepFn := req.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(delay) - } else { - sleepCtxFn := w.SleepWithContext - if sleepCtxFn == nil { - sleepCtxFn = aws.SleepWithContext - } - - if err := sleepCtxFn(ctx, delay); err != nil { - return awserr.New(CanceledErrorCode, "waiter context canceled", err) - } - } - } - - return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) -} - -// A WaiterAcceptor provides the information needed to wait for an API operation -// to complete. -type WaiterAcceptor struct { - State WaiterState - Matcher WaiterMatchMode - Argument string - Expected interface{} -} - -// match returns if the acceptor found a match with the passed in request -// or error. True is returned if the acceptor made a match, error is returned -// if there was an error attempting to perform the match. -func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { - result := false - var vals []interface{} - - switch a.Matcher { - case PathAllWaiterMatch, PathWaiterMatch: - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case PathAnyWaiterMatch: - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case PathListWaiterMatch: - // ignored matcher - case StatusWaiterMatch: - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case ErrorWaiterMatch: - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == a.Expected.(string) - } - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", - name, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - return false, nil - } - - switch a.State { - case SuccessWaiterState: - // waiter completed - return true, nil - case FailureWaiterState: - // Waiter failure state triggered - return true, awserr.New(WaiterResourceNotReadyErrorCode, - "failed waiting for successful resource state", err) - case RetryWaiterState: - // clear the error and retry the operation - return false, nil - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", - name, a.State) - return false, nil - } -} - -func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { - if logger != nil { - logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go deleted file mode 100644 index ea7b886f81..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ /dev/null @@ -1,273 +0,0 @@ -/* -Package session provides configuration for the SDK's service clients. - -Sessions can be shared across all service clients that share the same base -configuration. The Session is built from the SDK's default configuration and -request handlers. - -Sessions should be cached when possible, because creating a new Session will -load all configuration values from the environment, and config files each time -the Session is created. Sharing the Session value across all of your service -clients will ensure the configuration is loaded the fewest number of times possible. - -Concurrency - -Sessions are safe to use concurrently as long as the Session is not being -modified. The SDK will not modify the Session once the Session has been created. -Creating service clients concurrently from a shared Session is safe. - -Sessions from Shared Config - -Sessions can be created using the method above that will only load the -additional config if the AWS_SDK_LOAD_CONFIG environment variable is set. -Alternatively you can explicitly create a Session with shared config enabled. -To do this you can use NewSessionWithOptions to configure how the Session will -be created. Using the NewSessionWithOptions with SharedConfigState set to -SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG -environment variable was set. - -Creating Sessions - -When creating Sessions optional aws.Config values can be passed in that will -override the default, or loaded config values the Session is being created -with. This allows you to provide additional, or case based, configuration -as needed. - -By default NewSession will only load credentials from the shared credentials -file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is -set to a truthy value the Session will be created from the configuration -values from the shared config (~/.aws/config) and shared credentials -(~/.aws/credentials) files. See the section Sessions from Shared Config for -more information. - -Create a Session with the default config and request handlers. With credentials -region, and profile loaded from the environment and shared config automatically. -Requires the AWS_PROFILE to be set, or "default" is used. - - // Create Session - sess := session.Must(session.NewSession()) - - // Create a Session with a custom region - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String("us-east-1"), - })) - - // Create a S3 client instance from a session - sess := session.Must(session.NewSession()) - - svc := s3.New(sess) - -Create Session With Option Overrides - -In addition to NewSession, Sessions can be created using NewSessionWithOptions. -This func allows you to control and override how the Session will be created -through code instead of being driven by environment variables only. - -Use NewSessionWithOptions when you want to provide the config profile, or -override the shared config state (AWS_SDK_LOAD_CONFIG). - - // Equivalent to session.NewSession() - sess := session.Must(session.NewSessionWithOptions(session.Options{ - // Options - })) - - // Specify profile to load for the session's config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Profile: "profile_name", - })) - - // Specify profile for config and region for requests - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Config: aws.Config{Region: aws.String("us-east-1")}, - Profile: "profile_name", - })) - - // Force enable Shared Config support - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - -Adding Handlers - -You can add handlers to a session for processing HTTP requests. All service -clients that use the session inherit the handlers. For example, the following -handler logs every request and its payload made by a service client: - - // Create a session, and add additional handlers for all service - // clients created with the Session to inherit. Adds logging handler. - sess := session.Must(session.NewSession()) - - sess.Handlers.Send.PushFront(func(r *request.Request) { - // Log every request made and its payload - logger.Println("Request: %s/%s, Payload: %s", - r.ClientInfo.ServiceName, r.Operation, r.Params) - }) - -Deprecated "New" function - -The New session function has been deprecated because it does not provide good -way to return errors that occur when loading the configuration files and values. -Because of this, NewSession was created so errors can be retrieved when -creating a session fails. - -Shared Config Fields - -By default the SDK will only load the shared credentials file's (~/.aws/credentials) -credentials values, and all other config is provided by the environment variables, -SDK defaults, and user provided aws.Config values. - -If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable -option is used to create the Session the full shared config values will be -loaded. This includes credentials, region, and support for assume role. In -addition the Session will load its configuration from both the shared config -file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both -files have the same format. - -If both config files are present the configuration from both files will be -read. The Session will be created from configuration values from the shared -credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). - -Credentials are the values the SDK should use for authenticating requests with -AWS Services. They arfrom a configuration file will need to include both -aws_access_key_id and aws_secret_access_key must be provided together in the -same file to be considered valid. The values will be ignored if not a complete -group. aws_session_token is an optional field that can be provided if both of -the other two fields are also provided. - - aws_access_key_id = AKID - aws_secret_access_key = SECRET - aws_session_token = TOKEN - -Assume Role values allow you to configure the SDK to assume an IAM role using -a set of credentials provided in a config file via the source_profile field. -Both "role_arn" and "source_profile" are required. The SDK supports assuming -a role with MFA token if the session option AssumeRoleTokenProvider -is set. - - role_arn = arn:aws:iam:::role/ - source_profile = profile_with_creds - external_id = 1234 - mfa_serial = - role_session_name = session_name - -Region is the region the SDK should use for looking up AWS service endpoints -and signing requests. - - region = us-east-1 - -Assume Role with MFA token - -To create a session with support for assuming an IAM role with MFA set the -session option AssumeRoleTokenProvider to a function that will prompt for the -MFA token code when the SDK assumes the role and refreshes the role's credentials. -This allows you to configure the SDK via the shared config to assumea role -with MFA tokens. - -In order for the SDK to assume a role with MFA the SharedConfigState -session option must be set to SharedConfigEnable, or AWS_SDK_LOAD_CONFIG -environment variable set. - -The shared configuration instructs the SDK to assume an IAM role with MFA -when the mfa_serial configuration field is set in the shared config -(~/.aws/config) or shared credentials (~/.aws/credentials) file. - -If mfa_serial is set in the configuration, the SDK will assume the role, and -the AssumeRoleTokenProvider session option is not set an an error will -be returned when creating the session. - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - AssumeRoleTokenProvider: stscreds.StdinTokenProvider, - })) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess) - -To setup assume role outside of a session see the stscrds.AssumeRoleProvider -documentation. - -Environment Variables - -When a Session is created several environment variables can be set to adjust -how the SDK functions, and what configuration data it loads when creating -Sessions. All environment values are optional, but some values like credentials -require multiple of the values to set or the partial values will be ignored. -All environment variable values are strings unless otherwise noted. - -Environment configuration values. If set both Access Key ID and Secret Access -Key must be provided. Session Token and optionally also be provided, but is -not required. - - # Access Key ID - AWS_ACCESS_KEY_ID=AKID - AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - - # Secret Access Key - AWS_SECRET_ACCESS_KEY=SECRET - AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - - # Session Token - AWS_SESSION_TOKEN=TOKEN - -Region value will instruct the SDK where to make service API requests to. If is -not provided in the environment the region must be provided before a service -client request is made. - - AWS_REGION=us-east-1 - - # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_REGION is not also set. - AWS_DEFAULT_REGION=us-east-1 - -Profile name the SDK should load use when loading shared config from the -configuration files. If not provided "default" will be used as the profile name. - - AWS_PROFILE=my_profile - - # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_PROFILE is not also set. - AWS_DEFAULT_PROFILE=my_profile - -SDK load config instructs the SDK to load the shared config in addition to -shared credentials. This also expands the configuration loaded so the shared -credentials will have parity with the shared config file. This also enables -Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE -env values as well. - - AWS_SDK_LOAD_CONFIG=1 - -Shared credentials file path can be set to instruct the SDK to use an alternative -file for the shared credentials. If not set the file will be loaded from -$HOME/.aws/credentials on Linux/Unix based systems, and -%USERPROFILE%\.aws\credentials on Windows. - - AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - -Shared config file path can be set to instruct the SDK to use an alternative -file for the shared config. If not set the file will be loaded from -$HOME/.aws/config on Linux/Unix based systems, and -%USERPROFILE%\.aws\config on Windows. - - AWS_CONFIG_FILE=$HOME/my_shared_config - -Path to a custom Credentials Authority (CA) bundle PEM file that the SDK -will use instead of the default system's root CA bundle. Use this only -if you want to replace the CA bundle the SDK uses for TLS requests. - - AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - -Enabling this option will attempt to merge the Transport into the SDK's HTTP -client. If the client's Transport is not a http.Transport an error will be -returned. If the Transport's TLS config is set this option will cause the SDK -to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file -contains multiple certificates all of them will be loaded. - -The Session option CustomCABundle is also available when creating sessions -to also enable this feature. CustomCABundle session option field has priority -over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - -Setting a custom HTTPClient in the aws.Config options will override this setting. -To use this option and custom HTTP client, the HTTP client needs to be provided -when creating the session. Not the service client. -*/ -package session diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go deleted file mode 100644 index 7357e545ac..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ /dev/null @@ -1,188 +0,0 @@ -package session - -import ( - "os" - "strconv" - - "github.com/aws/aws-sdk-go/aws/credentials" -) - -// envConfig is a collection of environment values the SDK will read -// setup config from. All environment values are optional. But some values -// such as credentials require multiple values to be complete or the values -// will be ignored. -type envConfig struct { - // Environment configuration values. If set both Access Key ID and Secret Access - // Key must be provided. Session Token and optionally also be provided, but is - // not required. - // - // # Access Key ID - // AWS_ACCESS_KEY_ID=AKID - // AWS_ACCESS_KEY=AKID # only read if AWS_ACCESS_KEY_ID is not set. - // - // # Secret Access Key - // AWS_SECRET_ACCESS_KEY=SECRET - // AWS_SECRET_KEY=SECRET=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Creds credentials.Value - - // Region value will instruct the SDK where to make service API requests to. If is - // not provided in the environment the region must be provided before a service - // client request is made. - // - // AWS_REGION=us-east-1 - // - // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_REGION is not also set. - // AWS_DEFAULT_REGION=us-east-1 - Region string - - // Profile name the SDK should load use when loading shared configuration from the - // shared configuration files. If not provided "default" will be used as the - // profile name. - // - // AWS_PROFILE=my_profile - // - // # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_PROFILE is not also set. - // AWS_DEFAULT_PROFILE=my_profile - Profile string - - // SDK load config instructs the SDK to load the shared config in addition to - // shared credentials. This also expands the configuration loaded from the shared - // credentials to have parity with the shared config file. This also enables - // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE - // env values as well. - // - // AWS_SDK_LOAD_CONFIG=1 - EnableSharedConfig bool - - // Shared credentials file path can be set to instruct the SDK to use an alternate - // file for the shared credentials. If not set the file will be loaded from - // $HOME/.aws/credentials on Linux/Unix based systems, and - // %USERPROFILE%\.aws\credentials on Windows. - // - // AWS_SHARED_CREDENTIALS_FILE=$HOME/my_shared_credentials - SharedCredentialsFile string - - // Shared config file path can be set to instruct the SDK to use an alternate - // file for the shared config. If not set the file will be loaded from - // $HOME/.aws/config on Linux/Unix based systems, and - // %USERPROFILE%\.aws\config on Windows. - // - // AWS_CONFIG_FILE=$HOME/my_shared_config - SharedConfigFile string - - // Sets the path to a custom Credentials Authroity (CA) Bundle PEM file - // that the SDK will use instead of the the system's root CA bundle. - // Only use this if you want to configure the SDK to use a custom set - // of CAs. - // - // Enabling this option will attempt to merge the Transport - // into the SDK's HTTP client. If the client's Transport is - // not a http.Transport an error will be returned. If the - // Transport's TLS config is set this option will cause the - // SDK to overwrite the Transport's TLS config's RootCAs value. - // - // Setting a custom HTTPClient in the aws.Config options will override this setting. - // To use this option and custom HTTP client, the HTTP client needs to be provided - // when creating the session. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string -} - -var ( - credAccessEnvKey = []string{ - "AWS_ACCESS_KEY_ID", - "AWS_ACCESS_KEY", - } - credSecretEnvKey = []string{ - "AWS_SECRET_ACCESS_KEY", - "AWS_SECRET_KEY", - } - credSessionEnvKey = []string{ - "AWS_SESSION_TOKEN", - } - - regionEnvKeys = []string{ - "AWS_REGION", - "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - profileEnvKeys = []string{ - "AWS_PROFILE", - "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - sharedCredsFileEnvKey = []string{ - "AWS_SHARED_CREDENTIALS_FILE", - } - sharedConfigFileEnvKey = []string{ - "AWS_CONFIG_FILE", - } -) - -// loadEnvConfig retrieves the SDK's environment configuration. -// See `envConfig` for the values that will be retrieved. -// -// If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value -// the shared SDK config will be loaded in addition to the SDK's specific -// configuration values. -func loadEnvConfig() envConfig { - enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG")) - return envConfigLoad(enableSharedConfig) -} - -// loadEnvSharedConfig retrieves the SDK's environment configuration, and the -// SDK shared config. See `envConfig` for the values that will be retrieved. -// -// Loads the shared configuration in addition to the SDK's specific configuration. -// This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG` -// environment variable is set. -func loadSharedEnvConfig() envConfig { - return envConfigLoad(true) -} - -func envConfigLoad(enableSharedConfig bool) envConfig { - cfg := envConfig{} - - cfg.EnableSharedConfig = enableSharedConfig - - setFromEnvVal(&cfg.Creds.AccessKeyID, credAccessEnvKey) - setFromEnvVal(&cfg.Creds.SecretAccessKey, credSecretEnvKey) - setFromEnvVal(&cfg.Creds.SessionToken, credSessionEnvKey) - - // Require logical grouping of credentials - if len(cfg.Creds.AccessKeyID) == 0 || len(cfg.Creds.SecretAccessKey) == 0 { - cfg.Creds = credentials.Value{} - } else { - cfg.Creds.ProviderName = "EnvConfigCredentials" - } - - regionKeys := regionEnvKeys - profileKeys := profileEnvKeys - if !cfg.EnableSharedConfig { - regionKeys = regionKeys[:1] - profileKeys = profileKeys[:1] - } - - setFromEnvVal(&cfg.Region, regionKeys) - setFromEnvVal(&cfg.Profile, profileKeys) - - setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) - setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) - - cfg.CustomCABundle = os.Getenv("AWS_CA_BUNDLE") - - return cfg -} - -func setFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - *dst = v - break - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go deleted file mode 100644 index 9f75d5ac58..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ /dev/null @@ -1,606 +0,0 @@ -package session - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Session provides a central location to create service clients from and -// store configurations and request handlers for those services. -// -// Sessions are safe to create service clients concurrently, but it is not safe -// to mutate the Session concurrently. -// -// The Session satisfies the service client's client.ClientConfigProvider. -type Session struct { - Config *aws.Config - Handlers request.Handlers -} - -// New creates a new instance of the handlers merging in the provided configs -// on top of the SDK's default configurations. Once the Session is created it -// can be mutated to modify the Config or Handlers. The Session is safe to be -// read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New -// method could now encounter an error when loading the configuration. When -// The environment variable is set, and an error occurs, New will return a -// session that will fail all requests reporting the error that occurred while -// loading the session. Use NewSession to get the error when creating the -// session. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded, in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. -// -// Deprecated: Use NewSession functions to create sessions instead. NewSession -// has the same functionality as New except an error can be returned when the -// func is called instead of waiting to receive an error until a request is made. -func New(cfgs ...*aws.Config) *Session { - // load initial config from environment - envCfg := loadEnvConfig() - - if envCfg.EnableSharedConfig { - s, err := newSession(Options{}, envCfg, cfgs...) - if err != nil { - // Old session.New expected all errors to be discovered when - // a request is made, and would report the errors then. This - // needs to be replicated if an error occurs while creating - // the session. - msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + - "Use session.NewSession to handle errors occurring during session creation." - - // Session creation failed, need to report the error and prevent - // any requests from succeeding. - s = &Session{Config: defaults.Config()} - s.Config.MergeIn(cfgs...) - s.Config.Logger.Log("ERROR:", msg, "Error:", err) - s.Handlers.Validate.PushBack(func(r *request.Request) { - r.Error = err - }) - } - return s - } - - return deprecatedNewSession(cfgs...) -} - -// NewSession returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. Once the Session is created -// it can be mutated to modify the Config or Handlers. The Session is safe to -// be read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// See the NewSessionWithOptions func for information on how to override or -// control through code how the Session will be created. Such as specifying the -// config profile, and controlling if shared config is enabled or not. -func NewSession(cfgs ...*aws.Config) (*Session, error) { - opts := Options{} - opts.Config.MergeIn(cfgs...) - - return NewSessionWithOptions(opts) -} - -// SharedConfigState provides the ability to optionally override the state -// of the session's creation based on the shared config being enabled or -// disabled. -type SharedConfigState int - -const ( - // SharedConfigStateFromEnv does not override any state of the - // AWS_SDK_LOAD_CONFIG env var. It is the default value of the - // SharedConfigState type. - SharedConfigStateFromEnv SharedConfigState = iota - - // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value - // and disables the shared config functionality. - SharedConfigDisable - - // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value - // and enables the shared config functionality. - SharedConfigEnable -) - -// Options provides the means to control how a Session is created and what -// configuration values will be loaded. -// -type Options struct { - // Provides config values for the SDK to use when creating service clients - // and making API requests to services. Any value set in with this field - // will override the associated value provided by the SDK defaults, - // environment or config files where relevant. - // - // If not set, configuration values from from SDK defaults, environment, - // config will be used. - Config aws.Config - - // Overrides the config profile the Session should be created from. If not - // set the value of the environment variable will be loaded (AWS_PROFILE, - // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). - // - // If not set and environment variables are not set the "default" - // (DefaultSharedConfigProfile) will be used as the profile to load the - // session config from. - Profile string - - // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG - // environment variable. By default a Session will be created using the - // value provided by the AWS_SDK_LOAD_CONFIG environment variable. - // - // Setting this value to SharedConfigEnable or SharedConfigDisable - // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable - // and enable or disable the shared config functionality. - SharedConfigState SharedConfigState - - // Ordered list of files the session will load configuration from. - // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. - SharedConfigFiles []string - - // When the SDK's shared config is configured to assume a role with MFA - // this option is required in order to provide the mechanism that will - // retrieve the MFA token. There is no default value for this field. If - // it is not set an error will be returned when creating the session. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed. Within the context of service clients - // all sharing the same session the SDK will ensure calls to the token - // provider are atomic. When sharing a token provider across multiple - // sessions additional synchronization logic is needed to ensure the - // token providers do not introduce race conditions. It is recommend to - // share the session where possible. - // - // stscreds.StdinTokenProvider is a basic implementation that will prompt - // from stdin for the MFA token code. - // - // This field is only used if the shared configuration is enabled, and - // the config enables assume role wit MFA via the mfa_serial field. - AssumeRoleTokenProvider func() (string, error) - - // Reader for a custom Credentials Authority (CA) bundle in PEM format that - // the SDK will use instead of the default system's root CA bundle. Use this - // only if you want to replace the CA bundle the SDK uses for TLS requests. - // - // Enabling this option will attempt to merge the Transport into the SDK's HTTP - // client. If the client's Transport is not a http.Transport an error will be - // returned. If the Transport's TLS config is set this option will cause the SDK - // to overwrite the Transport's TLS config's RootCAs value. If the CA - // bundle reader contains multiple certificates all of them will be loaded. - // - // The Session option CustomCABundle is also available when creating sessions - // to also enable this feature. CustomCABundle session option field has priority - // over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - CustomCABundle io.Reader -} - -// NewSessionWithOptions returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. This func uses the Options -// values to configure how the Session is created. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// // Equivalent to session.New -// sess := session.Must(session.NewSessionWithOptions(session.Options{})) -// -// // Specify profile to load for the session's config -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Profile: "profile_name", -// })) -// -// // Specify profile for config and region for requests -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Config: aws.Config{Region: aws.String("us-east-1")}, -// Profile: "profile_name", -// })) -// -// // Force enable Shared Config support -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -func NewSessionWithOptions(opts Options) (*Session, error) { - var envCfg envConfig - if opts.SharedConfigState == SharedConfigEnable { - envCfg = loadSharedEnvConfig() - } else { - envCfg = loadEnvConfig() - } - - if len(opts.Profile) > 0 { - envCfg.Profile = opts.Profile - } - - switch opts.SharedConfigState { - case SharedConfigDisable: - envCfg.EnableSharedConfig = false - case SharedConfigEnable: - envCfg.EnableSharedConfig = true - } - - if len(envCfg.SharedCredentialsFile) == 0 { - envCfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() - } - if len(envCfg.SharedConfigFile) == 0 { - envCfg.SharedConfigFile = defaults.SharedConfigFilename() - } - - // Only use AWS_CA_BUNDLE if session option is not provided. - if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil { - f, err := os.Open(envCfg.CustomCABundle) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to open custom CA bundle PEM file", err) - } - defer f.Close() - opts.CustomCABundle = f - } - - return newSession(opts, envCfg, &opts.Config) -} - -// Must is a helper function to ensure the Session is valid and there was no -// error when calling a NewSession function. -// -// This helper is intended to be used in variable initialization to load the -// Session and configuration at startup. Such as: -// -// var sess = session.Must(session.NewSession()) -func Must(sess *Session, err error) *Session { - if err != nil { - panic(err) - } - - return sess -} - -func deprecatedNewSession(cfgs ...*aws.Config) *Session { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Apply the passed in configs so the configuration can be applied to the - // default credential chain - cfg.MergeIn(cfgs...) - if cfg.EndpointResolver == nil { - // An endpoint resolver is required for a session to be able to provide - // endpoints for service client configurations. - cfg.EndpointResolver = endpoints.DefaultResolver() - } - cfg.Credentials = defaults.CredChain(cfg, handlers) - - // Reapply any passed in configs to override credentials if set - cfg.MergeIn(cfgs...) - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - - return s -} - -func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Get a merged version of the user provided config to determine if - // credentials were. - userCfg := &aws.Config{} - userCfg.MergeIn(cfgs...) - - // Ordered config files will be loaded in with later files overwriting - // previous config file values. - var cfgFiles []string - if opts.SharedConfigFiles != nil { - cfgFiles = opts.SharedConfigFiles - } else { - cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} - if !envCfg.EnableSharedConfig { - // The shared config file (~/.aws/config) is only loaded if instructed - // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). - cfgFiles = cfgFiles[1:] - } - } - - // Load additional config from file(s) - sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles) - if err != nil { - return nil, err - } - - if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { - return nil, err - } - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - - // Setup HTTP client with custom cert bundle if enabled - if opts.CustomCABundle != nil { - if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil { - return nil, err - } - } - - return s, nil -} - -func loadCustomCABundle(s *Session, bundle io.Reader) error { - var t *http.Transport - switch v := s.Config.HTTPClient.Transport.(type) { - case *http.Transport: - t = v - default: - if s.Config.HTTPClient.Transport != nil { - return awserr.New("LoadCustomCABundleError", - "unable to load custom CA bundle, HTTPClient's transport unsupported type", nil) - } - } - if t == nil { - t = &http.Transport{} - } - - p, err := loadCertPool(bundle) - if err != nil { - return err - } - if t.TLSClientConfig == nil { - t.TLSClientConfig = &tls.Config{} - } - t.TLSClientConfig.RootCAs = p - - s.Config.HTTPClient.Transport = t - - return nil -} - -func loadCertPool(r io.Reader) (*x509.CertPool, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to read custom CA bundle PEM file", err) - } - - p := x509.NewCertPool() - if !p.AppendCertsFromPEM(b) { - return nil, awserr.New("LoadCustomCABundleError", - "failed to load custom CA bundle PEM file", err) - } - - return p, nil -} - -func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error { - // Merge in user provided configuration - cfg.MergeIn(userCfg) - - // Region if not already set by user - if len(aws.StringValue(cfg.Region)) == 0 { - if len(envCfg.Region) > 0 { - cfg.WithRegion(envCfg.Region) - } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { - cfg.WithRegion(sharedCfg.Region) - } - } - - // Configure credentials if not already set - if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { - if len(envCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - envCfg.Creds, - ) - } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil { - cfgCp := *cfg - cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.AssumeRoleSource.Creds, - ) - if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { - // AssumeRole Token provider is required if doing Assume Role - // with MFA. - return AssumeRoleTokenProviderNotSetError{} - } - cfg.Credentials = stscreds.NewCredentials( - &Session{ - Config: &cfgCp, - Handlers: handlers.Copy(), - }, - sharedCfg.AssumeRole.RoleARN, - func(opt *stscreds.AssumeRoleProvider) { - opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName - - // Assume role with external ID - if len(sharedCfg.AssumeRole.ExternalID) > 0 { - opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.AssumeRole.MFASerial) > 0 { - opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) - opt.TokenProvider = sessOpts.AssumeRoleTokenProvider - } - }, - ) - } else if len(sharedCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.Creds, - ) - } else { - // Fallback to default credentials provider, include mock errors - // for the credential chain so user can identify why credentials - // failed to be retrieved. - cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)}, - &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)}, - defaults.RemoteCredProvider(*cfg, handlers), - }, - }) - } - } - - return nil -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the -// MFAToken option is not set when shared config is configured load assume a -// role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Code is the short id of the error. -func (e AssumeRoleTokenProviderNotSetError) Code() string { - return "AssumeRoleTokenProviderNotSetError" -} - -// Message is the description of the error -func (e AssumeRoleTokenProviderNotSetError) Message() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -// OrigErr is the underlying error that caused the failure. -func (e AssumeRoleTokenProviderNotSetError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -type credProviderError struct { - Err error -} - -var emptyCreds = credentials.Value{} - -func (c credProviderError) Retrieve() (credentials.Value, error) { - return credentials.Value{}, c.Err -} -func (c credProviderError) IsExpired() bool { - return true -} - -func initHandlers(s *Session) { - // Add the Validate parameter handler if it is not disabled. - s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) - if !aws.BoolValue(s.Config.DisableParamValidation) { - s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) - } -} - -// Copy creates and returns a copy of the current Session, coping the config -// and handlers. If any additional configs are provided they will be merged -// on top of the Session's copied config. -// -// // Create a copy of the current Session, configured for the us-west-2 region. -// sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) -func (s *Session) Copy(cfgs ...*aws.Config) *Session { - newSession := &Session{ - Config: s.Config.Copy(cfgs...), - Handlers: s.Handlers.Copy(), - } - - initHandlers(newSession) - - return newSession -} - -// ClientConfig satisfies the client.ConfigProvider interface and is used to -// configure the service client instances. Passing the Session to the service -// client's constructor (New) will use this method to configure the client. -func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config { - // Backwards compatibility, the error will be eaten if user calls ClientConfig - // directly. All SDK services will use ClientconfigWithError. - cfg, _ := s.clientConfigWithErr(serviceName, cfgs...) - - return cfg -} - -func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - var err error - - region := aws.StringValue(s.Config.Region) - - if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 { - resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } else { - resolved, err = s.Config.EndpointResolver.EndpointFor( - serviceName, region, - func(opt *endpoints.Options) { - opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL) - opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack) - - // Support the condition where the service is modeled but its - // endpoint metadata is not available. - opt.ResolveUnknownService = true - }, - ) - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningName: resolved.SigningName, - }, err -} - -// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception -// that the EndpointResolver will not be used to resolve the endpoint. The only -// endpoint set must come from the aws.Config.Endpoint field. -func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - - region := aws.StringValue(s.Config.Region) - - if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { - resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningName: resolved.SigningName, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go deleted file mode 100644 index 09c8e5bc7a..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ /dev/null @@ -1,295 +0,0 @@ -package session - -import ( - "fmt" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" -) - -const ( - // Static Credentials group - accessKeyIDKey = `aws_access_key_id` // group required - secretAccessKey = `aws_secret_access_key` // group required - sessionTokenKey = `aws_session_token` // optional - - // Assume Role Credentials group - roleArnKey = `role_arn` // group required - sourceProfileKey = `source_profile` // group required - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - - // Additional Config fields - regionKey = `region` - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` -) - -type assumeRoleConfig struct { - RoleARN string - SourceProfile string - ExternalID string - MFASerial string - RoleSessionName string -} - -// sharedConfig represents the configuration fields of the SDK config files. -type sharedConfig struct { - // Credentials values from the config file. Both aws_access_key_id - // and aws_secret_access_key must be provided together in the same file - // to be considered valid. The values will be ignored if not a complete group. - // aws_session_token is an optional field that can be provided if both of the - // other two fields are also provided. - // - // aws_access_key_id - // aws_secret_access_key - // aws_session_token - Creds credentials.Value - - AssumeRole assumeRoleConfig - AssumeRoleSource *sharedConfig - - // Region is the region the SDK should use for looking up AWS service endpoints - // and signing requests. - // - // region - Region string -} - -type sharedConfigFile struct { - Filename string - IniData *ini.File -} - -// loadSharedConfig retrieves the configuration from the list of files -// using the profile provided. The order the files are listed will determine -// precedence. Values in subsequent files will overwrite values defined in -// earlier files. -// -// For example, given two files A and B. Both define credentials. If the order -// of the files are A then B, B's credential values will be used instead of A's. -// -// See sharedConfig.setFromFile for information how the config files -// will be loaded. -func loadSharedConfig(profile string, filenames []string) (sharedConfig, error) { - if len(profile) == 0 { - profile = DefaultSharedConfigProfile - } - - files, err := loadSharedConfigIniFiles(filenames) - if err != nil { - return sharedConfig{}, err - } - - cfg := sharedConfig{} - if err = cfg.setFromIniFiles(profile, files); err != nil { - return sharedConfig{}, err - } - - if len(cfg.AssumeRole.SourceProfile) > 0 { - if err := cfg.setAssumeRoleSource(profile, files); err != nil { - return sharedConfig{}, err - } - } - - return cfg, nil -} - -func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { - files := make([]sharedConfigFile, 0, len(filenames)) - - for _, filename := range filenames { - b, err := ioutil.ReadFile(filename) - if err != nil { - // Skip files which can't be opened and read for whatever reason - continue - } - - f, err := ini.Load(b) - if err != nil { - return nil, SharedConfigLoadError{Filename: filename, Err: err} - } - - files = append(files, sharedConfigFile{ - Filename: filename, IniData: f, - }) - } - - return files, nil -} - -func (cfg *sharedConfig) setAssumeRoleSource(origProfile string, files []sharedConfigFile) error { - var assumeRoleSrc sharedConfig - - // Multiple level assume role chains are not support - if cfg.AssumeRole.SourceProfile == origProfile { - assumeRoleSrc = *cfg - assumeRoleSrc.AssumeRole = assumeRoleConfig{} - } else { - err := assumeRoleSrc.setFromIniFiles(cfg.AssumeRole.SourceProfile, files) - if err != nil { - return err - } - } - - if len(assumeRoleSrc.Creds.AccessKeyID) == 0 { - return SharedConfigAssumeRoleError{RoleARN: cfg.AssumeRole.RoleARN} - } - - cfg.AssumeRoleSource = &assumeRoleSrc - - return nil -} - -func (cfg *sharedConfig) setFromIniFiles(profile string, files []sharedConfigFile) error { - // Trim files from the list that don't exist. - for _, f := range files { - if err := cfg.setFromIniFile(profile, f); err != nil { - if _, ok := err.(SharedConfigProfileNotExistsError); ok { - // Ignore proviles missings - continue - } - return err - } - } - - return nil -} - -// setFromFile loads the configuration from the file using -// the profile provided. A sharedConfig pointer type value is used so that -// multiple config file loadings can be chained. -// -// Only loads complete logically grouped values, and will not set fields in cfg -// for incomplete grouped values in the config. Such as credentials. For example -// if a config file only includes aws_access_key_id but no aws_secret_access_key -// the aws_access_key_id will be ignored. -func (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile) error { - section, err := file.IniData.GetSection(profile) - if err != nil { - // Fallback to to alternate profile name: profile - section, err = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) - if err != nil { - return SharedConfigProfileNotExistsError{Profile: profile, Err: err} - } - } - - // Shared Credentials - akid := section.Key(accessKeyIDKey).String() - secret := section.Key(secretAccessKey).String() - if len(akid) > 0 && len(secret) > 0 { - cfg.Creds = credentials.Value{ - AccessKeyID: akid, - SecretAccessKey: secret, - SessionToken: section.Key(sessionTokenKey).String(), - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), - } - } - - // Assume Role - roleArn := section.Key(roleArnKey).String() - srcProfile := section.Key(sourceProfileKey).String() - if len(roleArn) > 0 && len(srcProfile) > 0 { - cfg.AssumeRole = assumeRoleConfig{ - RoleARN: roleArn, - SourceProfile: srcProfile, - ExternalID: section.Key(externalIDKey).String(), - MFASerial: section.Key(mfaSerialKey).String(), - RoleSessionName: section.Key(roleSessionNameKey).String(), - } - } - - // Region - if v := section.Key(regionKey).String(); len(v) > 0 { - cfg.Region = v - } - - return nil -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigLoadError) Code() string { - return "SharedConfigLoadError" -} - -// Message is the description of the error -func (e SharedConfigLoadError) Message() string { - return fmt.Sprintf("failed to load config file, %s", e.Filename) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigLoadError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigLoadError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigProfileNotExistsError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistsError struct { - Profile string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigProfileNotExistsError) Code() string { - return "SharedConfigProfileNotExistsError" -} - -// Message is the description of the error -func (e SharedConfigProfileNotExistsError) Message() string { - return fmt.Sprintf("failed to get profile, %s", e.Profile) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigProfileNotExistsError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigProfileNotExistsError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigAssumeRoleError is an error for the shared config when the -// profile contains assume role information, but that information is invalid -// or not complete. -type SharedConfigAssumeRoleError struct { - RoleARN string -} - -// Code is the short id of the error. -func (e SharedConfigAssumeRoleError) Code() string { - return "SharedConfigAssumeRoleError" -} - -// Message is the description of the error -func (e SharedConfigAssumeRoleError) Message() string { - return fmt.Sprintf("failed to load assume role for %s, source profile has no shared credentials", - e.RoleARN) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e SharedConfigAssumeRoleError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go deleted file mode 100644 index 244c86da05..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go +++ /dev/null @@ -1,82 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" -) - -// validator houses a set of rule needed for validation of a -// string value -type rules []rule - -// rule interface allows for more flexible rules and just simply -// checks whether or not a value adheres to that rule -type rule interface { - IsValid(value string) bool -} - -// IsValid will iterate through all rules and see if any rules -// apply to the value and supports nested rules -func (r rules) IsValid(value string) bool { - for _, rule := range r { - if rule.IsValid(value) { - return true - } - } - return false -} - -// mapRule generic rule for maps -type mapRule map[string]struct{} - -// IsValid for the map rule satisfies whether it exists in the map -func (m mapRule) IsValid(value string) bool { - _, ok := m[value] - return ok -} - -// whitelist is a generic rule for whitelisting -type whitelist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (w whitelist) IsValid(value string) bool { - return w.rule.IsValid(value) -} - -// blacklist is a generic rule for blacklisting -type blacklist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (b blacklist) IsValid(value string) bool { - return !b.rule.IsValid(value) -} - -type patterns []string - -// IsValid for patterns checks each pattern and returns if a match has -// been found -func (p patterns) IsValid(value string) bool { - for _, pattern := range p { - if strings.HasPrefix(http.CanonicalHeaderKey(value), pattern) { - return true - } - } - return false -} - -// inclusiveRules rules allow for rules to depend on one another -type inclusiveRules []rule - -// IsValid will return true if all rules are true -func (r inclusiveRules) IsValid(value string) bool { - for _, rule := range r { - if !rule.IsValid(value) { - return false - } - } - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go deleted file mode 100644 index 6aa2ed241b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go +++ /dev/null @@ -1,7 +0,0 @@ -package v4 - -// WithUnsignedPayload will enable and set the UnsignedPayload field to -// true of the signer. -func WithUnsignedPayload(v4 *Signer) { - v4.UnsignedPayload = true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go deleted file mode 100644 index bd082e9d1f..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.5 - -package v4 - -import ( - "net/url" - "strings" -) - -func getURIPath(u *url.URL) string { - var uri string - - if len(u.Opaque) > 0 { - uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") - } else { - uri = u.EscapedPath() - } - - if len(uri) == 0 { - uri = "/" - } - - return uri -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go deleted file mode 100644 index d68905acbb..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ /dev/null @@ -1,761 +0,0 @@ -// Package v4 implements signing for AWS V4 signer -// -// Provides request signing for request that need to be signed with -// AWS V4 Signatures. -// -// Standalone Signer -// -// Generally using the signer outside of the SDK should not require any additional -// logic when using Go v1.5 or higher. The signer does this by taking advantage -// of the URL.EscapedPath method. If your request URI requires additional escaping -// you many need to use the URL.Opaque to define what the raw URI should be sent -// to the service as. -// -// The signer will first check the URL.Opaque field, and use its value if set. -// The signer does require the URL.Opaque field to be set in the form of: -// -// "///" -// -// // e.g. -// "//example.com/some/path" -// -// The leading "//" and hostname are required or the URL.Opaque escaping will -// not work correctly. -// -// If URL.Opaque is not set the signer will fallback to the URL.EscapedPath() -// method and using the returned value. If you're using Go v1.4 you must set -// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with -// Go v1.5 the signer will fallback to URL.Path. -// -// AWS v4 signature validation requires that the canonical string's URI path -// element must be the URI escaped form of the HTTP request's path. -// http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html -// -// The Go HTTP client will perform escaping automatically on the request. Some -// of these escaping may cause signature validation errors because the HTTP -// request differs from the URI path or query that the signature was generated. -// https://golang.org/pkg/net/url/#URL.EscapedPath -// -// Because of this, it is recommended that when using the signer outside of the -// SDK that explicitly escaping the request prior to being signed is preferable, -// and will help prevent signature validation errors. This can be done by setting -// the URL.Opaque or URL.RawPath. The SDK will use URL.Opaque first and then -// call URL.EscapedPath() if Opaque is not set. -// -// If signing a request intended for HTTP2 server, and you're using Go 1.6.2 -// through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the -// request URL. https://github.com/golang/go/issues/16847 points to a bug in -// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP -// message. URL.Opaque generally will force Go to make requests with absolute URL. -// URL.RawPath does not do this, but RawPath must be a valid escaping of Path -// or url.EscapedPath will ignore the RawPath escaping. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const ( - authHeaderPrefix = "AWS4-HMAC-SHA256" - timeFormat = "20060102T150405Z" - shortTimeFormat = "20060102" - - // emptyStringSHA256 is a SHA256 of an empty string - emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` -) - -var ignoredHeaders = rules{ - blacklist{ - mapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - }, - }, -} - -// requiredSignedHeaders is a whitelist for build canonical headers. -var requiredSignedHeaders = rules{ - whitelist{ - mapRule{ - "Cache-Control": struct{}{}, - "Content-Disposition": struct{}{}, - "Content-Encoding": struct{}{}, - "Content-Language": struct{}{}, - "Content-Md5": struct{}{}, - "Content-Type": struct{}{}, - "Expires": struct{}{}, - "If-Match": struct{}{}, - "If-Modified-Since": struct{}{}, - "If-None-Match": struct{}{}, - "If-Unmodified-Since": struct{}{}, - "Range": struct{}{}, - "X-Amz-Acl": struct{}{}, - "X-Amz-Copy-Source": struct{}{}, - "X-Amz-Copy-Source-If-Match": struct{}{}, - "X-Amz-Copy-Source-If-Modified-Since": struct{}{}, - "X-Amz-Copy-Source-If-None-Match": struct{}{}, - "X-Amz-Copy-Source-If-Unmodified-Since": struct{}{}, - "X-Amz-Copy-Source-Range": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Grant-Full-control": struct{}{}, - "X-Amz-Grant-Read": struct{}{}, - "X-Amz-Grant-Read-Acp": struct{}{}, - "X-Amz-Grant-Write": struct{}{}, - "X-Amz-Grant-Write-Acp": struct{}{}, - "X-Amz-Metadata-Directive": struct{}{}, - "X-Amz-Mfa": struct{}{}, - "X-Amz-Request-Payer": struct{}{}, - "X-Amz-Server-Side-Encryption": struct{}{}, - "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Algorithm": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key": struct{}{}, - "X-Amz-Server-Side-Encryption-Customer-Key-Md5": struct{}{}, - "X-Amz-Storage-Class": struct{}{}, - "X-Amz-Website-Redirect-Location": struct{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, -} - -// allowedHoisting is a whitelist for build query headers. The boolean value -// represents whether or not it is a pattern. -var allowedQueryHoisting = inclusiveRules{ - blacklist{requiredSignedHeaders}, - patterns{"X-Amz-"}, -} - -// Signer applies AWS v4 signing to given request. Use this to sign requests -// that need to be signed with AWS V4 Signatures. -type Signer struct { - // The authentication credentials the request will be signed against. - // This value must be set to sign requests. - Credentials *credentials.Credentials - - // Sets the log level the signer should use when reporting information to - // the logger. If the logger is nil nothing will be logged. See - // aws.LogLevelType for more information on available logging levels - // - // By default nothing will be logged. - Debug aws.LogLevelType - - // The logger loging information will be written to. If there the logger - // is nil, nothing will be logged. - Logger aws.Logger - - // Disables the Signer's moving HTTP header key/value pairs from the HTTP - // request header to the request's query string. This is most commonly used - // with pre-signed requests preventing headers from being added to the - // request's query string. - DisableHeaderHoisting bool - - // Disables the automatic escaping of the URI path of the request for the - // siganture's canonical string's path. For services that do not need additional - // escaping then use this to disable the signer escaping the path. - // - // S3 is an example of a service that does not need additional escaping. - // - // http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - DisableURIPathEscaping bool - - // Disales the automatical setting of the HTTP request's Body field with the - // io.ReadSeeker passed in to the signer. This is useful if you're using a - // custom wrapper around the body for the io.ReadSeeker and want to preserve - // the Body value on the Request.Body. - // - // This does run the risk of signing a request with a body that will not be - // sent in the request. Need to ensure that the underlying data of the Body - // values are the same. - DisableRequestBodyOverwrite bool - - // currentTimeFn returns the time value which represents the current time. - // This value should only be used for testing. If it is nil the default - // time.Now will be used. - currentTimeFn func() time.Time - - // UnsignedPayload will prevent signing of the payload. This will only - // work for services that have support for this. - UnsignedPayload bool -} - -// NewSigner returns a Signer pointer configured with the credentials and optional -// option values provided. If not options are provided the Signer will use its -// default configuration. -func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { - v4 := &Signer{ - Credentials: credentials, - } - - for _, option := range options { - option(v4) - } - - return v4 -} - -type signingCtx struct { - ServiceName string - Region string - Request *http.Request - Body io.ReadSeeker - Query url.Values - Time time.Time - ExpireTime time.Duration - SignedHeaderVals http.Header - - DisableURIPathEscaping bool - - credValues credentials.Value - isPresign bool - formattedTime string - formattedShortTime string - unsignedPayload bool - - bodyDigest string - signedHeaders string - canonicalHeaders string - canonicalString string - credentialString string - stringToSign string - signature string - authorization string -} - -// Sign signs AWS v4 requests with the provided body, service name, region the -// request is made to, and time the request is signed at. The signTime allows -// you to specify that a request is signed for the future, and cannot be -// used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. Generally for signed requests this value -// is not needed as the full request context will be captured by the http.Request -// value. It is included for reference though. -// -// Sign will set the request's Body to be the `body` parameter passed in. If -// the body is not already an io.ReadCloser, it will be wrapped within one. If -// a `nil` body parameter passed to Sign, the request's Body field will be -// also set to nil. Its important to note that this functionality will not -// change the request's ContentLength of the request. -// -// Sign differs from Presign in that it will sign the request using HTTP -// header values. This type of signing is intended for http.Request values that -// will not be shared, or are shared in a way the header values on the request -// will not be lost. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, 0, signTime) -} - -// Presign signs AWS v4 requests with the provided body, service name, region -// the request is made to, and time the request is signed at. The signTime -// allows you to specify that a request is signed for the future, and cannot -// be used until then. -// -// Returns a list of HTTP headers that were included in the signature or an -// error if signing the request failed. For presigned requests these headers -// and their values must be included on the HTTP request when it is made. This -// is helpful to know what header values need to be shared with the party the -// presigned request will be distributed to. -// -// Presign differs from Sign in that it will sign the request using query string -// instead of header values. This allows you to share the Presigned Request's -// URL with third parties, or distribute it throughout your system with minimal -// dependencies. -// -// Presign also takes an exp value which is the duration the -// signed request will be valid after the signing time. This is allows you to -// set when the request will expire. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -// -// Presigning a S3 request will not compute the body's SHA256 hash by default. -// This is done due to the general use case for S3 presigned URLs is to share -// PUT/GET capabilities. If you would like to include the body's SHA256 in the -// presigned request's signature you can set the "X-Amz-Content-Sha256" -// HTTP header and that will be included in the request's signature. -func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, exp, signTime) -} - -func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - currentTimeFn := v4.currentTimeFn - if currentTimeFn == nil { - currentTimeFn = time.Now - } - - ctx := &signingCtx{ - Request: r, - Body: body, - Query: r.URL.Query(), - Time: signTime, - ExpireTime: exp, - isPresign: exp != 0, - ServiceName: service, - Region: region, - DisableURIPathEscaping: v4.DisableURIPathEscaping, - unsignedPayload: v4.UnsignedPayload, - } - - for key := range ctx.Query { - sort.Strings(ctx.Query[key]) - } - - if ctx.isRequestSigned() { - ctx.Time = currentTimeFn() - ctx.handlePresignRemoval() - } - - var err error - ctx.credValues, err = v4.Credentials.Get() - if err != nil { - return http.Header{}, err - } - - ctx.assignAmzQueryValues() - ctx.build(v4.DisableHeaderHoisting) - - // If the request is not presigned the body should be attached to it. This - // prevents the confusion of wanting to send a signed request without - // the body the request was signed for attached. - if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { - var reader io.ReadCloser - if body != nil { - var ok bool - if reader, ok = body.(io.ReadCloser); !ok { - reader = ioutil.NopCloser(body) - } - } - r.Body = reader - } - - if v4.Debug.Matches(aws.LogDebugWithSigning) { - v4.logSigningInfo(ctx) - } - - return ctx.SignedHeaderVals, nil -} - -func (ctx *signingCtx) handlePresignRemoval() { - if !ctx.isPresign { - return - } - - // The credentials have expired for this request. The current signing - // is invalid, and needs to be request because the request will fail. - ctx.removePresign() - - // Update the request's query string to ensure the values stays in - // sync in the case retrieving the new credentials fails. - ctx.Request.URL.RawQuery = ctx.Query.Encode() -} - -func (ctx *signingCtx) assignAmzQueryValues() { - if ctx.isPresign { - ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if ctx.credValues.SessionToken != "" { - ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } else { - ctx.Query.Del("X-Amz-Security-Token") - } - - return - } - - if ctx.credValues.SessionToken != "" { - ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } -} - -// SignRequestHandler is a named request handler the SDK will use to sign -// service client request with using the V4 signature. -var SignRequestHandler = request.NamedHandler{ - Name: "v4.SignRequestHandler", Fn: SignSDKRequest, -} - -// SignSDKRequest signs an AWS request with the V4 signature. This -// request handler should only be used with the SDK's built in service client's -// API operation requests. -// -// This function should not be used on its on its own, but in conjunction with -// an AWS service client's API operation call. To sign a standalone request -// not created by a service client's API operation method use the "Sign" or -// "Presign" functions of the "Signer" type. -// -// If the credentials of the request's config are set to -// credentials.AnonymousCredentials the request will not be signed. -func SignSDKRequest(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now) -} - -// BuildNamedHandler will build a generic handler for signing. -func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { - return request.NamedHandler{ - Name: name, - Fn: func(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now, opts...) - }, - } -} - -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { - // If the request does not need to be signed ignore the signing of the - // request if the AnonymousCredentials object is used. - if req.Config.Credentials == credentials.AnonymousCredentials { - return - } - - region := req.ClientInfo.SigningRegion - if region == "" { - region = aws.StringValue(req.Config.Region) - } - - name := req.ClientInfo.SigningName - if name == "" { - name = req.ClientInfo.ServiceName - } - - v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { - v4.Debug = req.Config.LogLevel.Value() - v4.Logger = req.Config.Logger - v4.DisableHeaderHoisting = req.NotHoist - v4.currentTimeFn = curTimeFn - if name == "s3" { - // S3 service should not have any escaping applied - v4.DisableURIPathEscaping = true - } - // Prevents setting the HTTPRequest's Body. Since the Body could be - // wrapped in a custom io.Closer that we do not want to be stompped - // on top of by the signer. - v4.DisableRequestBodyOverwrite = true - }) - - for _, opt := range opts { - opt(v4) - } - - signingTime := req.Time - if !req.LastSignedAt.IsZero() { - signingTime = req.LastSignedAt - } - - signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), - name, region, req.ExpireTime, signingTime, - ) - if err != nil { - req.Error = err - req.SignedHeaderVals = nil - return - } - - req.SignedHeaderVals = signedHeaders - req.LastSignedAt = curTimeFn() -} - -const logSignInfoMsg = `DEBUG: Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` - -func (v4 *Signer) logSigningInfo(ctx *signingCtx) { - signedURLMsg := "" - if ctx.isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) - } - msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) - v4.Logger.Log(msg) -} - -func (ctx *signingCtx) build(disableHeaderHoisting bool) { - ctx.buildTime() // no depends - ctx.buildCredentialString() // no depends - - unsignedHeaders := ctx.Request.Header - if ctx.isPresign { - if !disableHeaderHoisting { - urlValues := url.Values{} - urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends - for k := range urlValues { - ctx.Query[k] = urlValues[k] - } - } - } - - ctx.buildBodyDigest() - ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) - ctx.buildCanonicalString() // depends on canon headers / signed headers - ctx.buildStringToSign() // depends on canon string - ctx.buildSignature() // depends on string to sign - - if ctx.isPresign { - ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature - } else { - parts := []string{ - authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, - "SignedHeaders=" + ctx.signedHeaders, - "Signature=" + ctx.signature, - } - ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) - } -} - -func (ctx *signingCtx) buildTime() { - ctx.formattedTime = ctx.Time.UTC().Format(timeFormat) - ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat) - - if ctx.isPresign { - duration := int64(ctx.ExpireTime / time.Second) - ctx.Query.Set("X-Amz-Date", ctx.formattedTime) - ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) - } else { - ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime) - } -} - -func (ctx *signingCtx) buildCredentialString() { - ctx.credentialString = strings.Join([]string{ - ctx.formattedShortTime, - ctx.Region, - ctx.ServiceName, - "aws4_request", - }, "/") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) - } -} - -func buildQuery(r rule, header http.Header) (url.Values, http.Header) { - query := url.Values{} - unsignedHeaders := http.Header{} - for k, h := range header { - if r.IsValid(k) { - query[k] = h - } else { - unsignedHeaders[k] = h - } - } - - return query, unsignedHeaders -} -func (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { - var headers []string - headers = append(headers, "host") - for k, v := range header { - canonicalKey := http.CanonicalHeaderKey(k) - if !r.IsValid(canonicalKey) { - continue // ignored header - } - if ctx.SignedHeaderVals == nil { - ctx.SignedHeaderVals = make(http.Header) - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { - // include additional values - ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - ctx.SignedHeaderVals[lowerCaseKey] = v - } - sort.Strings(headers) - - ctx.signedHeaders = strings.Join(headers, ";") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) - } - - headerValues := make([]string, len(headers)) - for i, k := range headers { - if k == "host" { - if ctx.Request.Host != "" { - headerValues[i] = "host:" + ctx.Request.Host - } else { - headerValues[i] = "host:" + ctx.Request.URL.Host - } - } else { - headerValues[i] = k + ":" + - strings.Join(ctx.SignedHeaderVals[k], ",") - } - } - stripExcessSpaces(headerValues) - ctx.canonicalHeaders = strings.Join(headerValues, "\n") -} - -func (ctx *signingCtx) buildCanonicalString() { - ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) - - uri := getURIPath(ctx.Request.URL) - - if !ctx.DisableURIPathEscaping { - uri = rest.EscapePath(uri, false) - } - - ctx.canonicalString = strings.Join([]string{ - ctx.Request.Method, - uri, - ctx.Request.URL.RawQuery, - ctx.canonicalHeaders + "\n", - ctx.signedHeaders, - ctx.bodyDigest, - }, "\n") -} - -func (ctx *signingCtx) buildStringToSign() { - ctx.stringToSign = strings.Join([]string{ - authHeaderPrefix, - ctx.formattedTime, - ctx.credentialString, - hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))), - }, "\n") -} - -func (ctx *signingCtx) buildSignature() { - secret := ctx.credValues.SecretAccessKey - date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime)) - region := makeHmac(date, []byte(ctx.Region)) - service := makeHmac(region, []byte(ctx.ServiceName)) - credentials := makeHmac(service, []byte("aws4_request")) - signature := makeHmac(credentials, []byte(ctx.stringToSign)) - ctx.signature = hex.EncodeToString(signature) -} - -func (ctx *signingCtx) buildBodyDigest() { - hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") - if hash == "" { - if ctx.unsignedPayload || (ctx.isPresign && ctx.ServiceName == "s3") { - hash = "UNSIGNED-PAYLOAD" - } else if ctx.Body == nil { - hash = emptyStringSHA256 - } else { - hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) - } - if ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { - ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) - } - } - ctx.bodyDigest = hash -} - -// isRequestSigned returns if the request is currently signed or presigned -func (ctx *signingCtx) isRequestSigned() bool { - if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { - return true - } - if ctx.Request.Header.Get("Authorization") != "" { - return true - } - - return false -} - -// unsign removes signing flags for both signed and presigned requests. -func (ctx *signingCtx) removePresign() { - ctx.Query.Del("X-Amz-Algorithm") - ctx.Query.Del("X-Amz-Signature") - ctx.Query.Del("X-Amz-Security-Token") - ctx.Query.Del("X-Amz-Date") - ctx.Query.Del("X-Amz-Expires") - ctx.Query.Del("X-Amz-Credential") - ctx.Query.Del("X-Amz-SignedHeaders") -} - -func makeHmac(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256(data []byte) []byte { - hash := sha256.New() - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256Reader(reader io.ReadSeeker) []byte { - hash := sha256.New() - start, _ := reader.Seek(0, 1) - defer reader.Seek(start, 0) - - io.Copy(hash, reader) - return hash.Sum(nil) -} - -const doubleSpace = " " - -// stripExcessSpaces will rewrite the passed in slice's string values to not -// contain muliple side-by-side spaces. -func stripExcessSpaces(vals []string) { - var j, k, l, m, spaces int - for i, str := range vals { - // Trim trailing spaces - for j = len(str) - 1; j >= 0 && str[j] == ' '; j-- { - } - - // Trim leading spaces - for k = 0; k < j && str[k] == ' '; k++ { - } - str = str[k : j+1] - - // Strip multiple spaces. - j = strings.Index(str, doubleSpace) - if j < 0 { - vals[i] = str - continue - } - - buf := []byte(str) - for k, m, l = j, j, len(buf); k < l; k++ { - if buf[k] == ' ' { - if spaces == 0 { - // First space. - buf[m] = buf[k] - m++ - } - spaces++ - } else { - // End of multiple spaces. - spaces = 0 - buf[m] = buf[k] - m++ - } - } - - vals[i] = string(buf[:m]) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go deleted file mode 100644 index 0e2d864e10..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ /dev/null @@ -1,118 +0,0 @@ -package aws - -import ( - "io" - "sync" -) - -// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Should -// only be used with an io.Reader that is also an io.Seeker. Doing so may -// cause request signature errors, or request body's not sent for GET, HEAD -// and DELETE HTTP methods. -// -// Deprecated: Should only be used with io.ReadSeeker. If using for -// S3 PutObject to stream content use s3manager.Uploader instead. -func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { - return ReaderSeekerCloser{r} -} - -// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and -// io.Closer interfaces to the underlying object if they are available. -type ReaderSeekerCloser struct { - r io.Reader -} - -// Read reads from the reader up to size of p. The number of bytes read, and -// error if it occurred will be returned. -// -// If the reader is not an io.Reader zero bytes read, and nil error will be returned. -// -// Performs the same functionality as io.Reader Read -func (r ReaderSeekerCloser) Read(p []byte) (int, error) { - switch t := r.r.(type) { - case io.Reader: - return t.Read(p) - } - return 0, nil -} - -// Seek sets the offset for the next Read to offset, interpreted according to -// whence: 0 means relative to the origin of the file, 1 means relative to the -// current offset, and 2 means relative to the end. Seek returns the new offset -// and an error, if any. -// -// If the ReaderSeekerCloser is not an io.Seeker nothing will be done. -func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { - switch t := r.r.(type) { - case io.Seeker: - return t.Seek(offset, whence) - } - return int64(0), nil -} - -// IsSeeker returns if the underlying reader is also a seeker. -func (r ReaderSeekerCloser) IsSeeker() bool { - _, ok := r.r.(io.Seeker) - return ok -} - -// Close closes the ReaderSeekerCloser. -// -// If the ReaderSeekerCloser is not an io.Closer nothing will be done. -func (r ReaderSeekerCloser) Close() error { - switch t := r.r.(type) { - case io.Closer: - return t.Close() - } - return nil -} - -// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface -// Can be used with the s3manager.Downloader to download content to a buffer -// in memory. Safe to use concurrently. -type WriteAtBuffer struct { - buf []byte - m sync.Mutex - - // GrowthCoeff defines the growth rate of the internal buffer. By - // default, the growth rate is 1, where expanding the internal - // buffer will allocate only enough capacity to fit the new expected - // length. - GrowthCoeff float64 -} - -// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer -// provided by buf. -func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { - return &WriteAtBuffer{buf: buf} -} - -// WriteAt writes a slice of bytes to a buffer starting at the position provided -// The number of bytes written will be returned, or error. Can overwrite previous -// written slices if the write ats overlap. -func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { - pLen := len(p) - expLen := pos + int64(pLen) - b.m.Lock() - defer b.m.Unlock() - if int64(len(b.buf)) < expLen { - if int64(cap(b.buf)) < expLen { - if b.GrowthCoeff < 1 { - b.GrowthCoeff = 1 - } - newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) - copy(newBuf, b.buf) - b.buf = newBuf - } - b.buf = b.buf[:expLen] - } - copy(b.buf[pos:], p) - return pLen, nil -} - -// Bytes returns a slice of bytes written to the buffer. -func (b *WriteAtBuffer) Bytes() []byte { - b.m.Lock() - defer b.m.Unlock() - return b.buf -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url.go b/vendor/github.com/aws/aws-sdk-go/aws/url.go deleted file mode 100644 index 6192b2455b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.8 - -package aws - -import "net/url" - -// URLHostname will extract the Hostname without port from the URL value. -// -// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. -func URLHostname(url *url.URL) string { - return url.Hostname() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go deleted file mode 100644 index 0210d2720e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build !go1.8 - -package aws - -import ( - "net/url" - "strings" -) - -// URLHostname will extract the Hostname without port from the URL value. -// -// Copy of Go 1.8's net/url#URL.Hostname functionality. -func URLHostname(url *url.URL) string { - return stripPort(url.Host) - -} - -// stripPort is copy of Go 1.8 url#URL.Hostname functionality. -// https://golang.org/src/net/url/url.go -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go deleted file mode 100644 index 971b08bcd0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/version.go +++ /dev/null @@ -1,8 +0,0 @@ -// Package aws provides core functionality for making requests to AWS services. -package aws - -// SDKName is the name of this AWS SDK -const SDKName = "aws-sdk-go" - -// SDKVersion is the version of this SDK -const SDKVersion = "1.10.18" diff --git a/vendor/github.com/aws/aws-sdk-go/doc.go b/vendor/github.com/aws/aws-sdk-go/doc.go deleted file mode 100644 index 3e077e51da..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/doc.go +++ /dev/null @@ -1,405 +0,0 @@ -// Package sdk is the official AWS SDK for the Go programming language. -// -// The AWS SDK for Go provides APIs and utilities that developers can use to -// build Go applications that use AWS services, such as Amazon Elastic Compute -// Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). -// -// The SDK removes the complexity of coding directly against a web service -// interface. It hides a lot of the lower-level plumbing, such as authentication, -// request retries, and error handling. -// -// The SDK also includes helpful utilities on top of the AWS APIs that add additional -// capabilities and functionality. For example, the Amazon S3 Download and Upload -// Manager will automatically split up large objects into multiple parts and -// transfer them concurrently. -// -// See the s3manager package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ -// -// Getting More Information -// -// Checkout the Getting Started Guide and API Reference Docs detailed the SDK's -// components and details on each AWS client the SDK supports. -// -// The Getting Started Guide provides examples and detailed description of how -// to get setup with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html -// -// The API Reference Docs include a detailed breakdown of the SDK's components -// such as utilities and AWS clients. Use this as a reference of the Go types -// included with the SDK, such as AWS clients, API operations, and API parameters. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// Overview of SDK's Packages -// -// The SDK is composed of two main components, SDK core, and service clients. -// The SDK core packages are all available under the aws package at the root of -// the SDK. Each client for a supported AWS service is available within its own -// package under the service folder at the root of the SDK. -// -// * aws - SDK core, provides common shared types such as Config, Logger, -// and utilities to make working with API parameters easier. -// -// * awserr - Provides the error interface that the SDK will use for all -// errors that occur in the SDK's processing. This includes service API -// response errors as well. The Error type is made up of a code and message. -// Cast the SDK's returned error type to awserr.Error and call the Code -// method to compare returned error to specific error codes. See the package's -// documentation for additional values that can be extracted such as RequestId. -// -// * credentials - Provides the types and built in credentials providers -// the SDK will use to retrieve AWS credentials to make API requests with. -// Nested under this folder are also additional credentials providers such as -// stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. -// -// * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. -// Use this to lookup AWS service endpoint information such as which services -// are in a region, and what regions a service is in. Constants are also provided -// for all region identifiers, e.g UsWest2RegionID for "us-west-2". -// -// * session - Provides initial default configuration, and load -// configuration from external sources such as environment and shared -// credentials file. -// -// * request - Provides the API request sending, and retry logic for the SDK. -// This package also includes utilities for defining your own request -// retryer, and configuring how the SDK processes the request. -// -// * service - Clients for AWS services. All services supported by the SDK are -// available under this folder. -// -// How to Use the SDK's AWS Service Clients -// -// The SDK includes the Go types and utilities you can use to make requests to -// AWS service APIs. Within the service folder at the root of the SDK you'll find -// a package for each AWS service the SDK supports. All service clients follows -// a common pattern of creation and usage. -// -// When creating a client for an AWS service you'll first need to have a Session -// value constructed. The Session provides shared configuration that can be shared -// between your service clients. When service clients are created you can pass -// in additional configuration via the aws.Config type to override configuration -// provided by in the Session to create service client instances with custom -// configuration. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// Configuring the SDK -// -// In the AWS SDK for Go, you can configure settings for service clients, such -// as the log level and maximum number of retries. Most settings are optional; -// however, for each service client, you must specify a region and your credentials. -// The SDK uses these values to send requests to the correct AWS region and sign -// requests with the correct credentials. You can specify these values as part -// of a session or as environment variables. -// -// See the SDK's configuration guide for more information. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -// -// See the session package documentation for more information on how to use Session -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -// -// See the Config type in the aws package for more information on configuration -// options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Configuring Credentials -// -// When using the SDK you'll generally need your AWS credentials to authenticate -// with AWS services. The SDK supports multiple methods of supporting these -// credentials. By default the SDK will source credentials automatically from -// its default credential chain. See the session package for more information -// on this chain, and how to configure it. The common items in the credential -// chain are the following: -// -// * Environment Credentials - Set of environment variables that are useful -// when sub processes are created for specific roles. -// -// * Shared Credentials file (~/.aws/credentials) - This file stores your -// credentials based on a profile name and is useful for local development. -// -// * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials -// to application running on an EC2 instance. This removes the need to manage -// credential files in production. -// -// Credentials can be configured in code as well by setting the Config's Credentials -// value to a custom provider or using one of the providers included with the -// SDK to bypass the default credential chain and use a custom one. This is -// helpful when you want to instruct the SDK to only use a specific set of -// credentials or providers. -// -// This example creates a credential provider for assuming an IAM role, "myRoleARN" -// and configures the S3 service client to use that role for API requests. -// -// // Initial credentials loaded from SDK's default credential chain. Such as -// // the environment, shared credentials (~/.aws/credentials), or EC2 Instance -// // Role. These credentials will be used to to make the STS Assume Role API. -// sess := session.Must(session.NewSession()) -// -// // Create the credentials from AssumeRoleProvider to assume the role -// // referenced by the "myRoleARN" ARN. -// creds := stscreds.NewCredentials(sess, "myRoleArn") -// -// // Create service client value configured for credentials -// // from assumed role. -// svc := s3.New(sess, &aws.Config{Credentials: creds})/ -// -// See the credentials package documentation for more information on credential -// providers included with the SDK, and how to customize the SDK's usage of -// credentials. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials -// -// The SDK has support for the shared configuration file (~/.aws/config). This -// support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -// or enabling the feature in code when creating a Session via the -// Option's SharedConfigState parameter. -// -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -// -// Configuring AWS Region -// -// In addition to the credentials you'll need to specify the region the SDK -// will use to make AWS API requests to. In the SDK you can specify the region -// either with an environment variable, or directly in code when a Session or -// service client is created. The last value specified in code wins if the region -// is specified multiple ways. -// -// To set the region via the environment variable set the "AWS_REGION" to the -// region you want to the SDK to use. Using this method to set the region will -// allow you to run your application in multiple regions without needing additional -// code in the application to select the region. -// -// AWS_REGION=us-west-2 -// -// The endpoints package includes constants for all regions the SDK knows. The -// values are all suffixed with RegionID. These values are helpful, because they -// reduce the need to type the region string manually. -// -// To set the region on a Session use the aws package's Config struct parameter -// Region to the AWS region you want the service clients created from the session to -// use. This is helpful when you want to create multiple service clients, and -// all of the clients make API requests to the same region. -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// })) -// -// See the endpoints package for the AWS Regions and Endpoints metadata. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ -// -// In addition to setting the region when creating a Session you can also set -// the region on a per service client bases. This overrides the region of a -// Session. This is helpful when you want to create service clients in specific -// regions different from the Session's region. -// -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String(ednpoints.UsWest2RegionID), -// }) -// -// See the Config type in the aws package for more information and additional -// options such as setting the Endpoint, and other service client configuration options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Making API Requests -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. The SDK provides methods for making the API call in multiple ways. -// -// In this list we'll use the S3 ListObjects API as an example for the different -// ways of making API requests. -// -// * ListObjects - Base API operation that will make the API request to the service. -// -// * ListObjectsRequest - API methods suffixed with Request will construct the -// API request, but not send it. This is also helpful when you want to get a -// presigned URL for a request, and share the presigned URL instead of your -// application making the request directly. -// -// * ListObjectsPages - Same as the base API operation, but uses a callback to -// automatically handle pagination of the API's response. -// -// * ListObjectsWithContext - Same as base API operation, but adds support for -// the Context pattern. This is helpful for controlling the canceling of in -// flight requests. See the Go standard library context package for more -// information. This method also takes request package's Option functional -// options as the variadic argument for modifying how the request will be -// made, or extracting information from the raw HTTP response. -// -// * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for -// the Context pattern. Similar to ListObjectsWithContext this method also -// takes the request package's Option function option types as the variadic -// argument. -// -// In addition to the API operations the SDK also includes several higher level -// methods that abstract checking for and waiting for an AWS resource to be in -// a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -// the different forms of waiters. -// -// * WaitUntilBucketExists. - Method to make API request to query an AWS service for -// a resource's state. Will return successfully when that state is accomplished. -// -// * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds -// support for the Context pattern. In addition these methods take request -// package's WaiterOptions to configure the waiter, and how underlying request -// will be made by the SDK. -// -// The API method will document which error codes the service might return for -// the operation. These errors will also be available as const strings prefixed -// with "ErrCode" in the service client's package. If there are no errors listed -// in the API's SDK documentation you'll need to consult the AWS service's API -// documentation for the errors that could be returned. -// -// ctx := context.Background() -// -// result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ -// Bucket: aws.String("my-bucket"), -// Key: aws.String("my-key"), -// }) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == s3.ErrCodeNoSuchKey { -// // Specific error code handling -// } -// return err -// } -// -// // Make sure to close the body when done with it for S3 GetObject APIs or -// // will leak connections. -// defer result.Body.Close() -// -// fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -// -// API Request Pagination and Resource Waiters -// -// Pagination helper methods are suffixed with "Pages", and provide the -// functionality needed to round trip API page requests. Pagination methods -// take a callback function that will be called for each page of the API's response. -// -// objects := []string{} -// err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ -// Bucket: aws.String(myBucket), -// }, func(p *s3.ListObjectsOutput, lastPage bool) bool { -// for _, o := range p.Contents { -// objects = append(objects, aws.StringValue(o.Key)) -// } -// return true // continue paging -// }) -// if err != nil { -// panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) -// } -// -// fmt.Println("Objects in bucket:", objects) -// -// Waiter helper methods provide the functionality to wait for an AWS resource -// state. These methods abstract the logic needed to to check the state of an -// AWS resource, and wait until that resource is in a desired state. The waiter -// will block until the resource is in the state that is desired, an error occurs, -// or the waiter times out. If a resource times out the error code returned will -// be request.WaiterResourceNotReadyErrorCode. -// -// err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ -// Bucket: aws.String(myBucket), -// }) -// if err != nil { -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { -// fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") -// } -// panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) -// } -// fmt.Println("Bucket", myBucket, "exists") -// -// Complete SDK Example -// -// This example shows a complete working Go file which will upload a file to S3 -// and use the Context pattern to implement timeout logic that will cancel the -// request if it takes too long. This example highlights how to use sessions, -// create a service client, make a request, handle the error, and process the -// response. -// -// package main -// -// import ( -// "context" -// "flag" -// "fmt" -// "os" -// "time" -// -// "github.com/aws/aws-sdk-go/aws" -// "github.com/aws/aws-sdk-go/aws/awserr" -// "github.com/aws/aws-sdk-go/aws/request" -// "github.com/aws/aws-sdk-go/aws/session" -// "github.com/aws/aws-sdk-go/service/s3" -// ) -// -// // Uploads a file to S3 given a bucket and object key. Also takes a duration -// // value to terminate the update if it doesn't complete within that time. -// // -// // The AWS Region needs to be provided in the AWS shared config or on the -// // environment variable as `AWS_REGION`. Credentials also must be provided -// // Will default to shared config file, but can load from environment if provided. -// // -// // Usage: -// // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail -// // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt -// func main() { -// var bucket, key string -// var timeout time.Duration -// -// flag.StringVar(&bucket, "b", "", "Bucket name.") -// flag.StringVar(&key, "k", "", "Object key name.") -// flag.DurationVar(&timeout, "d", 0, "Upload timeout.") -// flag.Parse() -// -// // All clients require a Session. The Session provides the client with -// // shared configuration such as region, endpoint, and credentials. A -// // Session should be shared where possible to take advantage of -// // configuration and credential caching. See the session package for -// // more information. -// sess := session.Must(session.NewSession()) -// -// // Create a new instance of the service's client with a Session. -// // Optional aws.Config values can also be provided as variadic arguments -// // to the New function. This option allows you to provide service -// // specific configuration. -// svc := s3.New(sess) -// -// // Create a context with a timeout that will abort the upload if it takes -// // more than the passed in timeout. -// ctx := context.Background() -// var cancelFn func() -// if timeout > 0 { -// ctx, cancelFn = context.WithTimeout(ctx, timeout) -// } -// // Ensure the context is canceled to prevent leaking. -// // See context package for more information, https://golang.org/pkg/context/ -// defer cancelFn() -// -// // Uploads the object to S3. The Context will interrupt the request if the -// // timeout expires. -// _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ -// Bucket: aws.String(bucket), -// Key: aws.String(key), -// Body: os.Stdin, -// }) -// if err != nil { -// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { -// // If the SDK can determine the request or retry delay was canceled -// // by a context the CanceledErrorCode error code will be returned. -// fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) -// } else { -// fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) -// } -// os.Exit(1) -// } -// -// fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) -// } -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go deleted file mode 100644 index ebcbc2b40a..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults - -import ( - "os" - "path/filepath" - "runtime" -) - -// SharedCredentialsFilename returns the SDK's default file path -// for the shared credentials file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/credentials -// - Windows: %USERPROFILE%\.aws\credentials -func SharedCredentialsFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "credentials") -} - -// SharedConfigFilename returns the SDK's default file path for -// the shared config file. -// -// Builds the shared config file path based on the OS's platform. -// -// - Linux/Unix: $HOME/.aws/config -// - Windows: %USERPROFILE%\.aws\config -func SharedConfigFilename() string { - return filepath.Join(UserHomeDir(), ".aws", "config") -} - -// UserHomeDir returns the home directory for the user the process is -// running under. -func UserHomeDir() string { - if runtime.GOOS == "windows" { // Windows - return os.Getenv("USERPROFILE") - } - - // *nix - return os.Getenv("HOME") -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go deleted file mode 100644 index 53831dff98..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go +++ /dev/null @@ -1,75 +0,0 @@ -package protocol - -import ( - "crypto/rand" - "fmt" - "reflect" -) - -// RandReader is the random reader the protocol package will use to read -// random bytes from. This is exported for testing, and should not be used. -var RandReader = rand.Reader - -const idempotencyTokenFillTag = `idempotencyToken` - -// CanSetIdempotencyToken returns true if the struct field should be -// automatically populated with a Idempotency token. -// -// Only *string and string type fields that are tagged with idempotencyToken -// which are not already set can be auto filled. -func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool { - switch u := v.Interface().(type) { - // To auto fill an Idempotency token the field must be a string, - // tagged for auto fill, and have a zero value. - case *string: - return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - case string: - return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - } - - return false -} - -// GetIdempotencyToken returns a randomly generated idempotency token. -func GetIdempotencyToken() string { - b := make([]byte, 16) - RandReader.Read(b) - - return UUIDVersion4(b) -} - -// SetIdempotencyToken will set the value provided with a Idempotency Token. -// Given that the value can be set. Will panic if value is not setable. -func SetIdempotencyToken(v reflect.Value) { - if v.Kind() == reflect.Ptr { - if v.IsNil() && v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - v = reflect.Indirect(v) - - if !v.CanSet() { - panic(fmt.Sprintf("unable to set idempotnecy token %v", v)) - } - - b := make([]byte, 16) - _, err := rand.Read(b) - if err != nil { - // TODO handle error - return - } - - v.Set(reflect.ValueOf(UUIDVersion4(b))) -} - -// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided -func UUIDVersion4(u []byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - // 13th character is "4" - u[6] = (u[6] | 0x40) & 0x4F - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] | 0x80) & 0xBF - - return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go deleted file mode 100644 index 18169f0f8c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go +++ /dev/null @@ -1,36 +0,0 @@ -// Package query provides serialization of AWS query requests, and responses. -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/query.json build_test.go - -import ( - "net/url" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query/queryutil" -) - -// BuildHandler is a named request handler for building query protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.query.Build", Fn: Build} - -// Build builds a request for an AWS Query service. -func Build(r *request.Request) { - body := url.Values{ - "Action": {r.Operation.Name}, - "Version": {r.ClientInfo.APIVersion}, - } - if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = awserr.New("SerializationError", "failed encoding Query request", err) - return - } - - if r.ExpireTime == 0 { - r.HTTPRequest.Method = "POST" - r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - r.SetBufferBody([]byte(body.Encode())) - } else { // This is a pre-signed request - r.HTTPRequest.Method = "GET" - r.HTTPRequest.URL.RawQuery = body.Encode() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go deleted file mode 100644 index 524ca952ad..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ /dev/null @@ -1,237 +0,0 @@ -package queryutil - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// Parse parses an object i and fills a url.Values object. The isEC2 flag -// indicates if this is the EC2 Query sub-protocol. -func Parse(body url.Values, i interface{}, isEC2 bool) error { - q := queryParser{isEC2: isEC2} - return q.parseValue(body, reflect.ValueOf(i), "", "") -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type queryParser struct { - isEC2 bool -} - -func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - value = elemOf(value) - - // no need to handle zero values - if !value.IsValid() { - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - return q.parseStruct(v, value, prefix) - case "list": - return q.parseList(v, value, prefix, tag) - case "map": - return q.parseMap(v, value, prefix, tag) - default: - return q.parseScalar(v, value, prefix, tag) - } -} - -func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { - if !value.IsValid() { - return nil - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - elemValue := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - elemValue = reflect.ValueOf(token) - } - - var name string - if q.isEC2 { - name = field.Tag.Get("queryName") - } - if name == "" { - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if name != "" && q.isEC2 { - name = strings.ToUpper(name[0:1]) + name[1:] - } - } - if name == "" { - name = field.Name - } - - if prefix != "" { - name = prefix + "." + name - } - - if err := q.parseValue(v, elemValue, name, field.Tag); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - if listName := tag.Get("locationNameList"); listName == "" { - prefix += ".member" - } else { - prefix += "." + listName - } - } - - for i := 0; i < value.Len(); i++ { - slicePrefix := prefix - if slicePrefix == "" { - slicePrefix = strconv.Itoa(i + 1) - } else { - slicePrefix = slicePrefix + "." + strconv.Itoa(i+1) - } - if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".entry" - } - - // sort keys for improved serialization consistency. - // this is not strictly necessary for protocol support. - mapKeyValues := value.MapKeys() - mapKeys := map[string]reflect.Value{} - mapKeyNames := make([]string, len(mapKeyValues)) - for i, mapKey := range mapKeyValues { - name := mapKey.String() - mapKeys[name] = mapKey - mapKeyNames[i] = name - } - sort.Strings(mapKeyNames) - - for i, mapKeyName := range mapKeyNames { - mapKey := mapKeys[mapKeyName] - mapValue := value.MapIndex(mapKey) - - kname := tag.Get("locationNameKey") - if kname == "" { - kname = "key" - } - vname := tag.Get("locationNameValue") - if vname == "" { - vname = "value" - } - - // serialize key - var keyName string - if prefix == "" { - keyName = strconv.Itoa(i+1) + "." + kname - } else { - keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname - } - - if err := q.parseValue(v, mapKey, keyName, ""); err != nil { - return err - } - - // serialize value - var valueName string - if prefix == "" { - valueName = strconv.Itoa(i+1) + "." + vname - } else { - valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname - } - - if err := q.parseValue(v, mapValue, valueName, ""); err != nil { - return err - } - } - - return nil -} - -func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { - switch value := r.Interface().(type) { - case string: - v.Set(name, value) - case []byte: - if !r.IsNil() { - v.Set(name, base64.StdEncoding.EncodeToString(value)) - } - case bool: - v.Set(name, strconv.FormatBool(value)) - case int64: - v.Set(name, strconv.FormatInt(value, 10)) - case int: - v.Set(name, strconv.Itoa(value)) - case float64: - v.Set(name, strconv.FormatFloat(value, 'f', -1, 64)) - case float32: - v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - v.Set(name, value.UTC().Format(ISO8601UTC)) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go deleted file mode 100644 index e0f4d5a541..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go +++ /dev/null @@ -1,35 +0,0 @@ -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/query.json unmarshal_test.go - -import ( - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// UnmarshalHandler is a named request handler for unmarshaling query protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.query.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling query protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals a response for an AWS Query service. -func Unmarshal(r *request.Request) { - defer r.HTTPResponse.Body.Close() - if r.DataFilled() { - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") - if err != nil { - r.Error = awserr.New("SerializationError", "failed decoding Query response", err) - return - } - } -} - -// UnmarshalMeta unmarshals header response values for an AWS Query service. -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go deleted file mode 100644 index f214296171..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go +++ /dev/null @@ -1,66 +0,0 @@ -package query - -import ( - "encoding/xml" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type xmlServiceUnavailableResponse struct { - XMLName xml.Name `xml:"ServiceUnavailableException"` -} - -// UnmarshalErrorHandler is a name request handler to unmarshal request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalError", Fn: UnmarshalError} - -// UnmarshalError unmarshals an error response for an AWS Query service. -func UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to read from query HTTP response body", err) - return - } - - // First check for specific error - resp := xmlErrorResponse{} - decodeErr := xml.Unmarshal(bodyBytes, &resp) - if decodeErr == nil { - reqID := resp.RequestID - if reqID == "" { - reqID = r.RequestID - } - r.Error = awserr.NewRequestFailure( - awserr.New(resp.Code, resp.Message, nil), - r.HTTPResponse.StatusCode, - reqID, - ) - return - } - - // Check for unhandled error - servUnavailResp := xmlServiceUnavailableResponse{} - unavailErr := xml.Unmarshal(bodyBytes, &servUnavailResp) - if unavailErr == nil { - r.Error = awserr.NewRequestFailure( - awserr.New("ServiceUnavailableException", "service is unavailable", nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - // Failed to retrieve any error message from the response body - r.Error = awserr.New("SerializationError", - "failed to decode query XML error response", decodeErr) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go deleted file mode 100644 index 7161835649..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ /dev/null @@ -1,290 +0,0 @@ -// Package rest provides RESTful serialization of AWS requests and responses. -package rest - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// RFC822 returns an RFC822 formatted timestamp for AWS protocols -const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT" - -// Whether the byte value can be sent without escaping in AWS URLs -var noEscape [256]bool - -var errValueNotSet = fmt.Errorf("value not set") - -func init() { - for i := 0; i < len(noEscape); i++ { - // AWS expects every character except these to be escaped - noEscape[i] = (i >= 'A' && i <= 'Z') || - (i >= 'a' && i <= 'z') || - (i >= '0' && i <= '9') || - i == '-' || - i == '.' || - i == '_' || - i == '~' - } -} - -// BuildHandler is a named request handler for building rest protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build} - -// Build builds the REST component of a service request. -func Build(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, false) - buildBody(r, v) - } -} - -// BuildAsGET builds the REST component of a service request with the ability to hoist -// data from the body. -func BuildAsGET(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, true) - buildBody(r, v) - } -} - -func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { - query := r.HTTPRequest.URL.Query() - - // Setup the raw path to match the base path pattern. This is needed - // so that when the path is mutated a custom escaped version can be - // stored in RawPath that will be used by the Go client. - r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path - - for i := 0; i < v.NumField(); i++ { - m := v.Field(i) - if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - field := v.Type().Field(i) - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - if kind := m.Kind(); kind == reflect.Ptr { - m = m.Elem() - } else if kind == reflect.Interface { - if !m.Elem().IsValid() { - continue - } - } - if !m.IsValid() { - continue - } - if field.Tag.Get("ignore") != "" { - continue - } - - var err error - switch field.Tag.Get("location") { - case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) - case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) - case "uri": - err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) - case "querystring": - err = buildQueryString(query, m, name, field.Tag) - default: - if buildGETQuery { - err = buildQueryString(query, m, name, field.Tag) - } - } - r.Error = err - } - if r.Error != nil { - return - } - } - - r.HTTPRequest.URL.RawQuery = query.Encode() - if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) { - cleanPath(r.HTTPRequest.URL) - } -} - -func buildBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() && payload.Interface() != nil { - switch reader := payload.Interface().(type) { - case io.ReadSeeker: - r.SetReaderBody(reader) - case []byte: - r.SetBufferBody(reader) - case string: - r.SetStringBody(reader) - default: - r.Error = awserr.New("SerializationError", - "failed to encode REST request", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } -} - -func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - header.Add(name, str) - - return nil -} - -func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { - prefix := tag.Get("locationName") - for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key), tag) - if err == errValueNotSet { - continue - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - - } - - header.Add(prefix+key.String(), str) - } - return nil -} - -func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { - value, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1) - u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1) - - u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1) - u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1) - - return nil -} - -func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { - switch value := v.Interface().(type) { - case []*string: - for _, item := range value { - query.Add(name, *item) - } - case map[string]*string: - for key, item := range value { - query.Add(key, *item) - } - case map[string][]*string: - for key, items := range value { - for _, item := range items { - query.Add(key, *item) - } - } - default: - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - query.Set(name, str) - } - - return nil -} - -func cleanPath(u *url.URL) { - hasSlash := strings.HasSuffix(u.Path, "/") - - // clean up path, removing duplicate `/` - u.Path = path.Clean(u.Path) - u.RawPath = path.Clean(u.RawPath) - - if hasSlash && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - u.RawPath += "/" - } -} - -// EscapePath escapes part of a URL path in Amazon style -func EscapePath(path string, encodeSep bool) string { - var buf bytes.Buffer - for i := 0; i < len(path); i++ { - c := path[i] - if noEscape[c] || (c == '/' && !encodeSep) { - buf.WriteByte(c) - } else { - fmt.Fprintf(&buf, "%%%02X", c) - } - } - return buf.String() -} - -func convertType(v reflect.Value, tag reflect.StructTag) (string, error) { - v = reflect.Indirect(v) - if !v.IsValid() { - return "", errValueNotSet - } - - var str string - switch value := v.Interface().(type) { - case string: - str = value - case []byte: - str = base64.StdEncoding.EncodeToString(value) - case bool: - str = strconv.FormatBool(value) - case int64: - str = strconv.FormatInt(value, 10) - case float64: - str = strconv.FormatFloat(value, 'f', -1, 64) - case time.Time: - str = value.UTC().Format(RFC822) - case aws.JSONValue: - b, err := json.Marshal(value) - if err != nil { - return "", err - } - if tag.Get("location") == "header" { - str = base64.StdEncoding.EncodeToString(b) - } else { - str = string(b) - } - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return "", err - } - return str, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go deleted file mode 100644 index 4366de2e1e..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go +++ /dev/null @@ -1,45 +0,0 @@ -package rest - -import "reflect" - -// PayloadMember returns the payload field member of i if there is one, or nil. -func PayloadMember(i interface{}) interface{} { - if i == nil { - return nil - } - - v := reflect.ValueOf(i).Elem() - if !v.IsValid() { - return nil - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - field, _ := v.Type().FieldByName(payloadName) - if field.Tag.Get("type") != "structure" { - return nil - } - - payload := v.FieldByName(payloadName) - if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { - return payload.Interface() - } - } - } - return nil -} - -// PayloadType returns the type of a payload field member of i if there is one, or "". -func PayloadType(i interface{}) string { - v := reflect.Indirect(reflect.ValueOf(i)) - if !v.IsValid() { - return "" - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - if member, ok := v.Type().FieldByName(payloadName); ok { - return member.Tag.Get("type") - } - } - } - return "" -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go deleted file mode 100644 index 7a779ee226..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ /dev/null @@ -1,227 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals the REST component of a response in a REST service. -func Unmarshal(r *request.Request) { - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalBody(r, v) - } -} - -// UnmarshalMeta unmarshals the REST metadata of a response in a REST service -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") - if r.RequestID == "" { - // Alternative version of request id in the header - r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id") - } - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalLocationElements(r, v) - } -} - -func unmarshalBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := v.FieldByName(payloadName) - if payload.IsValid() { - switch payload.Interface().(type) { - case []byte: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - payload.Set(reflect.ValueOf(b)) - } - case *string: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - str := string(b) - payload.Set(reflect.ValueOf(&str)) - } - default: - switch payload.Type().String() { - case "io.ReadCloser": - payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) - case "io.ReadSeeker": - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", - "failed to read response body", err) - return - } - payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b)))) - default: - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - defer r.HTTPResponse.Body.Close() - r.Error = awserr.New("SerializationError", - "failed to decode REST response", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } - } -} - -func unmarshalLocationElements(r *request.Request, v reflect.Value) { - for i := 0; i < v.NumField(); i++ { - m, field := v.Field(i), v.Type().Field(i) - if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - - switch field.Tag.Get("location") { - case "statusCode": - unmarshalStatusCode(m, r.HTTPResponse.StatusCode) - case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - case "headers": - prefix := field.Tag.Get("locationName") - err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - } - } - if r.Error != nil { - return - } - } -} - -func unmarshalStatusCode(v reflect.Value, statusCode int) { - if !v.IsValid() { - return - } - - switch v.Interface().(type) { - case *int64: - s := int64(statusCode) - v.Set(reflect.ValueOf(&s)) - } -} - -func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { - switch r.Interface().(type) { - case map[string]*string: // we only support string map value types - out := map[string]*string{} - for k, v := range headers { - k = http.CanonicalHeaderKey(k) - if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { - out[k[len(prefix):]] = &v[0] - } - } - r.Set(reflect.ValueOf(out)) - } - return nil -} - -func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { - isJSONValue := tag.Get("type") == "jsonvalue" - if isJSONValue { - if len(header) == 0 { - return nil - } - } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { - return nil - } - - switch v.Interface().(type) { - case *string: - v.Set(reflect.ValueOf(&header)) - case []byte: - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *bool: - b, err := strconv.ParseBool(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *int64: - i, err := strconv.ParseInt(header, 10, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&i)) - case *float64: - f, err := strconv.ParseFloat(header, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&f)) - case *time.Time: - t, err := time.Parse(RFC822, header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - b := []byte(header) - var err error - if tag.Get("location") == "header" { - b, err = base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } - } - - m := aws.JSONValue{} - err = json.Unmarshal(b, &m) - if err != nil { - return err - } - v.Set(reflect.ValueOf(m)) - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go deleted file mode 100644 index 7bdf4c8538..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package restxml provides RESTful XML serialization of AWS -// requests and responses. -package restxml - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/rest-xml.json build_test.go -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/rest-xml.json unmarshal_test.go - -import ( - "bytes" - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/rest" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// BuildHandler is a named request handler for building restxml protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.restxml.Build", Fn: Build} - -// UnmarshalHandler is a named request handler for unmarshaling restxml protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.restxml.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling restxml protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalMeta", Fn: UnmarshalMeta} - -// UnmarshalErrorHandler is a named request handler for unmarshaling restxml protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalError", Fn: UnmarshalError} - -// Build builds a request payload for the REST XML protocol. -func Build(r *request.Request) { - rest.Build(r) - - if t := rest.PayloadType(r.Params); t == "structure" || t == "" { - var buf bytes.Buffer - err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to encode rest XML request", err) - return - } - r.SetBufferBody(buf.Bytes()) - } -} - -// Unmarshal unmarshals a payload response for the REST XML protocol. -func Unmarshal(r *request.Request) { - if t := rest.PayloadType(r.Data); t == "structure" || t == "" { - defer r.HTTPResponse.Body.Close() - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, "") - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) - return - } - } else { - rest.Unmarshal(r) - } -} - -// UnmarshalMeta unmarshals response headers for the REST XML protocol. -func UnmarshalMeta(r *request.Request) { - rest.UnmarshalMeta(r) -} - -// UnmarshalError unmarshals a response error for the REST XML protocol. -func UnmarshalError(r *request.Request) { - query.UnmarshalError(r) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go deleted file mode 100644 index da1a68111d..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go +++ /dev/null @@ -1,21 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body -var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody} - -// UnmarshalDiscardBody is a request handler to empty a response's body and closing it. -func UnmarshalDiscardBody(r *request.Request) { - if r.HTTPResponse == nil || r.HTTPResponse.Body == nil { - return - } - - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - r.HTTPResponse.Body.Close() -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go deleted file mode 100644 index 7091b456d1..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ /dev/null @@ -1,296 +0,0 @@ -// Package xmlutil provides XML serialization of AWS requests and responses. -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// BuildXML will serialize params into an xml.Encoder. -// Error will be returned if the serialization of any of the params or nested values fails. -func BuildXML(params interface{}, e *xml.Encoder) error { - b := xmlBuilder{encoder: e, namespaces: map[string]string{}} - root := NewXMLElement(xml.Name{}) - if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { - return err - } - for _, c := range root.Children { - for _, v := range c { - return StructToXML(e, v, false) - } - } - return nil -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -// A xmlBuilder serializes values from Go code to XML -type xmlBuilder struct { - encoder *xml.Encoder - namespaces map[string]string -} - -// buildValue generic XMLNode builder for any type. Will build value for their specific type -// struct, list, map, scalar. -// -// Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If -// type is not provided reflect will be used to determine the value's type. -func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - value = elemOf(value) - if !value.IsValid() { // no need to handle zero values - return nil - } else if tag.Get("location") != "" { // don't handle non-body location values - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := value.Type().FieldByName("_"); ok { - tag = tag + reflect.StructTag(" ") + field.Tag - } - return b.buildStruct(value, current, tag) - case "list": - return b.buildList(value, current, tag) - case "map": - return b.buildMap(value, current, tag) - default: - return b.buildScalar(value, current, tag) - } -} - -// buildStruct adds a struct and its fields to the current XMLNode. All fields any any nested -// types are converted to XMLNodes also. -func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - fieldAdded := false - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - child := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - - // there is an xmlNamespace associated with this struct - if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" { - ns := xml.Attr{ - Name: xml.Name{Local: "xmlns"}, - Value: uri, - } - if prefix != "" { - b.namespaces[prefix] = uri // register the namespace - ns.Name.Local = "xmlns:" + prefix - } - - child.Attr = append(child.Attr, ns) - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - member := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - mTag := field.Tag - if mTag.Get("location") != "" { // skip non-body members - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(token) - } - - memberName := mTag.Get("locationName") - if memberName == "" { - memberName = field.Name - mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`) - } - if err := b.buildValue(member, child, mTag); err != nil { - return err - } - - fieldAdded = true - } - - if fieldAdded { // only append this child if we have one ore more valid members - current.AddChild(child) - } - - return nil -} - -// buildList adds the value's list items to the current XMLNode as children nodes. All -// nested values in the list are converted to XMLNodes also. -func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted lists - return nil - } - - // check for unflattened list member - flattened := tag.Get("flattened") != "" - - xname := xml.Name{Local: tag.Get("locationName")} - if flattened { - for i := 0; i < value.Len(); i++ { - child := NewXMLElement(xname) - current.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } else { - list := NewXMLElement(xname) - current.AddChild(list) - - for i := 0; i < value.Len(); i++ { - iname := tag.Get("locationNameList") - if iname == "" { - iname = "member" - } - - child := NewXMLElement(xml.Name{Local: iname}) - list.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } - - return nil -} - -// buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All -// nested values in the map are converted to XMLNodes also. -// -// Error will be returned if it is unable to build the map's values into XMLNodes -func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted maps - return nil - } - - maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - current.AddChild(maproot) - current = maproot - - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - // sorting is not required for compliance, but it makes testing easier - keys := make([]string, value.Len()) - for i, k := range value.MapKeys() { - keys[i] = k.String() - } - sort.Strings(keys) - - for _, k := range keys { - v := value.MapIndex(reflect.ValueOf(k)) - - mapcur := current - if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps - child := NewXMLElement(xml.Name{Local: "entry"}) - mapcur.AddChild(child) - mapcur = child - } - - kchild := NewXMLElement(xml.Name{Local: kname}) - kchild.Text = k - vchild := NewXMLElement(xml.Name{Local: vname}) - mapcur.AddChild(kchild) - mapcur.AddChild(vchild) - - if err := b.buildValue(v, vchild, ""); err != nil { - return err - } - } - - return nil -} - -// buildScalar will convert the value into a string and append it as a attribute or child -// of the current XMLNode. -// -// The value will be added as an attribute if tag contains a "xmlAttribute" attribute value. -// -// Error will be returned if the value type is unsupported. -func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - var str string - switch converted := value.Interface().(type) { - case string: - str = converted - case []byte: - if !value.IsNil() { - str = base64.StdEncoding.EncodeToString(converted) - } - case bool: - str = strconv.FormatBool(converted) - case int64: - str = strconv.FormatInt(converted, 10) - case int: - str = strconv.Itoa(converted) - case float64: - str = strconv.FormatFloat(converted, 'f', -1, 64) - case float32: - str = strconv.FormatFloat(float64(converted), 'f', -1, 32) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - str = converted.UTC().Format(ISO8601UTC) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", - tag.Get("locationName"), value.Interface(), value.Type().Name()) - } - - xname := xml.Name{Local: tag.Get("locationName")} - if tag.Get("xmlAttribute") != "" { // put into current node's attribute list - attr := xml.Attr{Name: xname, Value: str} - current.Attr = append(current.Attr, attr) - } else { // regular text node - current.AddChild(&XMLNode{Name: xname, Text: str}) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go deleted file mode 100644 index 87584628a2..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ /dev/null @@ -1,260 +0,0 @@ -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "io" - "reflect" - "strconv" - "strings" - "time" -) - -// UnmarshalXML deserializes an xml.Decoder into the container v. V -// needs to match the shape of the XML expected to be decoded. -// If the shape doesn't match unmarshaling will fail. -func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, err := XMLToStruct(d, nil) - if err != nil { - return err - } - if n.Children != nil { - for _, root := range n.Children { - for _, c := range root { - if wrappedChild, ok := c.Children[wrapper]; ok { - c = wrappedChild[0] // pull out wrapped element - } - - err = parse(reflect.ValueOf(v), c, "") - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } - } - return nil - } - return nil -} - -// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect -// will be used to determine the type from r. -func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - rtype := r.Type() - if rtype.Kind() == reflect.Ptr { - rtype = rtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch rtype.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := rtype.FieldByName("_"); ok { - tag = field.Tag - } - return parseStruct(r, node, tag) - case "list": - return parseList(r, node, tag) - case "map": - return parseMap(r, node, tag) - default: - return parseScalar(r, node, tag) - } -} - -// parseStruct deserializes a structure and its fields from an XMLNode. Any nested -// types in the structure will also be deserialized. -func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - if r.IsNil() { // create the structure if it's nil - s := reflect.New(r.Type().Elem()) - r.Set(s) - r = s - } - - r = r.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return parseStruct(r.FieldByName(payload), node, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if c := field.Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - // try to find the field by name in elements - elems := node.Children[name] - - if elems == nil { // try to find the field in attributes - if val, ok := node.findElem(name); ok { - elems = []*XMLNode{{Text: val}} - } - } - - member := r.FieldByName(field.Name) - for _, elem := range elems { - err := parse(member, elem, field.Tag) - if err != nil { - return err - } - } - } - return nil -} - -// parseList deserializes a list of values from an XML node. Each list entry -// will also be deserialized. -func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - - if tag.Get("flattened") == "" { // look at all item entries - mname := "member" - if name := tag.Get("locationNameList"); name != "" { - mname = name - } - - if Children, ok := node.Children[mname]; ok { - if r.IsNil() { - r.Set(reflect.MakeSlice(t, len(Children), len(Children))) - } - - for i, c := range Children { - err := parse(r.Index(i), c, "") - if err != nil { - return err - } - } - } - } else { // flattened list means this is a single element - if r.IsNil() { - r.Set(reflect.MakeSlice(t, 0, 0)) - } - - childR := reflect.Zero(t.Elem()) - r.Set(reflect.Append(r, childR)) - err := parse(r.Index(r.Len()-1), node, "") - if err != nil { - return err - } - } - - return nil -} - -// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode -// will also be deserialized as map entries. -func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - if r.IsNil() { - r.Set(reflect.MakeMap(r.Type())) - } - - if tag.Get("flattened") == "" { // look at all child entries - for _, entry := range node.Children["entry"] { - parseMapEntry(r, entry, tag) - } - } else { // this element is itself an entry - parseMapEntry(r, node, tag) - } - - return nil -} - -// parseMapEntry deserializes a map entry from a XML node. -func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - keys, ok := node.Children[kname] - values := node.Children[vname] - if ok { - for i, key := range keys { - keyR := reflect.ValueOf(key.Text) - value := values[i] - valueR := reflect.New(r.Type().Elem()).Elem() - - parse(valueR, value, "") - r.SetMapIndex(keyR, valueR) - } - } - return nil -} - -// parseScaller deserializes an XMLNode value into a concrete type based on the -// interface type of r. -// -// Error is returned if the deserialization fails due to invalid type conversion, -// or unsupported interface type. -func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - switch r.Interface().(type) { - case *string: - r.Set(reflect.ValueOf(&node.Text)) - return nil - case []byte: - b, err := base64.StdEncoding.DecodeString(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(b)) - case *bool: - v, err := strconv.ParseBool(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *int64: - v, err := strconv.ParseInt(node.Text, 10, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *float64: - v, err := strconv.ParseFloat(node.Text, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - t, err := time.Parse(ISO8601UTC, node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go deleted file mode 100644 index 3e970b629d..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ /dev/null @@ -1,147 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "sort" -) - -// A XMLNode contains the values to be encoded or decoded. -type XMLNode struct { - Name xml.Name `json:",omitempty"` - Children map[string][]*XMLNode `json:",omitempty"` - Text string `json:",omitempty"` - Attr []xml.Attr `json:",omitempty"` - - namespaces map[string]string - parent *XMLNode -} - -// NewXMLElement returns a pointer to a new XMLNode initialized to default values. -func NewXMLElement(name xml.Name) *XMLNode { - return &XMLNode{ - Name: name, - Children: map[string][]*XMLNode{}, - Attr: []xml.Attr{}, - } -} - -// AddChild adds child to the XMLNode. -func (n *XMLNode) AddChild(child *XMLNode) { - if _, ok := n.Children[child.Name.Local]; !ok { - n.Children[child.Name.Local] = []*XMLNode{} - } - n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child) -} - -// XMLToStruct converts a xml.Decoder stream to XMLNode with nested values. -func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { - out := &XMLNode{} - for { - tok, err := d.Token() - if err != nil { - if err == io.EOF { - break - } else { - return out, err - } - } - - if tok == nil { - break - } - - switch typed := tok.(type) { - case xml.CharData: - out.Text = string(typed.Copy()) - case xml.StartElement: - el := typed.Copy() - out.Attr = el.Attr - if out.Children == nil { - out.Children = map[string][]*XMLNode{} - } - - name := typed.Name.Local - slice := out.Children[name] - if slice == nil { - slice = []*XMLNode{} - } - node, e := XMLToStruct(d, &el) - out.findNamespaces() - if e != nil { - return out, e - } - node.Name = typed.Name - node.findNamespaces() - tempOut := *out - // Save into a temp variable, simply because out gets squashed during - // loop iterations - node.parent = &tempOut - slice = append(slice, node) - out.Children[name] = slice - case xml.EndElement: - if s != nil && s.Name.Local == typed.Name.Local { // matching end token - return out, nil - } - out = &XMLNode{} - } - } - return out, nil -} - -func (n *XMLNode) findNamespaces() { - ns := map[string]string{} - for _, a := range n.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - } - } - - n.namespaces = ns -} - -func (n *XMLNode) findElem(name string) (string, bool) { - for node := n; node != nil; node = node.parent { - for _, a := range node.Attr { - namespace := a.Name.Space - if v, ok := node.namespaces[namespace]; ok { - namespace = v - } - if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) { - return a.Value, true - } - } - } - return "", false -} - -// StructToXML writes an XMLNode to a xml.Encoder as tokens. -func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error { - e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr}) - - if node.Text != "" { - e.EncodeToken(xml.CharData([]byte(node.Text))) - } else if sorted { - sortedNames := []string{} - for k := range node.Children { - sortedNames = append(sortedNames, k) - } - sort.Strings(sortedNames) - - for _, k := range sortedNames { - for _, v := range node.Children[k] { - StructToXML(e, v, sorted) - } - } - } else { - for _, c := range node.Children { - for _, v := range c { - StructToXML(e, v, sorted) - } - } - } - - e.EncodeToken(xml.EndElement{Name: node.Name}) - return e.Flush() -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go b/vendor/github.com/aws/aws-sdk-go/service/s3/api.go deleted file mode 100644 index 564a39651c..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/api.go +++ /dev/null @@ -1,21374 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package s3 - -import ( - "fmt" - "io" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -const opAbortMultipartUpload = "AbortMultipartUpload" - -// AbortMultipartUploadRequest generates a "aws/request.Request" representing the -// client's request for the AbortMultipartUpload operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AbortMultipartUpload for more information on using the AbortMultipartUpload -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AbortMultipartUploadRequest method. -// req, resp := client.AbortMultipartUploadRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload -func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *request.Request, output *AbortMultipartUploadOutput) { - op := &request.Operation{ - Name: opAbortMultipartUpload, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &AbortMultipartUploadInput{} - } - - output = &AbortMultipartUploadOutput{} - req = c.newRequest(op, input, output) - return -} - -// AbortMultipartUpload API operation for Amazon Simple Storage Service. -// -// Aborts a multipart upload. -// -// To verify that all parts have been removed, so you don't get charged for -// the part storage, you should call the List Parts operation and ensure the -// parts list is empty. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation AbortMultipartUpload for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchUpload "NoSuchUpload" -// The specified multipart upload does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUpload -func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMultipartUploadOutput, error) { - req, out := c.AbortMultipartUploadRequest(input) - return out, req.Send() -} - -// AbortMultipartUploadWithContext is the same as AbortMultipartUpload with the addition of -// the ability to pass a context and additional request options. -// -// See AbortMultipartUpload for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) AbortMultipartUploadWithContext(ctx aws.Context, input *AbortMultipartUploadInput, opts ...request.Option) (*AbortMultipartUploadOutput, error) { - req, out := c.AbortMultipartUploadRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCompleteMultipartUpload = "CompleteMultipartUpload" - -// CompleteMultipartUploadRequest generates a "aws/request.Request" representing the -// client's request for the CompleteMultipartUpload operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CompleteMultipartUpload for more information on using the CompleteMultipartUpload -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CompleteMultipartUploadRequest method. -// req, resp := client.CompleteMultipartUploadRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload -func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *request.Request, output *CompleteMultipartUploadOutput) { - op := &request.Operation{ - Name: opCompleteMultipartUpload, - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &CompleteMultipartUploadInput{} - } - - output = &CompleteMultipartUploadOutput{} - req = c.newRequest(op, input, output) - return -} - -// CompleteMultipartUpload API operation for Amazon Simple Storage Service. -// -// Completes a multipart upload by assembling previously uploaded parts. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation CompleteMultipartUpload for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUpload -func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*CompleteMultipartUploadOutput, error) { - req, out := c.CompleteMultipartUploadRequest(input) - return out, req.Send() -} - -// CompleteMultipartUploadWithContext is the same as CompleteMultipartUpload with the addition of -// the ability to pass a context and additional request options. -// -// See CompleteMultipartUpload for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) CompleteMultipartUploadWithContext(ctx aws.Context, input *CompleteMultipartUploadInput, opts ...request.Option) (*CompleteMultipartUploadOutput, error) { - req, out := c.CompleteMultipartUploadRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCopyObject = "CopyObject" - -// CopyObjectRequest generates a "aws/request.Request" representing the -// client's request for the CopyObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CopyObject for more information on using the CopyObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CopyObjectRequest method. -// req, resp := client.CopyObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject -func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *request.Request, output *CopyObjectOutput) { - op := &request.Operation{ - Name: opCopyObject, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &CopyObjectInput{} - } - - output = &CopyObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// CopyObject API operation for Amazon Simple Storage Service. -// -// Creates a copy of an object that is already stored in Amazon S3. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation CopyObject for usage and error information. -// -// Returned Error Codes: -// * ErrCodeObjectNotInActiveTierError "ObjectNotInActiveTierError" -// The source object of the COPY operation is not in the active tier and is -// only stored in Amazon Glacier. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObject -func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { - req, out := c.CopyObjectRequest(input) - return out, req.Send() -} - -// CopyObjectWithContext is the same as CopyObject with the addition of -// the ability to pass a context and additional request options. -// -// See CopyObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) CopyObjectWithContext(ctx aws.Context, input *CopyObjectInput, opts ...request.Option) (*CopyObjectOutput, error) { - req, out := c.CopyObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateBucket = "CreateBucket" - -// CreateBucketRequest generates a "aws/request.Request" representing the -// client's request for the CreateBucket operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateBucket for more information on using the CreateBucket -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateBucketRequest method. -// req, resp := client.CreateBucketRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket -func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *request.Request, output *CreateBucketOutput) { - op := &request.Operation{ - Name: opCreateBucket, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}", - } - - if input == nil { - input = &CreateBucketInput{} - } - - output = &CreateBucketOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateBucket API operation for Amazon Simple Storage Service. -// -// Creates a new bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation CreateBucket for usage and error information. -// -// Returned Error Codes: -// * ErrCodeBucketAlreadyExists "BucketAlreadyExists" -// The requested bucket name is not available. The bucket namespace is shared -// by all users of the system. Please select a different name and try again. -// -// * ErrCodeBucketAlreadyOwnedByYou "BucketAlreadyOwnedByYou" -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucket -func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) { - req, out := c.CreateBucketRequest(input) - return out, req.Send() -} - -// CreateBucketWithContext is the same as CreateBucket with the addition of -// the ability to pass a context and additional request options. -// -// See CreateBucket for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) CreateBucketWithContext(ctx aws.Context, input *CreateBucketInput, opts ...request.Option) (*CreateBucketOutput, error) { - req, out := c.CreateBucketRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateMultipartUpload = "CreateMultipartUpload" - -// CreateMultipartUploadRequest generates a "aws/request.Request" representing the -// client's request for the CreateMultipartUpload operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateMultipartUpload for more information on using the CreateMultipartUpload -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateMultipartUploadRequest method. -// req, resp := client.CreateMultipartUploadRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload -func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *request.Request, output *CreateMultipartUploadOutput) { - op := &request.Operation{ - Name: opCreateMultipartUpload, - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?uploads", - } - - if input == nil { - input = &CreateMultipartUploadInput{} - } - - output = &CreateMultipartUploadOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateMultipartUpload API operation for Amazon Simple Storage Service. -// -// Initiates a multipart upload and returns an upload ID. -// -// Note: After you initiate multipart upload and upload one or more parts, you -// must either complete or abort multipart upload in order to stop getting charged -// for storage of the uploaded parts. Only after you either complete or abort -// multipart upload, Amazon S3 frees up the parts storage and stops charging -// you for the parts storage. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation CreateMultipartUpload for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUpload -func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMultipartUploadOutput, error) { - req, out := c.CreateMultipartUploadRequest(input) - return out, req.Send() -} - -// CreateMultipartUploadWithContext is the same as CreateMultipartUpload with the addition of -// the ability to pass a context and additional request options. -// -// See CreateMultipartUpload for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) CreateMultipartUploadWithContext(ctx aws.Context, input *CreateMultipartUploadInput, opts ...request.Option) (*CreateMultipartUploadOutput, error) { - req, out := c.CreateMultipartUploadRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucket = "DeleteBucket" - -// DeleteBucketRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucket operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucket for more information on using the DeleteBucket -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketRequest method. -// req, resp := client.DeleteBucketRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket -func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *request.Request, output *DeleteBucketOutput) { - op := &request.Operation{ - Name: opDeleteBucket, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}", - } - - if input == nil { - input = &DeleteBucketInput{} - } - - output = &DeleteBucketOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucket API operation for Amazon Simple Storage Service. -// -// Deletes the bucket. All objects (including all object versions and Delete -// Markers) in the bucket must be deleted before the bucket itself can be deleted. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucket for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucket -func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) { - req, out := c.DeleteBucketRequest(input) - return out, req.Send() -} - -// DeleteBucketWithContext is the same as DeleteBucket with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucket for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketWithContext(ctx aws.Context, input *DeleteBucketInput, opts ...request.Option) (*DeleteBucketOutput, error) { - req, out := c.DeleteBucketRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketAnalyticsConfiguration = "DeleteBucketAnalyticsConfiguration" - -// DeleteBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketAnalyticsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketAnalyticsConfiguration for more information on using the DeleteBucketAnalyticsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketAnalyticsConfigurationRequest method. -// req, resp := client.DeleteBucketAnalyticsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration -func (c *S3) DeleteBucketAnalyticsConfigurationRequest(input *DeleteBucketAnalyticsConfigurationInput) (req *request.Request, output *DeleteBucketAnalyticsConfigurationOutput) { - op := &request.Operation{ - Name: opDeleteBucketAnalyticsConfiguration, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?analytics", - } - - if input == nil { - input = &DeleteBucketAnalyticsConfigurationInput{} - } - - output = &DeleteBucketAnalyticsConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketAnalyticsConfiguration API operation for Amazon Simple Storage Service. -// -// Deletes an analytics configuration for the bucket (specified by the analytics -// configuration ID). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfiguration -func (c *S3) DeleteBucketAnalyticsConfiguration(input *DeleteBucketAnalyticsConfigurationInput) (*DeleteBucketAnalyticsConfigurationOutput, error) { - req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) - return out, req.Send() -} - -// DeleteBucketAnalyticsConfigurationWithContext is the same as DeleteBucketAnalyticsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketAnalyticsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *DeleteBucketAnalyticsConfigurationInput, opts ...request.Option) (*DeleteBucketAnalyticsConfigurationOutput, error) { - req, out := c.DeleteBucketAnalyticsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketCors = "DeleteBucketCors" - -// DeleteBucketCorsRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketCors operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketCors for more information on using the DeleteBucketCors -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketCorsRequest method. -// req, resp := client.DeleteBucketCorsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors -func (c *S3) DeleteBucketCorsRequest(input *DeleteBucketCorsInput) (req *request.Request, output *DeleteBucketCorsOutput) { - op := &request.Operation{ - Name: opDeleteBucketCors, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?cors", - } - - if input == nil { - input = &DeleteBucketCorsInput{} - } - - output = &DeleteBucketCorsOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketCors API operation for Amazon Simple Storage Service. -// -// Deletes the cors configuration information set for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCors -func (c *S3) DeleteBucketCors(input *DeleteBucketCorsInput) (*DeleteBucketCorsOutput, error) { - req, out := c.DeleteBucketCorsRequest(input) - return out, req.Send() -} - -// DeleteBucketCorsWithContext is the same as DeleteBucketCors with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketCors for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketCorsWithContext(ctx aws.Context, input *DeleteBucketCorsInput, opts ...request.Option) (*DeleteBucketCorsOutput, error) { - req, out := c.DeleteBucketCorsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketEncryption = "DeleteBucketEncryption" - -// DeleteBucketEncryptionRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketEncryption operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketEncryption for more information on using the DeleteBucketEncryption -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketEncryptionRequest method. -// req, resp := client.DeleteBucketEncryptionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryption -func (c *S3) DeleteBucketEncryptionRequest(input *DeleteBucketEncryptionInput) (req *request.Request, output *DeleteBucketEncryptionOutput) { - op := &request.Operation{ - Name: opDeleteBucketEncryption, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?encryption", - } - - if input == nil { - input = &DeleteBucketEncryptionInput{} - } - - output = &DeleteBucketEncryptionOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketEncryption API operation for Amazon Simple Storage Service. -// -// Deletes the server-side encryption configuration from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketEncryption for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryption -func (c *S3) DeleteBucketEncryption(input *DeleteBucketEncryptionInput) (*DeleteBucketEncryptionOutput, error) { - req, out := c.DeleteBucketEncryptionRequest(input) - return out, req.Send() -} - -// DeleteBucketEncryptionWithContext is the same as DeleteBucketEncryption with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketEncryption for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketEncryptionWithContext(ctx aws.Context, input *DeleteBucketEncryptionInput, opts ...request.Option) (*DeleteBucketEncryptionOutput, error) { - req, out := c.DeleteBucketEncryptionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketInventoryConfiguration = "DeleteBucketInventoryConfiguration" - -// DeleteBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketInventoryConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketInventoryConfiguration for more information on using the DeleteBucketInventoryConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketInventoryConfigurationRequest method. -// req, resp := client.DeleteBucketInventoryConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration -func (c *S3) DeleteBucketInventoryConfigurationRequest(input *DeleteBucketInventoryConfigurationInput) (req *request.Request, output *DeleteBucketInventoryConfigurationOutput) { - op := &request.Operation{ - Name: opDeleteBucketInventoryConfiguration, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?inventory", - } - - if input == nil { - input = &DeleteBucketInventoryConfigurationInput{} - } - - output = &DeleteBucketInventoryConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketInventoryConfiguration API operation for Amazon Simple Storage Service. -// -// Deletes an inventory configuration (identified by the inventory ID) from -// the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfiguration -func (c *S3) DeleteBucketInventoryConfiguration(input *DeleteBucketInventoryConfigurationInput) (*DeleteBucketInventoryConfigurationOutput, error) { - req, out := c.DeleteBucketInventoryConfigurationRequest(input) - return out, req.Send() -} - -// DeleteBucketInventoryConfigurationWithContext is the same as DeleteBucketInventoryConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketInventoryConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketInventoryConfigurationWithContext(ctx aws.Context, input *DeleteBucketInventoryConfigurationInput, opts ...request.Option) (*DeleteBucketInventoryConfigurationOutput, error) { - req, out := c.DeleteBucketInventoryConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketLifecycle = "DeleteBucketLifecycle" - -// DeleteBucketLifecycleRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketLifecycle operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketLifecycle for more information on using the DeleteBucketLifecycle -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketLifecycleRequest method. -// req, resp := client.DeleteBucketLifecycleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle -func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *request.Request, output *DeleteBucketLifecycleOutput) { - op := &request.Operation{ - Name: opDeleteBucketLifecycle, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?lifecycle", - } - - if input == nil { - input = &DeleteBucketLifecycleInput{} - } - - output = &DeleteBucketLifecycleOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketLifecycle API operation for Amazon Simple Storage Service. -// -// Deletes the lifecycle configuration from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycle -func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBucketLifecycleOutput, error) { - req, out := c.DeleteBucketLifecycleRequest(input) - return out, req.Send() -} - -// DeleteBucketLifecycleWithContext is the same as DeleteBucketLifecycle with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketLifecycle for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketLifecycleWithContext(ctx aws.Context, input *DeleteBucketLifecycleInput, opts ...request.Option) (*DeleteBucketLifecycleOutput, error) { - req, out := c.DeleteBucketLifecycleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketMetricsConfiguration = "DeleteBucketMetricsConfiguration" - -// DeleteBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketMetricsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketMetricsConfiguration for more information on using the DeleteBucketMetricsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketMetricsConfigurationRequest method. -// req, resp := client.DeleteBucketMetricsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration -func (c *S3) DeleteBucketMetricsConfigurationRequest(input *DeleteBucketMetricsConfigurationInput) (req *request.Request, output *DeleteBucketMetricsConfigurationOutput) { - op := &request.Operation{ - Name: opDeleteBucketMetricsConfiguration, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?metrics", - } - - if input == nil { - input = &DeleteBucketMetricsConfigurationInput{} - } - - output = &DeleteBucketMetricsConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketMetricsConfiguration API operation for Amazon Simple Storage Service. -// -// Deletes a metrics configuration (specified by the metrics configuration ID) -// from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfiguration -func (c *S3) DeleteBucketMetricsConfiguration(input *DeleteBucketMetricsConfigurationInput) (*DeleteBucketMetricsConfigurationOutput, error) { - req, out := c.DeleteBucketMetricsConfigurationRequest(input) - return out, req.Send() -} - -// DeleteBucketMetricsConfigurationWithContext is the same as DeleteBucketMetricsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketMetricsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketMetricsConfigurationWithContext(ctx aws.Context, input *DeleteBucketMetricsConfigurationInput, opts ...request.Option) (*DeleteBucketMetricsConfigurationOutput, error) { - req, out := c.DeleteBucketMetricsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketPolicy = "DeleteBucketPolicy" - -// DeleteBucketPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketPolicy for more information on using the DeleteBucketPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketPolicyRequest method. -// req, resp := client.DeleteBucketPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy -func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *request.Request, output *DeleteBucketPolicyOutput) { - op := &request.Operation{ - Name: opDeleteBucketPolicy, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?policy", - } - - if input == nil { - input = &DeleteBucketPolicyInput{} - } - - output = &DeleteBucketPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketPolicy API operation for Amazon Simple Storage Service. -// -// Deletes the policy from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicy -func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPolicyOutput, error) { - req, out := c.DeleteBucketPolicyRequest(input) - return out, req.Send() -} - -// DeleteBucketPolicyWithContext is the same as DeleteBucketPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketPolicyWithContext(ctx aws.Context, input *DeleteBucketPolicyInput, opts ...request.Option) (*DeleteBucketPolicyOutput, error) { - req, out := c.DeleteBucketPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketReplication = "DeleteBucketReplication" - -// DeleteBucketReplicationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketReplication operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketReplication for more information on using the DeleteBucketReplication -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketReplicationRequest method. -// req, resp := client.DeleteBucketReplicationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication -func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *request.Request, output *DeleteBucketReplicationOutput) { - op := &request.Operation{ - Name: opDeleteBucketReplication, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?replication", - } - - if input == nil { - input = &DeleteBucketReplicationInput{} - } - - output = &DeleteBucketReplicationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketReplication API operation for Amazon Simple Storage Service. -// -// Deletes the replication configuration from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplication -func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*DeleteBucketReplicationOutput, error) { - req, out := c.DeleteBucketReplicationRequest(input) - return out, req.Send() -} - -// DeleteBucketReplicationWithContext is the same as DeleteBucketReplication with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketReplication for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketReplicationWithContext(ctx aws.Context, input *DeleteBucketReplicationInput, opts ...request.Option) (*DeleteBucketReplicationOutput, error) { - req, out := c.DeleteBucketReplicationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketTagging = "DeleteBucketTagging" - -// DeleteBucketTaggingRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketTagging for more information on using the DeleteBucketTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketTaggingRequest method. -// req, resp := client.DeleteBucketTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging -func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *request.Request, output *DeleteBucketTaggingOutput) { - op := &request.Operation{ - Name: opDeleteBucketTagging, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?tagging", - } - - if input == nil { - input = &DeleteBucketTaggingInput{} - } - - output = &DeleteBucketTaggingOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketTagging API operation for Amazon Simple Storage Service. -// -// Deletes the tags from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTagging -func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucketTaggingOutput, error) { - req, out := c.DeleteBucketTaggingRequest(input) - return out, req.Send() -} - -// DeleteBucketTaggingWithContext is the same as DeleteBucketTagging with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketTaggingWithContext(ctx aws.Context, input *DeleteBucketTaggingInput, opts ...request.Option) (*DeleteBucketTaggingOutput, error) { - req, out := c.DeleteBucketTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteBucketWebsite = "DeleteBucketWebsite" - -// DeleteBucketWebsiteRequest generates a "aws/request.Request" representing the -// client's request for the DeleteBucketWebsite operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteBucketWebsite for more information on using the DeleteBucketWebsite -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteBucketWebsiteRequest method. -// req, resp := client.DeleteBucketWebsiteRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite -func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *request.Request, output *DeleteBucketWebsiteOutput) { - op := &request.Operation{ - Name: opDeleteBucketWebsite, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?website", - } - - if input == nil { - input = &DeleteBucketWebsiteInput{} - } - - output = &DeleteBucketWebsiteOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// DeleteBucketWebsite API operation for Amazon Simple Storage Service. -// -// This operation removes the website configuration from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsite -func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucketWebsiteOutput, error) { - req, out := c.DeleteBucketWebsiteRequest(input) - return out, req.Send() -} - -// DeleteBucketWebsiteWithContext is the same as DeleteBucketWebsite with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteBucketWebsite for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteBucketWebsiteWithContext(ctx aws.Context, input *DeleteBucketWebsiteInput, opts ...request.Option) (*DeleteBucketWebsiteOutput, error) { - req, out := c.DeleteBucketWebsiteRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteObject = "DeleteObject" - -// DeleteObjectRequest generates a "aws/request.Request" representing the -// client's request for the DeleteObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteObject for more information on using the DeleteObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteObjectRequest method. -// req, resp := client.DeleteObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject -func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *request.Request, output *DeleteObjectOutput) { - op := &request.Operation{ - Name: opDeleteObject, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &DeleteObjectInput{} - } - - output = &DeleteObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteObject API operation for Amazon Simple Storage Service. -// -// Removes the null version (if there is one) of an object and inserts a delete -// marker, which becomes the latest version of the object. If there isn't a -// null version, Amazon S3 does not remove any objects. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObject -func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) { - req, out := c.DeleteObjectRequest(input) - return out, req.Send() -} - -// DeleteObjectWithContext is the same as DeleteObject with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteObjectWithContext(ctx aws.Context, input *DeleteObjectInput, opts ...request.Option) (*DeleteObjectOutput, error) { - req, out := c.DeleteObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteObjectTagging = "DeleteObjectTagging" - -// DeleteObjectTaggingRequest generates a "aws/request.Request" representing the -// client's request for the DeleteObjectTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteObjectTagging for more information on using the DeleteObjectTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteObjectTaggingRequest method. -// req, resp := client.DeleteObjectTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging -func (c *S3) DeleteObjectTaggingRequest(input *DeleteObjectTaggingInput) (req *request.Request, output *DeleteObjectTaggingOutput) { - op := &request.Operation{ - Name: opDeleteObjectTagging, - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}?tagging", - } - - if input == nil { - input = &DeleteObjectTaggingInput{} - } - - output = &DeleteObjectTaggingOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteObjectTagging API operation for Amazon Simple Storage Service. -// -// Removes the tag-set from an existing object. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTagging -func (c *S3) DeleteObjectTagging(input *DeleteObjectTaggingInput) (*DeleteObjectTaggingOutput, error) { - req, out := c.DeleteObjectTaggingRequest(input) - return out, req.Send() -} - -// DeleteObjectTaggingWithContext is the same as DeleteObjectTagging with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteObjectTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteObjectTaggingWithContext(ctx aws.Context, input *DeleteObjectTaggingInput, opts ...request.Option) (*DeleteObjectTaggingOutput, error) { - req, out := c.DeleteObjectTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteObjects = "DeleteObjects" - -// DeleteObjectsRequest generates a "aws/request.Request" representing the -// client's request for the DeleteObjects operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteObjects for more information on using the DeleteObjects -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteObjectsRequest method. -// req, resp := client.DeleteObjectsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects -func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *request.Request, output *DeleteObjectsOutput) { - op := &request.Operation{ - Name: opDeleteObjects, - HTTPMethod: "POST", - HTTPPath: "/{Bucket}?delete", - } - - if input == nil { - input = &DeleteObjectsInput{} - } - - output = &DeleteObjectsOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteObjects API operation for Amazon Simple Storage Service. -// -// This operation enables you to delete multiple objects from a bucket using -// a single HTTP request. You may specify up to 1000 keys. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation DeleteObjects for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjects -func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, error) { - req, out := c.DeleteObjectsRequest(input) - return out, req.Send() -} - -// DeleteObjectsWithContext is the same as DeleteObjects with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteObjects for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) DeleteObjectsWithContext(ctx aws.Context, input *DeleteObjectsInput, opts ...request.Option) (*DeleteObjectsOutput, error) { - req, out := c.DeleteObjectsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketAccelerateConfiguration = "GetBucketAccelerateConfiguration" - -// GetBucketAccelerateConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketAccelerateConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketAccelerateConfiguration for more information on using the GetBucketAccelerateConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketAccelerateConfigurationRequest method. -// req, resp := client.GetBucketAccelerateConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration -func (c *S3) GetBucketAccelerateConfigurationRequest(input *GetBucketAccelerateConfigurationInput) (req *request.Request, output *GetBucketAccelerateConfigurationOutput) { - op := &request.Operation{ - Name: opGetBucketAccelerateConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?accelerate", - } - - if input == nil { - input = &GetBucketAccelerateConfigurationInput{} - } - - output = &GetBucketAccelerateConfigurationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketAccelerateConfiguration API operation for Amazon Simple Storage Service. -// -// Returns the accelerate configuration of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketAccelerateConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfiguration -func (c *S3) GetBucketAccelerateConfiguration(input *GetBucketAccelerateConfigurationInput) (*GetBucketAccelerateConfigurationOutput, error) { - req, out := c.GetBucketAccelerateConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketAccelerateConfigurationWithContext is the same as GetBucketAccelerateConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketAccelerateConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketAccelerateConfigurationWithContext(ctx aws.Context, input *GetBucketAccelerateConfigurationInput, opts ...request.Option) (*GetBucketAccelerateConfigurationOutput, error) { - req, out := c.GetBucketAccelerateConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketAcl = "GetBucketAcl" - -// GetBucketAclRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketAcl operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketAcl for more information on using the GetBucketAcl -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketAclRequest method. -// req, resp := client.GetBucketAclRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl -func (c *S3) GetBucketAclRequest(input *GetBucketAclInput) (req *request.Request, output *GetBucketAclOutput) { - op := &request.Operation{ - Name: opGetBucketAcl, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?acl", - } - - if input == nil { - input = &GetBucketAclInput{} - } - - output = &GetBucketAclOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketAcl API operation for Amazon Simple Storage Service. -// -// Gets the access control policy for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketAcl for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAcl -func (c *S3) GetBucketAcl(input *GetBucketAclInput) (*GetBucketAclOutput, error) { - req, out := c.GetBucketAclRequest(input) - return out, req.Send() -} - -// GetBucketAclWithContext is the same as GetBucketAcl with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketAcl for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketAclWithContext(ctx aws.Context, input *GetBucketAclInput, opts ...request.Option) (*GetBucketAclOutput, error) { - req, out := c.GetBucketAclRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketAnalyticsConfiguration = "GetBucketAnalyticsConfiguration" - -// GetBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketAnalyticsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketAnalyticsConfiguration for more information on using the GetBucketAnalyticsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketAnalyticsConfigurationRequest method. -// req, resp := client.GetBucketAnalyticsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration -func (c *S3) GetBucketAnalyticsConfigurationRequest(input *GetBucketAnalyticsConfigurationInput) (req *request.Request, output *GetBucketAnalyticsConfigurationOutput) { - op := &request.Operation{ - Name: opGetBucketAnalyticsConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?analytics", - } - - if input == nil { - input = &GetBucketAnalyticsConfigurationInput{} - } - - output = &GetBucketAnalyticsConfigurationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketAnalyticsConfiguration API operation for Amazon Simple Storage Service. -// -// Gets an analytics configuration for the bucket (specified by the analytics -// configuration ID). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfiguration -func (c *S3) GetBucketAnalyticsConfiguration(input *GetBucketAnalyticsConfigurationInput) (*GetBucketAnalyticsConfigurationOutput, error) { - req, out := c.GetBucketAnalyticsConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketAnalyticsConfigurationWithContext is the same as GetBucketAnalyticsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketAnalyticsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *GetBucketAnalyticsConfigurationInput, opts ...request.Option) (*GetBucketAnalyticsConfigurationOutput, error) { - req, out := c.GetBucketAnalyticsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketCors = "GetBucketCors" - -// GetBucketCorsRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketCors operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketCors for more information on using the GetBucketCors -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketCorsRequest method. -// req, resp := client.GetBucketCorsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors -func (c *S3) GetBucketCorsRequest(input *GetBucketCorsInput) (req *request.Request, output *GetBucketCorsOutput) { - op := &request.Operation{ - Name: opGetBucketCors, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?cors", - } - - if input == nil { - input = &GetBucketCorsInput{} - } - - output = &GetBucketCorsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketCors API operation for Amazon Simple Storage Service. -// -// Returns the cors configuration for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCors -func (c *S3) GetBucketCors(input *GetBucketCorsInput) (*GetBucketCorsOutput, error) { - req, out := c.GetBucketCorsRequest(input) - return out, req.Send() -} - -// GetBucketCorsWithContext is the same as GetBucketCors with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketCors for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketCorsWithContext(ctx aws.Context, input *GetBucketCorsInput, opts ...request.Option) (*GetBucketCorsOutput, error) { - req, out := c.GetBucketCorsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketEncryption = "GetBucketEncryption" - -// GetBucketEncryptionRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketEncryption operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketEncryption for more information on using the GetBucketEncryption -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketEncryptionRequest method. -// req, resp := client.GetBucketEncryptionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryption -func (c *S3) GetBucketEncryptionRequest(input *GetBucketEncryptionInput) (req *request.Request, output *GetBucketEncryptionOutput) { - op := &request.Operation{ - Name: opGetBucketEncryption, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?encryption", - } - - if input == nil { - input = &GetBucketEncryptionInput{} - } - - output = &GetBucketEncryptionOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketEncryption API operation for Amazon Simple Storage Service. -// -// Returns the server-side encryption configuration of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketEncryption for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryption -func (c *S3) GetBucketEncryption(input *GetBucketEncryptionInput) (*GetBucketEncryptionOutput, error) { - req, out := c.GetBucketEncryptionRequest(input) - return out, req.Send() -} - -// GetBucketEncryptionWithContext is the same as GetBucketEncryption with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketEncryption for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketEncryptionWithContext(ctx aws.Context, input *GetBucketEncryptionInput, opts ...request.Option) (*GetBucketEncryptionOutput, error) { - req, out := c.GetBucketEncryptionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketInventoryConfiguration = "GetBucketInventoryConfiguration" - -// GetBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketInventoryConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketInventoryConfiguration for more information on using the GetBucketInventoryConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketInventoryConfigurationRequest method. -// req, resp := client.GetBucketInventoryConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration -func (c *S3) GetBucketInventoryConfigurationRequest(input *GetBucketInventoryConfigurationInput) (req *request.Request, output *GetBucketInventoryConfigurationOutput) { - op := &request.Operation{ - Name: opGetBucketInventoryConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?inventory", - } - - if input == nil { - input = &GetBucketInventoryConfigurationInput{} - } - - output = &GetBucketInventoryConfigurationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketInventoryConfiguration API operation for Amazon Simple Storage Service. -// -// Returns an inventory configuration (identified by the inventory ID) from -// the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfiguration -func (c *S3) GetBucketInventoryConfiguration(input *GetBucketInventoryConfigurationInput) (*GetBucketInventoryConfigurationOutput, error) { - req, out := c.GetBucketInventoryConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketInventoryConfigurationWithContext is the same as GetBucketInventoryConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketInventoryConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketInventoryConfigurationWithContext(ctx aws.Context, input *GetBucketInventoryConfigurationInput, opts ...request.Option) (*GetBucketInventoryConfigurationOutput, error) { - req, out := c.GetBucketInventoryConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketLifecycle = "GetBucketLifecycle" - -// GetBucketLifecycleRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketLifecycle operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketLifecycle for more information on using the GetBucketLifecycle -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketLifecycleRequest method. -// req, resp := client.GetBucketLifecycleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle -func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *request.Request, output *GetBucketLifecycleOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, GetBucketLifecycle, has been deprecated") - } - op := &request.Operation{ - Name: opGetBucketLifecycle, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?lifecycle", - } - - if input == nil { - input = &GetBucketLifecycleInput{} - } - - output = &GetBucketLifecycleOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketLifecycle API operation for Amazon Simple Storage Service. -// -// Deprecated, see the GetBucketLifecycleConfiguration operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycle -func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifecycleOutput, error) { - req, out := c.GetBucketLifecycleRequest(input) - return out, req.Send() -} - -// GetBucketLifecycleWithContext is the same as GetBucketLifecycle with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketLifecycle for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketLifecycleWithContext(ctx aws.Context, input *GetBucketLifecycleInput, opts ...request.Option) (*GetBucketLifecycleOutput, error) { - req, out := c.GetBucketLifecycleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketLifecycleConfiguration = "GetBucketLifecycleConfiguration" - -// GetBucketLifecycleConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketLifecycleConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketLifecycleConfiguration for more information on using the GetBucketLifecycleConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketLifecycleConfigurationRequest method. -// req, resp := client.GetBucketLifecycleConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration -func (c *S3) GetBucketLifecycleConfigurationRequest(input *GetBucketLifecycleConfigurationInput) (req *request.Request, output *GetBucketLifecycleConfigurationOutput) { - op := &request.Operation{ - Name: opGetBucketLifecycleConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?lifecycle", - } - - if input == nil { - input = &GetBucketLifecycleConfigurationInput{} - } - - output = &GetBucketLifecycleConfigurationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketLifecycleConfiguration API operation for Amazon Simple Storage Service. -// -// Returns the lifecycle configuration information set on the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketLifecycleConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfiguration -func (c *S3) GetBucketLifecycleConfiguration(input *GetBucketLifecycleConfigurationInput) (*GetBucketLifecycleConfigurationOutput, error) { - req, out := c.GetBucketLifecycleConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketLifecycleConfigurationWithContext is the same as GetBucketLifecycleConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketLifecycleConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketLifecycleConfigurationWithContext(ctx aws.Context, input *GetBucketLifecycleConfigurationInput, opts ...request.Option) (*GetBucketLifecycleConfigurationOutput, error) { - req, out := c.GetBucketLifecycleConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketLocation = "GetBucketLocation" - -// GetBucketLocationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketLocation operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketLocation for more information on using the GetBucketLocation -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketLocationRequest method. -// req, resp := client.GetBucketLocationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation -func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *request.Request, output *GetBucketLocationOutput) { - op := &request.Operation{ - Name: opGetBucketLocation, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?location", - } - - if input == nil { - input = &GetBucketLocationInput{} - } - - output = &GetBucketLocationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketLocation API operation for Amazon Simple Storage Service. -// -// Returns the region the bucket resides in. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketLocation for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocation -func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocationOutput, error) { - req, out := c.GetBucketLocationRequest(input) - return out, req.Send() -} - -// GetBucketLocationWithContext is the same as GetBucketLocation with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketLocation for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketLocationWithContext(ctx aws.Context, input *GetBucketLocationInput, opts ...request.Option) (*GetBucketLocationOutput, error) { - req, out := c.GetBucketLocationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketLogging = "GetBucketLogging" - -// GetBucketLoggingRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketLogging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketLogging for more information on using the GetBucketLogging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketLoggingRequest method. -// req, resp := client.GetBucketLoggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging -func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *request.Request, output *GetBucketLoggingOutput) { - op := &request.Operation{ - Name: opGetBucketLogging, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?logging", - } - - if input == nil { - input = &GetBucketLoggingInput{} - } - - output = &GetBucketLoggingOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketLogging API operation for Amazon Simple Storage Service. -// -// Returns the logging status of a bucket and the permissions users have to -// view and modify that status. To use GET, you must be the bucket owner. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketLogging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLogging -func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOutput, error) { - req, out := c.GetBucketLoggingRequest(input) - return out, req.Send() -} - -// GetBucketLoggingWithContext is the same as GetBucketLogging with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketLogging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketLoggingWithContext(ctx aws.Context, input *GetBucketLoggingInput, opts ...request.Option) (*GetBucketLoggingOutput, error) { - req, out := c.GetBucketLoggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketMetricsConfiguration = "GetBucketMetricsConfiguration" - -// GetBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketMetricsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketMetricsConfiguration for more information on using the GetBucketMetricsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketMetricsConfigurationRequest method. -// req, resp := client.GetBucketMetricsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration -func (c *S3) GetBucketMetricsConfigurationRequest(input *GetBucketMetricsConfigurationInput) (req *request.Request, output *GetBucketMetricsConfigurationOutput) { - op := &request.Operation{ - Name: opGetBucketMetricsConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?metrics", - } - - if input == nil { - input = &GetBucketMetricsConfigurationInput{} - } - - output = &GetBucketMetricsConfigurationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketMetricsConfiguration API operation for Amazon Simple Storage Service. -// -// Gets a metrics configuration (specified by the metrics configuration ID) -// from the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfiguration -func (c *S3) GetBucketMetricsConfiguration(input *GetBucketMetricsConfigurationInput) (*GetBucketMetricsConfigurationOutput, error) { - req, out := c.GetBucketMetricsConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketMetricsConfigurationWithContext is the same as GetBucketMetricsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketMetricsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketMetricsConfigurationWithContext(ctx aws.Context, input *GetBucketMetricsConfigurationInput, opts ...request.Option) (*GetBucketMetricsConfigurationOutput, error) { - req, out := c.GetBucketMetricsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketNotification = "GetBucketNotification" - -// GetBucketNotificationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketNotification operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketNotification for more information on using the GetBucketNotification -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketNotificationRequest method. -// req, resp := client.GetBucketNotificationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification -func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfigurationDeprecated) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, GetBucketNotification, has been deprecated") - } - op := &request.Operation{ - Name: opGetBucketNotification, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?notification", - } - - if input == nil { - input = &GetBucketNotificationConfigurationRequest{} - } - - output = &NotificationConfigurationDeprecated{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketNotification API operation for Amazon Simple Storage Service. -// -// Deprecated, see the GetBucketNotificationConfiguration operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketNotification for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotification -func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequest) (*NotificationConfigurationDeprecated, error) { - req, out := c.GetBucketNotificationRequest(input) - return out, req.Send() -} - -// GetBucketNotificationWithContext is the same as GetBucketNotification with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketNotification for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketNotificationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfigurationDeprecated, error) { - req, out := c.GetBucketNotificationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration" - -// GetBucketNotificationConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketNotificationConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketNotificationConfiguration for more information on using the GetBucketNotificationConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketNotificationConfigurationRequest method. -// req, resp := client.GetBucketNotificationConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration -func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *request.Request, output *NotificationConfiguration) { - op := &request.Operation{ - Name: opGetBucketNotificationConfiguration, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?notification", - } - - if input == nil { - input = &GetBucketNotificationConfigurationRequest{} - } - - output = &NotificationConfiguration{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketNotificationConfiguration API operation for Amazon Simple Storage Service. -// -// Returns the notification configuration of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketNotificationConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfiguration -func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConfigurationRequest) (*NotificationConfiguration, error) { - req, out := c.GetBucketNotificationConfigurationRequest(input) - return out, req.Send() -} - -// GetBucketNotificationConfigurationWithContext is the same as GetBucketNotificationConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketNotificationConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketNotificationConfigurationWithContext(ctx aws.Context, input *GetBucketNotificationConfigurationRequest, opts ...request.Option) (*NotificationConfiguration, error) { - req, out := c.GetBucketNotificationConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketPolicy = "GetBucketPolicy" - -// GetBucketPolicyRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketPolicy for more information on using the GetBucketPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketPolicyRequest method. -// req, resp := client.GetBucketPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy -func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *request.Request, output *GetBucketPolicyOutput) { - op := &request.Operation{ - Name: opGetBucketPolicy, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?policy", - } - - if input == nil { - input = &GetBucketPolicyInput{} - } - - output = &GetBucketPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketPolicy API operation for Amazon Simple Storage Service. -// -// Returns the policy of a specified bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy -func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutput, error) { - req, out := c.GetBucketPolicyRequest(input) - return out, req.Send() -} - -// GetBucketPolicyWithContext is the same as GetBucketPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketPolicyWithContext(ctx aws.Context, input *GetBucketPolicyInput, opts ...request.Option) (*GetBucketPolicyOutput, error) { - req, out := c.GetBucketPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketReplication = "GetBucketReplication" - -// GetBucketReplicationRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketReplication operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketReplication for more information on using the GetBucketReplication -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketReplicationRequest method. -// req, resp := client.GetBucketReplicationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication -func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *request.Request, output *GetBucketReplicationOutput) { - op := &request.Operation{ - Name: opGetBucketReplication, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?replication", - } - - if input == nil { - input = &GetBucketReplicationInput{} - } - - output = &GetBucketReplicationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketReplication API operation for Amazon Simple Storage Service. -// -// Returns the replication configuration of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplication -func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketReplicationOutput, error) { - req, out := c.GetBucketReplicationRequest(input) - return out, req.Send() -} - -// GetBucketReplicationWithContext is the same as GetBucketReplication with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketReplication for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketReplicationWithContext(ctx aws.Context, input *GetBucketReplicationInput, opts ...request.Option) (*GetBucketReplicationOutput, error) { - req, out := c.GetBucketReplicationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketRequestPayment = "GetBucketRequestPayment" - -// GetBucketRequestPaymentRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketRequestPayment operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketRequestPayment for more information on using the GetBucketRequestPayment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketRequestPaymentRequest method. -// req, resp := client.GetBucketRequestPaymentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment -func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *request.Request, output *GetBucketRequestPaymentOutput) { - op := &request.Operation{ - Name: opGetBucketRequestPayment, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?requestPayment", - } - - if input == nil { - input = &GetBucketRequestPaymentInput{} - } - - output = &GetBucketRequestPaymentOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketRequestPayment API operation for Amazon Simple Storage Service. -// -// Returns the request payment configuration of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketRequestPayment for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPayment -func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetBucketRequestPaymentOutput, error) { - req, out := c.GetBucketRequestPaymentRequest(input) - return out, req.Send() -} - -// GetBucketRequestPaymentWithContext is the same as GetBucketRequestPayment with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketRequestPayment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketRequestPaymentWithContext(ctx aws.Context, input *GetBucketRequestPaymentInput, opts ...request.Option) (*GetBucketRequestPaymentOutput, error) { - req, out := c.GetBucketRequestPaymentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketTagging = "GetBucketTagging" - -// GetBucketTaggingRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketTagging for more information on using the GetBucketTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketTaggingRequest method. -// req, resp := client.GetBucketTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging -func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *request.Request, output *GetBucketTaggingOutput) { - op := &request.Operation{ - Name: opGetBucketTagging, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?tagging", - } - - if input == nil { - input = &GetBucketTaggingInput{} - } - - output = &GetBucketTaggingOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketTagging API operation for Amazon Simple Storage Service. -// -// Returns the tag set associated with the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTagging -func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOutput, error) { - req, out := c.GetBucketTaggingRequest(input) - return out, req.Send() -} - -// GetBucketTaggingWithContext is the same as GetBucketTagging with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketTaggingWithContext(ctx aws.Context, input *GetBucketTaggingInput, opts ...request.Option) (*GetBucketTaggingOutput, error) { - req, out := c.GetBucketTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketVersioning = "GetBucketVersioning" - -// GetBucketVersioningRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketVersioning operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketVersioning for more information on using the GetBucketVersioning -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketVersioningRequest method. -// req, resp := client.GetBucketVersioningRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning -func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *request.Request, output *GetBucketVersioningOutput) { - op := &request.Operation{ - Name: opGetBucketVersioning, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versioning", - } - - if input == nil { - input = &GetBucketVersioningInput{} - } - - output = &GetBucketVersioningOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketVersioning API operation for Amazon Simple Storage Service. -// -// Returns the versioning state of a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketVersioning for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioning -func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVersioningOutput, error) { - req, out := c.GetBucketVersioningRequest(input) - return out, req.Send() -} - -// GetBucketVersioningWithContext is the same as GetBucketVersioning with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketVersioning for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketVersioningWithContext(ctx aws.Context, input *GetBucketVersioningInput, opts ...request.Option) (*GetBucketVersioningOutput, error) { - req, out := c.GetBucketVersioningRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBucketWebsite = "GetBucketWebsite" - -// GetBucketWebsiteRequest generates a "aws/request.Request" representing the -// client's request for the GetBucketWebsite operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBucketWebsite for more information on using the GetBucketWebsite -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBucketWebsiteRequest method. -// req, resp := client.GetBucketWebsiteRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite -func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *request.Request, output *GetBucketWebsiteOutput) { - op := &request.Operation{ - Name: opGetBucketWebsite, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?website", - } - - if input == nil { - input = &GetBucketWebsiteInput{} - } - - output = &GetBucketWebsiteOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBucketWebsite API operation for Amazon Simple Storage Service. -// -// Returns the website configuration for a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsite -func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOutput, error) { - req, out := c.GetBucketWebsiteRequest(input) - return out, req.Send() -} - -// GetBucketWebsiteWithContext is the same as GetBucketWebsite with the addition of -// the ability to pass a context and additional request options. -// -// See GetBucketWebsite for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetBucketWebsiteWithContext(ctx aws.Context, input *GetBucketWebsiteInput, opts ...request.Option) (*GetBucketWebsiteOutput, error) { - req, out := c.GetBucketWebsiteRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetObject = "GetObject" - -// GetObjectRequest generates a "aws/request.Request" representing the -// client's request for the GetObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetObject for more information on using the GetObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetObjectRequest method. -// req, resp := client.GetObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject -func (c *S3) GetObjectRequest(input *GetObjectInput) (req *request.Request, output *GetObjectOutput) { - op := &request.Operation{ - Name: opGetObject, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &GetObjectInput{} - } - - output = &GetObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetObject API operation for Amazon Simple Storage Service. -// -// Retrieves objects from Amazon S3. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetObject for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchKey "NoSuchKey" -// The specified key does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject -func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { - req, out := c.GetObjectRequest(input) - return out, req.Send() -} - -// GetObjectWithContext is the same as GetObject with the addition of -// the ability to pass a context and additional request options. -// -// See GetObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetObjectWithContext(ctx aws.Context, input *GetObjectInput, opts ...request.Option) (*GetObjectOutput, error) { - req, out := c.GetObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetObjectAcl = "GetObjectAcl" - -// GetObjectAclRequest generates a "aws/request.Request" representing the -// client's request for the GetObjectAcl operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetObjectAcl for more information on using the GetObjectAcl -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetObjectAclRequest method. -// req, resp := client.GetObjectAclRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl -func (c *S3) GetObjectAclRequest(input *GetObjectAclInput) (req *request.Request, output *GetObjectAclOutput) { - op := &request.Operation{ - Name: opGetObjectAcl, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?acl", - } - - if input == nil { - input = &GetObjectAclInput{} - } - - output = &GetObjectAclOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetObjectAcl API operation for Amazon Simple Storage Service. -// -// Returns the access control list (ACL) of an object. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetObjectAcl for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchKey "NoSuchKey" -// The specified key does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAcl -func (c *S3) GetObjectAcl(input *GetObjectAclInput) (*GetObjectAclOutput, error) { - req, out := c.GetObjectAclRequest(input) - return out, req.Send() -} - -// GetObjectAclWithContext is the same as GetObjectAcl with the addition of -// the ability to pass a context and additional request options. -// -// See GetObjectAcl for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetObjectAclWithContext(ctx aws.Context, input *GetObjectAclInput, opts ...request.Option) (*GetObjectAclOutput, error) { - req, out := c.GetObjectAclRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetObjectTagging = "GetObjectTagging" - -// GetObjectTaggingRequest generates a "aws/request.Request" representing the -// client's request for the GetObjectTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetObjectTagging for more information on using the GetObjectTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetObjectTaggingRequest method. -// req, resp := client.GetObjectTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging -func (c *S3) GetObjectTaggingRequest(input *GetObjectTaggingInput) (req *request.Request, output *GetObjectTaggingOutput) { - op := &request.Operation{ - Name: opGetObjectTagging, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?tagging", - } - - if input == nil { - input = &GetObjectTaggingInput{} - } - - output = &GetObjectTaggingOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetObjectTagging API operation for Amazon Simple Storage Service. -// -// Returns the tag-set of an object. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTagging -func (c *S3) GetObjectTagging(input *GetObjectTaggingInput) (*GetObjectTaggingOutput, error) { - req, out := c.GetObjectTaggingRequest(input) - return out, req.Send() -} - -// GetObjectTaggingWithContext is the same as GetObjectTagging with the addition of -// the ability to pass a context and additional request options. -// -// See GetObjectTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetObjectTaggingWithContext(ctx aws.Context, input *GetObjectTaggingInput, opts ...request.Option) (*GetObjectTaggingOutput, error) { - req, out := c.GetObjectTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetObjectTorrent = "GetObjectTorrent" - -// GetObjectTorrentRequest generates a "aws/request.Request" representing the -// client's request for the GetObjectTorrent operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetObjectTorrent for more information on using the GetObjectTorrent -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetObjectTorrentRequest method. -// req, resp := client.GetObjectTorrentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent -func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *request.Request, output *GetObjectTorrentOutput) { - op := &request.Operation{ - Name: opGetObjectTorrent, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?torrent", - } - - if input == nil { - input = &GetObjectTorrentInput{} - } - - output = &GetObjectTorrentOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetObjectTorrent API operation for Amazon Simple Storage Service. -// -// Return torrent files from a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation GetObjectTorrent for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent -func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOutput, error) { - req, out := c.GetObjectTorrentRequest(input) - return out, req.Send() -} - -// GetObjectTorrentWithContext is the same as GetObjectTorrent with the addition of -// the ability to pass a context and additional request options. -// -// See GetObjectTorrent for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) GetObjectTorrentWithContext(ctx aws.Context, input *GetObjectTorrentInput, opts ...request.Option) (*GetObjectTorrentOutput, error) { - req, out := c.GetObjectTorrentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opHeadBucket = "HeadBucket" - -// HeadBucketRequest generates a "aws/request.Request" representing the -// client's request for the HeadBucket operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See HeadBucket for more information on using the HeadBucket -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the HeadBucketRequest method. -// req, resp := client.HeadBucketRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket -func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *request.Request, output *HeadBucketOutput) { - op := &request.Operation{ - Name: opHeadBucket, - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}", - } - - if input == nil { - input = &HeadBucketInput{} - } - - output = &HeadBucketOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// HeadBucket API operation for Amazon Simple Storage Service. -// -// This operation is useful to determine if a bucket exists and you have permission -// to access it. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation HeadBucket for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchBucket "NoSuchBucket" -// The specified bucket does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucket -func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { - req, out := c.HeadBucketRequest(input) - return out, req.Send() -} - -// HeadBucketWithContext is the same as HeadBucket with the addition of -// the ability to pass a context and additional request options. -// -// See HeadBucket for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) HeadBucketWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.Option) (*HeadBucketOutput, error) { - req, out := c.HeadBucketRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opHeadObject = "HeadObject" - -// HeadObjectRequest generates a "aws/request.Request" representing the -// client's request for the HeadObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See HeadObject for more information on using the HeadObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the HeadObjectRequest method. -// req, resp := client.HeadObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject -func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *request.Request, output *HeadObjectOutput) { - op := &request.Operation{ - Name: opHeadObject, - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &HeadObjectInput{} - } - - output = &HeadObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// HeadObject API operation for Amazon Simple Storage Service. -// -// The HEAD operation retrieves metadata from an object without returning the -// object itself. This operation is useful if you're only interested in an object's -// metadata. To use HEAD, you must have READ access to the object. -// -// See http://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#RESTErrorResponses -// for more information on returned errors. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation HeadObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObject -func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { - req, out := c.HeadObjectRequest(input) - return out, req.Send() -} - -// HeadObjectWithContext is the same as HeadObject with the addition of -// the ability to pass a context and additional request options. -// -// See HeadObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) HeadObjectWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.Option) (*HeadObjectOutput, error) { - req, out := c.HeadObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListBucketAnalyticsConfigurations = "ListBucketAnalyticsConfigurations" - -// ListBucketAnalyticsConfigurationsRequest generates a "aws/request.Request" representing the -// client's request for the ListBucketAnalyticsConfigurations operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListBucketAnalyticsConfigurations for more information on using the ListBucketAnalyticsConfigurations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListBucketAnalyticsConfigurationsRequest method. -// req, resp := client.ListBucketAnalyticsConfigurationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations -func (c *S3) ListBucketAnalyticsConfigurationsRequest(input *ListBucketAnalyticsConfigurationsInput) (req *request.Request, output *ListBucketAnalyticsConfigurationsOutput) { - op := &request.Operation{ - Name: opListBucketAnalyticsConfigurations, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?analytics", - } - - if input == nil { - input = &ListBucketAnalyticsConfigurationsInput{} - } - - output = &ListBucketAnalyticsConfigurationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListBucketAnalyticsConfigurations API operation for Amazon Simple Storage Service. -// -// Lists the analytics configurations for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListBucketAnalyticsConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurations -func (c *S3) ListBucketAnalyticsConfigurations(input *ListBucketAnalyticsConfigurationsInput) (*ListBucketAnalyticsConfigurationsOutput, error) { - req, out := c.ListBucketAnalyticsConfigurationsRequest(input) - return out, req.Send() -} - -// ListBucketAnalyticsConfigurationsWithContext is the same as ListBucketAnalyticsConfigurations with the addition of -// the ability to pass a context and additional request options. -// -// See ListBucketAnalyticsConfigurations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListBucketAnalyticsConfigurationsWithContext(ctx aws.Context, input *ListBucketAnalyticsConfigurationsInput, opts ...request.Option) (*ListBucketAnalyticsConfigurationsOutput, error) { - req, out := c.ListBucketAnalyticsConfigurationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListBucketInventoryConfigurations = "ListBucketInventoryConfigurations" - -// ListBucketInventoryConfigurationsRequest generates a "aws/request.Request" representing the -// client's request for the ListBucketInventoryConfigurations operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListBucketInventoryConfigurations for more information on using the ListBucketInventoryConfigurations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListBucketInventoryConfigurationsRequest method. -// req, resp := client.ListBucketInventoryConfigurationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations -func (c *S3) ListBucketInventoryConfigurationsRequest(input *ListBucketInventoryConfigurationsInput) (req *request.Request, output *ListBucketInventoryConfigurationsOutput) { - op := &request.Operation{ - Name: opListBucketInventoryConfigurations, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?inventory", - } - - if input == nil { - input = &ListBucketInventoryConfigurationsInput{} - } - - output = &ListBucketInventoryConfigurationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListBucketInventoryConfigurations API operation for Amazon Simple Storage Service. -// -// Returns a list of inventory configurations for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListBucketInventoryConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurations -func (c *S3) ListBucketInventoryConfigurations(input *ListBucketInventoryConfigurationsInput) (*ListBucketInventoryConfigurationsOutput, error) { - req, out := c.ListBucketInventoryConfigurationsRequest(input) - return out, req.Send() -} - -// ListBucketInventoryConfigurationsWithContext is the same as ListBucketInventoryConfigurations with the addition of -// the ability to pass a context and additional request options. -// -// See ListBucketInventoryConfigurations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListBucketInventoryConfigurationsWithContext(ctx aws.Context, input *ListBucketInventoryConfigurationsInput, opts ...request.Option) (*ListBucketInventoryConfigurationsOutput, error) { - req, out := c.ListBucketInventoryConfigurationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListBucketMetricsConfigurations = "ListBucketMetricsConfigurations" - -// ListBucketMetricsConfigurationsRequest generates a "aws/request.Request" representing the -// client's request for the ListBucketMetricsConfigurations operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListBucketMetricsConfigurations for more information on using the ListBucketMetricsConfigurations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListBucketMetricsConfigurationsRequest method. -// req, resp := client.ListBucketMetricsConfigurationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations -func (c *S3) ListBucketMetricsConfigurationsRequest(input *ListBucketMetricsConfigurationsInput) (req *request.Request, output *ListBucketMetricsConfigurationsOutput) { - op := &request.Operation{ - Name: opListBucketMetricsConfigurations, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?metrics", - } - - if input == nil { - input = &ListBucketMetricsConfigurationsInput{} - } - - output = &ListBucketMetricsConfigurationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListBucketMetricsConfigurations API operation for Amazon Simple Storage Service. -// -// Lists the metrics configurations for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListBucketMetricsConfigurations for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurations -func (c *S3) ListBucketMetricsConfigurations(input *ListBucketMetricsConfigurationsInput) (*ListBucketMetricsConfigurationsOutput, error) { - req, out := c.ListBucketMetricsConfigurationsRequest(input) - return out, req.Send() -} - -// ListBucketMetricsConfigurationsWithContext is the same as ListBucketMetricsConfigurations with the addition of -// the ability to pass a context and additional request options. -// -// See ListBucketMetricsConfigurations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListBucketMetricsConfigurationsWithContext(ctx aws.Context, input *ListBucketMetricsConfigurationsInput, opts ...request.Option) (*ListBucketMetricsConfigurationsOutput, error) { - req, out := c.ListBucketMetricsConfigurationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListBuckets = "ListBuckets" - -// ListBucketsRequest generates a "aws/request.Request" representing the -// client's request for the ListBuckets operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListBuckets for more information on using the ListBuckets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListBucketsRequest method. -// req, resp := client.ListBucketsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets -func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *request.Request, output *ListBucketsOutput) { - op := &request.Operation{ - Name: opListBuckets, - HTTPMethod: "GET", - HTTPPath: "/", - } - - if input == nil { - input = &ListBucketsInput{} - } - - output = &ListBucketsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListBuckets API operation for Amazon Simple Storage Service. -// -// Returns a list of all buckets owned by the authenticated sender of the request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListBuckets for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBuckets -func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { - req, out := c.ListBucketsRequest(input) - return out, req.Send() -} - -// ListBucketsWithContext is the same as ListBuckets with the addition of -// the ability to pass a context and additional request options. -// -// See ListBuckets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListBucketsWithContext(ctx aws.Context, input *ListBucketsInput, opts ...request.Option) (*ListBucketsOutput, error) { - req, out := c.ListBucketsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListMultipartUploads = "ListMultipartUploads" - -// ListMultipartUploadsRequest generates a "aws/request.Request" representing the -// client's request for the ListMultipartUploads operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListMultipartUploads for more information on using the ListMultipartUploads -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListMultipartUploadsRequest method. -// req, resp := client.ListMultipartUploadsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads -func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *request.Request, output *ListMultipartUploadsOutput) { - op := &request.Operation{ - Name: opListMultipartUploads, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?uploads", - Paginator: &request.Paginator{ - InputTokens: []string{"KeyMarker", "UploadIdMarker"}, - OutputTokens: []string{"NextKeyMarker", "NextUploadIdMarker"}, - LimitToken: "MaxUploads", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListMultipartUploadsInput{} - } - - output = &ListMultipartUploadsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListMultipartUploads API operation for Amazon Simple Storage Service. -// -// This operation lists in-progress multipart uploads. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListMultipartUploads for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploads -func (c *S3) ListMultipartUploads(input *ListMultipartUploadsInput) (*ListMultipartUploadsOutput, error) { - req, out := c.ListMultipartUploadsRequest(input) - return out, req.Send() -} - -// ListMultipartUploadsWithContext is the same as ListMultipartUploads with the addition of -// the ability to pass a context and additional request options. -// -// See ListMultipartUploads for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListMultipartUploadsWithContext(ctx aws.Context, input *ListMultipartUploadsInput, opts ...request.Option) (*ListMultipartUploadsOutput, error) { - req, out := c.ListMultipartUploadsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListMultipartUploadsPages iterates over the pages of a ListMultipartUploads operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListMultipartUploads method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListMultipartUploads operation. -// pageNum := 0 -// err := client.ListMultipartUploadsPages(params, -// func(page *ListMultipartUploadsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool) error { - return c.ListMultipartUploadsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListMultipartUploadsPagesWithContext same as ListMultipartUploadsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListMultipartUploadsPagesWithContext(ctx aws.Context, input *ListMultipartUploadsInput, fn func(*ListMultipartUploadsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListMultipartUploadsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListMultipartUploadsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListMultipartUploadsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListObjectVersions = "ListObjectVersions" - -// ListObjectVersionsRequest generates a "aws/request.Request" representing the -// client's request for the ListObjectVersions operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListObjectVersions for more information on using the ListObjectVersions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListObjectVersionsRequest method. -// req, resp := client.ListObjectVersionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions -func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *request.Request, output *ListObjectVersionsOutput) { - op := &request.Operation{ - Name: opListObjectVersions, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versions", - Paginator: &request.Paginator{ - InputTokens: []string{"KeyMarker", "VersionIdMarker"}, - OutputTokens: []string{"NextKeyMarker", "NextVersionIdMarker"}, - LimitToken: "MaxKeys", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListObjectVersionsInput{} - } - - output = &ListObjectVersionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListObjectVersions API operation for Amazon Simple Storage Service. -// -// Returns metadata about all of the versions of objects in a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListObjectVersions for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersions -func (c *S3) ListObjectVersions(input *ListObjectVersionsInput) (*ListObjectVersionsOutput, error) { - req, out := c.ListObjectVersionsRequest(input) - return out, req.Send() -} - -// ListObjectVersionsWithContext is the same as ListObjectVersions with the addition of -// the ability to pass a context and additional request options. -// -// See ListObjectVersions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectVersionsWithContext(ctx aws.Context, input *ListObjectVersionsInput, opts ...request.Option) (*ListObjectVersionsOutput, error) { - req, out := c.ListObjectVersionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListObjectVersionsPages iterates over the pages of a ListObjectVersions operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListObjectVersions method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListObjectVersions operation. -// pageNum := 0 -// err := client.ListObjectVersionsPages(params, -// func(page *ListObjectVersionsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool) error { - return c.ListObjectVersionsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListObjectVersionsPagesWithContext same as ListObjectVersionsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectVersionsPagesWithContext(ctx aws.Context, input *ListObjectVersionsInput, fn func(*ListObjectVersionsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListObjectVersionsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListObjectVersionsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListObjectVersionsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListObjects = "ListObjects" - -// ListObjectsRequest generates a "aws/request.Request" representing the -// client's request for the ListObjects operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListObjects for more information on using the ListObjects -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListObjectsRequest method. -// req, resp := client.ListObjectsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects -func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *request.Request, output *ListObjectsOutput) { - op := &request.Operation{ - Name: opListObjects, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker || Contents[-1].Key"}, - LimitToken: "MaxKeys", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListObjectsInput{} - } - - output = &ListObjectsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListObjects API operation for Amazon Simple Storage Service. -// -// Returns some or all (up to 1000) of the objects in a bucket. You can use -// the request parameters as selection criteria to return a subset of the objects -// in a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListObjects for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchBucket "NoSuchBucket" -// The specified bucket does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjects -func (c *S3) ListObjects(input *ListObjectsInput) (*ListObjectsOutput, error) { - req, out := c.ListObjectsRequest(input) - return out, req.Send() -} - -// ListObjectsWithContext is the same as ListObjects with the addition of -// the ability to pass a context and additional request options. -// -// See ListObjects for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectsWithContext(ctx aws.Context, input *ListObjectsInput, opts ...request.Option) (*ListObjectsOutput, error) { - req, out := c.ListObjectsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListObjectsPages iterates over the pages of a ListObjects operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListObjects method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListObjects operation. -// pageNum := 0 -// err := client.ListObjectsPages(params, -// func(page *ListObjectsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool) error { - return c.ListObjectsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListObjectsPagesWithContext same as ListObjectsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectsPagesWithContext(ctx aws.Context, input *ListObjectsInput, fn func(*ListObjectsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListObjectsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListObjectsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListObjectsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListObjectsV2 = "ListObjectsV2" - -// ListObjectsV2Request generates a "aws/request.Request" representing the -// client's request for the ListObjectsV2 operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListObjectsV2 for more information on using the ListObjectsV2 -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListObjectsV2Request method. -// req, resp := client.ListObjectsV2Request(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 -func (c *S3) ListObjectsV2Request(input *ListObjectsV2Input) (req *request.Request, output *ListObjectsV2Output) { - op := &request.Operation{ - Name: opListObjectsV2, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?list-type=2", - Paginator: &request.Paginator{ - InputTokens: []string{"ContinuationToken"}, - OutputTokens: []string{"NextContinuationToken"}, - LimitToken: "MaxKeys", - TruncationToken: "", - }, - } - - if input == nil { - input = &ListObjectsV2Input{} - } - - output = &ListObjectsV2Output{} - req = c.newRequest(op, input, output) - return -} - -// ListObjectsV2 API operation for Amazon Simple Storage Service. -// -// Returns some or all (up to 1000) of the objects in a bucket. You can use -// the request parameters as selection criteria to return a subset of the objects -// in a bucket. Note: ListObjectsV2 is the revised List Objects API and we recommend -// you use this revised API for new application development. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListObjectsV2 for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchBucket "NoSuchBucket" -// The specified bucket does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2 -func (c *S3) ListObjectsV2(input *ListObjectsV2Input) (*ListObjectsV2Output, error) { - req, out := c.ListObjectsV2Request(input) - return out, req.Send() -} - -// ListObjectsV2WithContext is the same as ListObjectsV2 with the addition of -// the ability to pass a context and additional request options. -// -// See ListObjectsV2 for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectsV2WithContext(ctx aws.Context, input *ListObjectsV2Input, opts ...request.Option) (*ListObjectsV2Output, error) { - req, out := c.ListObjectsV2Request(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListObjectsV2Pages iterates over the pages of a ListObjectsV2 operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListObjectsV2 method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListObjectsV2 operation. -// pageNum := 0 -// err := client.ListObjectsV2Pages(params, -// func(page *ListObjectsV2Output, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *S3) ListObjectsV2Pages(input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool) error { - return c.ListObjectsV2PagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListObjectsV2PagesWithContext same as ListObjectsV2Pages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListObjectsV2PagesWithContext(ctx aws.Context, input *ListObjectsV2Input, fn func(*ListObjectsV2Output, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListObjectsV2Input - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListObjectsV2Request(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListObjectsV2Output), !p.HasNextPage()) - } - return p.Err() -} - -const opListParts = "ListParts" - -// ListPartsRequest generates a "aws/request.Request" representing the -// client's request for the ListParts operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListParts for more information on using the ListParts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListPartsRequest method. -// req, resp := client.ListPartsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts -func (c *S3) ListPartsRequest(input *ListPartsInput) (req *request.Request, output *ListPartsOutput) { - op := &request.Operation{ - Name: opListParts, - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - Paginator: &request.Paginator{ - InputTokens: []string{"PartNumberMarker"}, - OutputTokens: []string{"NextPartNumberMarker"}, - LimitToken: "MaxParts", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListPartsInput{} - } - - output = &ListPartsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListParts API operation for Amazon Simple Storage Service. -// -// Lists the parts that have been uploaded for a specific multipart upload. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation ListParts for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListParts -func (c *S3) ListParts(input *ListPartsInput) (*ListPartsOutput, error) { - req, out := c.ListPartsRequest(input) - return out, req.Send() -} - -// ListPartsWithContext is the same as ListParts with the addition of -// the ability to pass a context and additional request options. -// -// See ListParts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListPartsWithContext(ctx aws.Context, input *ListPartsInput, opts ...request.Option) (*ListPartsOutput, error) { - req, out := c.ListPartsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListPartsPages iterates over the pages of a ListParts operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListParts method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListParts operation. -// pageNum := 0 -// err := client.ListPartsPages(params, -// func(page *ListPartsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *S3) ListPartsPages(input *ListPartsInput, fn func(*ListPartsOutput, bool) bool) error { - return c.ListPartsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListPartsPagesWithContext same as ListPartsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) ListPartsPagesWithContext(ctx aws.Context, input *ListPartsInput, fn func(*ListPartsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListPartsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListPartsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListPartsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opPutBucketAccelerateConfiguration = "PutBucketAccelerateConfiguration" - -// PutBucketAccelerateConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketAccelerateConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketAccelerateConfiguration for more information on using the PutBucketAccelerateConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketAccelerateConfigurationRequest method. -// req, resp := client.PutBucketAccelerateConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration -func (c *S3) PutBucketAccelerateConfigurationRequest(input *PutBucketAccelerateConfigurationInput) (req *request.Request, output *PutBucketAccelerateConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketAccelerateConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?accelerate", - } - - if input == nil { - input = &PutBucketAccelerateConfigurationInput{} - } - - output = &PutBucketAccelerateConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketAccelerateConfiguration API operation for Amazon Simple Storage Service. -// -// Sets the accelerate configuration of an existing bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketAccelerateConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfiguration -func (c *S3) PutBucketAccelerateConfiguration(input *PutBucketAccelerateConfigurationInput) (*PutBucketAccelerateConfigurationOutput, error) { - req, out := c.PutBucketAccelerateConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketAccelerateConfigurationWithContext is the same as PutBucketAccelerateConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketAccelerateConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketAccelerateConfigurationWithContext(ctx aws.Context, input *PutBucketAccelerateConfigurationInput, opts ...request.Option) (*PutBucketAccelerateConfigurationOutput, error) { - req, out := c.PutBucketAccelerateConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketAcl = "PutBucketAcl" - -// PutBucketAclRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketAcl operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketAcl for more information on using the PutBucketAcl -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketAclRequest method. -// req, resp := client.PutBucketAclRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl -func (c *S3) PutBucketAclRequest(input *PutBucketAclInput) (req *request.Request, output *PutBucketAclOutput) { - op := &request.Operation{ - Name: opPutBucketAcl, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?acl", - } - - if input == nil { - input = &PutBucketAclInput{} - } - - output = &PutBucketAclOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketAcl API operation for Amazon Simple Storage Service. -// -// Sets the permissions on a bucket using access control lists (ACL). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketAcl for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAcl -func (c *S3) PutBucketAcl(input *PutBucketAclInput) (*PutBucketAclOutput, error) { - req, out := c.PutBucketAclRequest(input) - return out, req.Send() -} - -// PutBucketAclWithContext is the same as PutBucketAcl with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketAcl for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketAclWithContext(ctx aws.Context, input *PutBucketAclInput, opts ...request.Option) (*PutBucketAclOutput, error) { - req, out := c.PutBucketAclRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketAnalyticsConfiguration = "PutBucketAnalyticsConfiguration" - -// PutBucketAnalyticsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketAnalyticsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketAnalyticsConfiguration for more information on using the PutBucketAnalyticsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketAnalyticsConfigurationRequest method. -// req, resp := client.PutBucketAnalyticsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration -func (c *S3) PutBucketAnalyticsConfigurationRequest(input *PutBucketAnalyticsConfigurationInput) (req *request.Request, output *PutBucketAnalyticsConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketAnalyticsConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?analytics", - } - - if input == nil { - input = &PutBucketAnalyticsConfigurationInput{} - } - - output = &PutBucketAnalyticsConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketAnalyticsConfiguration API operation for Amazon Simple Storage Service. -// -// Sets an analytics configuration for the bucket (specified by the analytics -// configuration ID). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketAnalyticsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfiguration -func (c *S3) PutBucketAnalyticsConfiguration(input *PutBucketAnalyticsConfigurationInput) (*PutBucketAnalyticsConfigurationOutput, error) { - req, out := c.PutBucketAnalyticsConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketAnalyticsConfigurationWithContext is the same as PutBucketAnalyticsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketAnalyticsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketAnalyticsConfigurationWithContext(ctx aws.Context, input *PutBucketAnalyticsConfigurationInput, opts ...request.Option) (*PutBucketAnalyticsConfigurationOutput, error) { - req, out := c.PutBucketAnalyticsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketCors = "PutBucketCors" - -// PutBucketCorsRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketCors operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketCors for more information on using the PutBucketCors -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketCorsRequest method. -// req, resp := client.PutBucketCorsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors -func (c *S3) PutBucketCorsRequest(input *PutBucketCorsInput) (req *request.Request, output *PutBucketCorsOutput) { - op := &request.Operation{ - Name: opPutBucketCors, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?cors", - } - - if input == nil { - input = &PutBucketCorsInput{} - } - - output = &PutBucketCorsOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketCors API operation for Amazon Simple Storage Service. -// -// Sets the cors configuration for a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketCors for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCors -func (c *S3) PutBucketCors(input *PutBucketCorsInput) (*PutBucketCorsOutput, error) { - req, out := c.PutBucketCorsRequest(input) - return out, req.Send() -} - -// PutBucketCorsWithContext is the same as PutBucketCors with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketCors for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketCorsWithContext(ctx aws.Context, input *PutBucketCorsInput, opts ...request.Option) (*PutBucketCorsOutput, error) { - req, out := c.PutBucketCorsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketEncryption = "PutBucketEncryption" - -// PutBucketEncryptionRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketEncryption operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketEncryption for more information on using the PutBucketEncryption -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketEncryptionRequest method. -// req, resp := client.PutBucketEncryptionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryption -func (c *S3) PutBucketEncryptionRequest(input *PutBucketEncryptionInput) (req *request.Request, output *PutBucketEncryptionOutput) { - op := &request.Operation{ - Name: opPutBucketEncryption, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?encryption", - } - - if input == nil { - input = &PutBucketEncryptionInput{} - } - - output = &PutBucketEncryptionOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketEncryption API operation for Amazon Simple Storage Service. -// -// Creates a new server-side encryption configuration (or replaces an existing -// one, if present). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketEncryption for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryption -func (c *S3) PutBucketEncryption(input *PutBucketEncryptionInput) (*PutBucketEncryptionOutput, error) { - req, out := c.PutBucketEncryptionRequest(input) - return out, req.Send() -} - -// PutBucketEncryptionWithContext is the same as PutBucketEncryption with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketEncryption for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketEncryptionWithContext(ctx aws.Context, input *PutBucketEncryptionInput, opts ...request.Option) (*PutBucketEncryptionOutput, error) { - req, out := c.PutBucketEncryptionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketInventoryConfiguration = "PutBucketInventoryConfiguration" - -// PutBucketInventoryConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketInventoryConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketInventoryConfiguration for more information on using the PutBucketInventoryConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketInventoryConfigurationRequest method. -// req, resp := client.PutBucketInventoryConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration -func (c *S3) PutBucketInventoryConfigurationRequest(input *PutBucketInventoryConfigurationInput) (req *request.Request, output *PutBucketInventoryConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketInventoryConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?inventory", - } - - if input == nil { - input = &PutBucketInventoryConfigurationInput{} - } - - output = &PutBucketInventoryConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketInventoryConfiguration API operation for Amazon Simple Storage Service. -// -// Adds an inventory configuration (identified by the inventory ID) from the -// bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketInventoryConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfiguration -func (c *S3) PutBucketInventoryConfiguration(input *PutBucketInventoryConfigurationInput) (*PutBucketInventoryConfigurationOutput, error) { - req, out := c.PutBucketInventoryConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketInventoryConfigurationWithContext is the same as PutBucketInventoryConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketInventoryConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketInventoryConfigurationWithContext(ctx aws.Context, input *PutBucketInventoryConfigurationInput, opts ...request.Option) (*PutBucketInventoryConfigurationOutput, error) { - req, out := c.PutBucketInventoryConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketLifecycle = "PutBucketLifecycle" - -// PutBucketLifecycleRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketLifecycle operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketLifecycle for more information on using the PutBucketLifecycle -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketLifecycleRequest method. -// req, resp := client.PutBucketLifecycleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle -func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *request.Request, output *PutBucketLifecycleOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, PutBucketLifecycle, has been deprecated") - } - op := &request.Operation{ - Name: opPutBucketLifecycle, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?lifecycle", - } - - if input == nil { - input = &PutBucketLifecycleInput{} - } - - output = &PutBucketLifecycleOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketLifecycle API operation for Amazon Simple Storage Service. -// -// Deprecated, see the PutBucketLifecycleConfiguration operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketLifecycle for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycle -func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifecycleOutput, error) { - req, out := c.PutBucketLifecycleRequest(input) - return out, req.Send() -} - -// PutBucketLifecycleWithContext is the same as PutBucketLifecycle with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketLifecycle for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketLifecycleWithContext(ctx aws.Context, input *PutBucketLifecycleInput, opts ...request.Option) (*PutBucketLifecycleOutput, error) { - req, out := c.PutBucketLifecycleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketLifecycleConfiguration = "PutBucketLifecycleConfiguration" - -// PutBucketLifecycleConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketLifecycleConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketLifecycleConfiguration for more information on using the PutBucketLifecycleConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketLifecycleConfigurationRequest method. -// req, resp := client.PutBucketLifecycleConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration -func (c *S3) PutBucketLifecycleConfigurationRequest(input *PutBucketLifecycleConfigurationInput) (req *request.Request, output *PutBucketLifecycleConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketLifecycleConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?lifecycle", - } - - if input == nil { - input = &PutBucketLifecycleConfigurationInput{} - } - - output = &PutBucketLifecycleConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketLifecycleConfiguration API operation for Amazon Simple Storage Service. -// -// Sets lifecycle configuration for your bucket. If a lifecycle configuration -// exists, it replaces it. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketLifecycleConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfiguration -func (c *S3) PutBucketLifecycleConfiguration(input *PutBucketLifecycleConfigurationInput) (*PutBucketLifecycleConfigurationOutput, error) { - req, out := c.PutBucketLifecycleConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketLifecycleConfigurationWithContext is the same as PutBucketLifecycleConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketLifecycleConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketLifecycleConfigurationWithContext(ctx aws.Context, input *PutBucketLifecycleConfigurationInput, opts ...request.Option) (*PutBucketLifecycleConfigurationOutput, error) { - req, out := c.PutBucketLifecycleConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketLogging = "PutBucketLogging" - -// PutBucketLoggingRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketLogging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketLogging for more information on using the PutBucketLogging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketLoggingRequest method. -// req, resp := client.PutBucketLoggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging -func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *request.Request, output *PutBucketLoggingOutput) { - op := &request.Operation{ - Name: opPutBucketLogging, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?logging", - } - - if input == nil { - input = &PutBucketLoggingInput{} - } - - output = &PutBucketLoggingOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketLogging API operation for Amazon Simple Storage Service. -// -// Set the logging parameters for a bucket and to specify permissions for who -// can view and modify the logging parameters. To set the logging status of -// a bucket, you must be the bucket owner. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketLogging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLogging -func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOutput, error) { - req, out := c.PutBucketLoggingRequest(input) - return out, req.Send() -} - -// PutBucketLoggingWithContext is the same as PutBucketLogging with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketLogging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketLoggingWithContext(ctx aws.Context, input *PutBucketLoggingInput, opts ...request.Option) (*PutBucketLoggingOutput, error) { - req, out := c.PutBucketLoggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketMetricsConfiguration = "PutBucketMetricsConfiguration" - -// PutBucketMetricsConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketMetricsConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketMetricsConfiguration for more information on using the PutBucketMetricsConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketMetricsConfigurationRequest method. -// req, resp := client.PutBucketMetricsConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration -func (c *S3) PutBucketMetricsConfigurationRequest(input *PutBucketMetricsConfigurationInput) (req *request.Request, output *PutBucketMetricsConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketMetricsConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?metrics", - } - - if input == nil { - input = &PutBucketMetricsConfigurationInput{} - } - - output = &PutBucketMetricsConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketMetricsConfiguration API operation for Amazon Simple Storage Service. -// -// Sets a metrics configuration (specified by the metrics configuration ID) -// for the bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketMetricsConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfiguration -func (c *S3) PutBucketMetricsConfiguration(input *PutBucketMetricsConfigurationInput) (*PutBucketMetricsConfigurationOutput, error) { - req, out := c.PutBucketMetricsConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketMetricsConfigurationWithContext is the same as PutBucketMetricsConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketMetricsConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketMetricsConfigurationWithContext(ctx aws.Context, input *PutBucketMetricsConfigurationInput, opts ...request.Option) (*PutBucketMetricsConfigurationOutput, error) { - req, out := c.PutBucketMetricsConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketNotification = "PutBucketNotification" - -// PutBucketNotificationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketNotification operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketNotification for more information on using the PutBucketNotification -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketNotificationRequest method. -// req, resp := client.PutBucketNotificationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification -func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *request.Request, output *PutBucketNotificationOutput) { - if c.Client.Config.Logger != nil { - c.Client.Config.Logger.Log("This operation, PutBucketNotification, has been deprecated") - } - op := &request.Operation{ - Name: opPutBucketNotification, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?notification", - } - - if input == nil { - input = &PutBucketNotificationInput{} - } - - output = &PutBucketNotificationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketNotification API operation for Amazon Simple Storage Service. -// -// Deprecated, see the PutBucketNotificationConfiguraiton operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketNotification for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotification -func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucketNotificationOutput, error) { - req, out := c.PutBucketNotificationRequest(input) - return out, req.Send() -} - -// PutBucketNotificationWithContext is the same as PutBucketNotification with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketNotification for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketNotificationWithContext(ctx aws.Context, input *PutBucketNotificationInput, opts ...request.Option) (*PutBucketNotificationOutput, error) { - req, out := c.PutBucketNotificationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration" - -// PutBucketNotificationConfigurationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketNotificationConfiguration operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketNotificationConfiguration for more information on using the PutBucketNotificationConfiguration -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketNotificationConfigurationRequest method. -// req, resp := client.PutBucketNotificationConfigurationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration -func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *request.Request, output *PutBucketNotificationConfigurationOutput) { - op := &request.Operation{ - Name: opPutBucketNotificationConfiguration, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?notification", - } - - if input == nil { - input = &PutBucketNotificationConfigurationInput{} - } - - output = &PutBucketNotificationConfigurationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketNotificationConfiguration API operation for Amazon Simple Storage Service. -// -// Enables notifications of specified events for a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketNotificationConfiguration for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfiguration -func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConfigurationInput) (*PutBucketNotificationConfigurationOutput, error) { - req, out := c.PutBucketNotificationConfigurationRequest(input) - return out, req.Send() -} - -// PutBucketNotificationConfigurationWithContext is the same as PutBucketNotificationConfiguration with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketNotificationConfiguration for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketNotificationConfigurationWithContext(ctx aws.Context, input *PutBucketNotificationConfigurationInput, opts ...request.Option) (*PutBucketNotificationConfigurationOutput, error) { - req, out := c.PutBucketNotificationConfigurationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketPolicy = "PutBucketPolicy" - -// PutBucketPolicyRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketPolicy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketPolicy for more information on using the PutBucketPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketPolicyRequest method. -// req, resp := client.PutBucketPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy -func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *request.Request, output *PutBucketPolicyOutput) { - op := &request.Operation{ - Name: opPutBucketPolicy, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?policy", - } - - if input == nil { - input = &PutBucketPolicyInput{} - } - - output = &PutBucketPolicyOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketPolicy API operation for Amazon Simple Storage Service. -// -// Replaces a policy on a bucket. If the bucket already has a policy, the one -// in this request completely replaces it. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketPolicy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicy -func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutput, error) { - req, out := c.PutBucketPolicyRequest(input) - return out, req.Send() -} - -// PutBucketPolicyWithContext is the same as PutBucketPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketPolicyWithContext(ctx aws.Context, input *PutBucketPolicyInput, opts ...request.Option) (*PutBucketPolicyOutput, error) { - req, out := c.PutBucketPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketReplication = "PutBucketReplication" - -// PutBucketReplicationRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketReplication operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketReplication for more information on using the PutBucketReplication -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketReplicationRequest method. -// req, resp := client.PutBucketReplicationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication -func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *request.Request, output *PutBucketReplicationOutput) { - op := &request.Operation{ - Name: opPutBucketReplication, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?replication", - } - - if input == nil { - input = &PutBucketReplicationInput{} - } - - output = &PutBucketReplicationOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketReplication API operation for Amazon Simple Storage Service. -// -// Creates a new replication configuration (or replaces an existing one, if -// present). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketReplication for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplication -func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketReplicationOutput, error) { - req, out := c.PutBucketReplicationRequest(input) - return out, req.Send() -} - -// PutBucketReplicationWithContext is the same as PutBucketReplication with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketReplication for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketReplicationWithContext(ctx aws.Context, input *PutBucketReplicationInput, opts ...request.Option) (*PutBucketReplicationOutput, error) { - req, out := c.PutBucketReplicationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketRequestPayment = "PutBucketRequestPayment" - -// PutBucketRequestPaymentRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketRequestPayment operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketRequestPayment for more information on using the PutBucketRequestPayment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketRequestPaymentRequest method. -// req, resp := client.PutBucketRequestPaymentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment -func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *request.Request, output *PutBucketRequestPaymentOutput) { - op := &request.Operation{ - Name: opPutBucketRequestPayment, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?requestPayment", - } - - if input == nil { - input = &PutBucketRequestPaymentInput{} - } - - output = &PutBucketRequestPaymentOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketRequestPayment API operation for Amazon Simple Storage Service. -// -// Sets the request payment configuration for a bucket. By default, the bucket -// owner pays for downloads from the bucket. This configuration parameter enables -// the bucket owner (only) to specify that the person requesting the download -// will be charged for the download. Documentation on requester pays buckets -// can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/RequesterPaysBuckets.html -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketRequestPayment for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPayment -func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutBucketRequestPaymentOutput, error) { - req, out := c.PutBucketRequestPaymentRequest(input) - return out, req.Send() -} - -// PutBucketRequestPaymentWithContext is the same as PutBucketRequestPayment with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketRequestPayment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketRequestPaymentWithContext(ctx aws.Context, input *PutBucketRequestPaymentInput, opts ...request.Option) (*PutBucketRequestPaymentOutput, error) { - req, out := c.PutBucketRequestPaymentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketTagging = "PutBucketTagging" - -// PutBucketTaggingRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketTagging for more information on using the PutBucketTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketTaggingRequest method. -// req, resp := client.PutBucketTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging -func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *request.Request, output *PutBucketTaggingOutput) { - op := &request.Operation{ - Name: opPutBucketTagging, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?tagging", - } - - if input == nil { - input = &PutBucketTaggingInput{} - } - - output = &PutBucketTaggingOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketTagging API operation for Amazon Simple Storage Service. -// -// Sets the tags for a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTagging -func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOutput, error) { - req, out := c.PutBucketTaggingRequest(input) - return out, req.Send() -} - -// PutBucketTaggingWithContext is the same as PutBucketTagging with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketTaggingWithContext(ctx aws.Context, input *PutBucketTaggingInput, opts ...request.Option) (*PutBucketTaggingOutput, error) { - req, out := c.PutBucketTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketVersioning = "PutBucketVersioning" - -// PutBucketVersioningRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketVersioning operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketVersioning for more information on using the PutBucketVersioning -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketVersioningRequest method. -// req, resp := client.PutBucketVersioningRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning -func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *request.Request, output *PutBucketVersioningOutput) { - op := &request.Operation{ - Name: opPutBucketVersioning, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?versioning", - } - - if input == nil { - input = &PutBucketVersioningInput{} - } - - output = &PutBucketVersioningOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketVersioning API operation for Amazon Simple Storage Service. -// -// Sets the versioning state of an existing bucket. To set the versioning state, -// you must be the bucket owner. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketVersioning for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioning -func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVersioningOutput, error) { - req, out := c.PutBucketVersioningRequest(input) - return out, req.Send() -} - -// PutBucketVersioningWithContext is the same as PutBucketVersioning with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketVersioning for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketVersioningWithContext(ctx aws.Context, input *PutBucketVersioningInput, opts ...request.Option) (*PutBucketVersioningOutput, error) { - req, out := c.PutBucketVersioningRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutBucketWebsite = "PutBucketWebsite" - -// PutBucketWebsiteRequest generates a "aws/request.Request" representing the -// client's request for the PutBucketWebsite operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutBucketWebsite for more information on using the PutBucketWebsite -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutBucketWebsiteRequest method. -// req, resp := client.PutBucketWebsiteRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite -func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *request.Request, output *PutBucketWebsiteOutput) { - op := &request.Operation{ - Name: opPutBucketWebsite, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?website", - } - - if input == nil { - input = &PutBucketWebsiteInput{} - } - - output = &PutBucketWebsiteOutput{} - req = c.newRequest(op, input, output) - req.Handlers.Unmarshal.Remove(restxml.UnmarshalHandler) - req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler) - return -} - -// PutBucketWebsite API operation for Amazon Simple Storage Service. -// -// Set the website configuration for a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutBucketWebsite for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsite -func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOutput, error) { - req, out := c.PutBucketWebsiteRequest(input) - return out, req.Send() -} - -// PutBucketWebsiteWithContext is the same as PutBucketWebsite with the addition of -// the ability to pass a context and additional request options. -// -// See PutBucketWebsite for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutBucketWebsiteWithContext(ctx aws.Context, input *PutBucketWebsiteInput, opts ...request.Option) (*PutBucketWebsiteOutput, error) { - req, out := c.PutBucketWebsiteRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutObject = "PutObject" - -// PutObjectRequest generates a "aws/request.Request" representing the -// client's request for the PutObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutObject for more information on using the PutObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutObjectRequest method. -// req, resp := client.PutObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject -func (c *S3) PutObjectRequest(input *PutObjectInput) (req *request.Request, output *PutObjectOutput) { - op := &request.Operation{ - Name: opPutObject, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &PutObjectInput{} - } - - output = &PutObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutObject API operation for Amazon Simple Storage Service. -// -// Adds an object to a bucket. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutObject for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObject -func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { - req, out := c.PutObjectRequest(input) - return out, req.Send() -} - -// PutObjectWithContext is the same as PutObject with the addition of -// the ability to pass a context and additional request options. -// -// See PutObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutObjectWithContext(ctx aws.Context, input *PutObjectInput, opts ...request.Option) (*PutObjectOutput, error) { - req, out := c.PutObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutObjectAcl = "PutObjectAcl" - -// PutObjectAclRequest generates a "aws/request.Request" representing the -// client's request for the PutObjectAcl operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutObjectAcl for more information on using the PutObjectAcl -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutObjectAclRequest method. -// req, resp := client.PutObjectAclRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl -func (c *S3) PutObjectAclRequest(input *PutObjectAclInput) (req *request.Request, output *PutObjectAclOutput) { - op := &request.Operation{ - Name: opPutObjectAcl, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}?acl", - } - - if input == nil { - input = &PutObjectAclInput{} - } - - output = &PutObjectAclOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutObjectAcl API operation for Amazon Simple Storage Service. -// -// uses the acl subresource to set the access control list (ACL) permissions -// for an object that already exists in a bucket -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutObjectAcl for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchKey "NoSuchKey" -// The specified key does not exist. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAcl -func (c *S3) PutObjectAcl(input *PutObjectAclInput) (*PutObjectAclOutput, error) { - req, out := c.PutObjectAclRequest(input) - return out, req.Send() -} - -// PutObjectAclWithContext is the same as PutObjectAcl with the addition of -// the ability to pass a context and additional request options. -// -// See PutObjectAcl for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutObjectAclWithContext(ctx aws.Context, input *PutObjectAclInput, opts ...request.Option) (*PutObjectAclOutput, error) { - req, out := c.PutObjectAclRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutObjectTagging = "PutObjectTagging" - -// PutObjectTaggingRequest generates a "aws/request.Request" representing the -// client's request for the PutObjectTagging operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutObjectTagging for more information on using the PutObjectTagging -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutObjectTaggingRequest method. -// req, resp := client.PutObjectTaggingRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging -func (c *S3) PutObjectTaggingRequest(input *PutObjectTaggingInput) (req *request.Request, output *PutObjectTaggingOutput) { - op := &request.Operation{ - Name: opPutObjectTagging, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}?tagging", - } - - if input == nil { - input = &PutObjectTaggingInput{} - } - - output = &PutObjectTaggingOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutObjectTagging API operation for Amazon Simple Storage Service. -// -// Sets the supplied tag-set to an object that already exists in a bucket -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation PutObjectTagging for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTagging -func (c *S3) PutObjectTagging(input *PutObjectTaggingInput) (*PutObjectTaggingOutput, error) { - req, out := c.PutObjectTaggingRequest(input) - return out, req.Send() -} - -// PutObjectTaggingWithContext is the same as PutObjectTagging with the addition of -// the ability to pass a context and additional request options. -// -// See PutObjectTagging for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) PutObjectTaggingWithContext(ctx aws.Context, input *PutObjectTaggingInput, opts ...request.Option) (*PutObjectTaggingOutput, error) { - req, out := c.PutObjectTaggingRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opRestoreObject = "RestoreObject" - -// RestoreObjectRequest generates a "aws/request.Request" representing the -// client's request for the RestoreObject operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See RestoreObject for more information on using the RestoreObject -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the RestoreObjectRequest method. -// req, resp := client.RestoreObjectRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject -func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *request.Request, output *RestoreObjectOutput) { - op := &request.Operation{ - Name: opRestoreObject, - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?restore", - } - - if input == nil { - input = &RestoreObjectInput{} - } - - output = &RestoreObjectOutput{} - req = c.newRequest(op, input, output) - return -} - -// RestoreObject API operation for Amazon Simple Storage Service. -// -// Restores an archived copy of an object back into Amazon S3 -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation RestoreObject for usage and error information. -// -// Returned Error Codes: -// * ErrCodeObjectAlreadyInActiveTierError "ObjectAlreadyInActiveTierError" -// This operation is not allowed against this storage tier -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObject -func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, error) { - req, out := c.RestoreObjectRequest(input) - return out, req.Send() -} - -// RestoreObjectWithContext is the same as RestoreObject with the addition of -// the ability to pass a context and additional request options. -// -// See RestoreObject for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) RestoreObjectWithContext(ctx aws.Context, input *RestoreObjectInput, opts ...request.Option) (*RestoreObjectOutput, error) { - req, out := c.RestoreObjectRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUploadPart = "UploadPart" - -// UploadPartRequest generates a "aws/request.Request" representing the -// client's request for the UploadPart operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UploadPart for more information on using the UploadPart -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UploadPartRequest method. -// req, resp := client.UploadPartRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart -func (c *S3) UploadPartRequest(input *UploadPartInput) (req *request.Request, output *UploadPartOutput) { - op := &request.Operation{ - Name: opUploadPart, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &UploadPartInput{} - } - - output = &UploadPartOutput{} - req = c.newRequest(op, input, output) - return -} - -// UploadPart API operation for Amazon Simple Storage Service. -// -// Uploads a part in a multipart upload. -// -// Note: After you initiate multipart upload and upload one or more parts, you -// must either complete or abort multipart upload in order to stop getting charged -// for storage of the uploaded parts. Only after you either complete or abort -// multipart upload, Amazon S3 frees up the parts storage and stops charging -// you for the parts storage. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation UploadPart for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPart -func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { - req, out := c.UploadPartRequest(input) - return out, req.Send() -} - -// UploadPartWithContext is the same as UploadPart with the addition of -// the ability to pass a context and additional request options. -// -// See UploadPart for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) UploadPartWithContext(ctx aws.Context, input *UploadPartInput, opts ...request.Option) (*UploadPartOutput, error) { - req, out := c.UploadPartRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUploadPartCopy = "UploadPartCopy" - -// UploadPartCopyRequest generates a "aws/request.Request" representing the -// client's request for the UploadPartCopy operation. The "output" return -// value will be populated with the request's response once the request complets -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UploadPartCopy for more information on using the UploadPartCopy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UploadPartCopyRequest method. -// req, resp := client.UploadPartCopyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy -func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *request.Request, output *UploadPartCopyOutput) { - op := &request.Operation{ - Name: opUploadPartCopy, - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } - - if input == nil { - input = &UploadPartCopyInput{} - } - - output = &UploadPartCopyOutput{} - req = c.newRequest(op, input, output) - return -} - -// UploadPartCopy API operation for Amazon Simple Storage Service. -// -// Uploads a part by copying data from an existing object as data source. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Simple Storage Service's -// API operation UploadPartCopy for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopy -func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, error) { - req, out := c.UploadPartCopyRequest(input) - return out, req.Send() -} - -// UploadPartCopyWithContext is the same as UploadPartCopy with the addition of -// the ability to pass a context and additional request options. -// -// See UploadPartCopy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) UploadPartCopyWithContext(ctx aws.Context, input *UploadPartCopyInput, opts ...request.Option) (*UploadPartCopyOutput, error) { - req, out := c.UploadPartCopyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// Specifies the days since the initiation of an Incomplete Multipart Upload -// that Lifecycle will wait before permanently removing all parts of the upload. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortIncompleteMultipartUpload -type AbortIncompleteMultipartUpload struct { - _ struct{} `type:"structure"` - - // Indicates the number of days that must pass since initiation for Lifecycle - // to abort an Incomplete Multipart Upload. - DaysAfterInitiation *int64 `type:"integer"` -} - -// String returns the string representation -func (s AbortIncompleteMultipartUpload) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AbortIncompleteMultipartUpload) GoString() string { - return s.String() -} - -// SetDaysAfterInitiation sets the DaysAfterInitiation field's value. -func (s *AbortIncompleteMultipartUpload) SetDaysAfterInitiation(v int64) *AbortIncompleteMultipartUpload { - s.DaysAfterInitiation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadRequest -type AbortMultipartUploadInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` -} - -// String returns the string representation -func (s AbortMultipartUploadInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AbortMultipartUploadInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AbortMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AbortMultipartUploadInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *AbortMultipartUploadInput) SetBucket(v string) *AbortMultipartUploadInput { - s.Bucket = &v - return s -} - -func (s *AbortMultipartUploadInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *AbortMultipartUploadInput) SetKey(v string) *AbortMultipartUploadInput { - s.Key = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *AbortMultipartUploadInput) SetRequestPayer(v string) *AbortMultipartUploadInput { - s.RequestPayer = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *AbortMultipartUploadInput) SetUploadId(v string) *AbortMultipartUploadInput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AbortMultipartUploadOutput -type AbortMultipartUploadOutput struct { - _ struct{} `type:"structure"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -} - -// String returns the string representation -func (s AbortMultipartUploadOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AbortMultipartUploadOutput) GoString() string { - return s.String() -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *AbortMultipartUploadOutput) SetRequestCharged(v string) *AbortMultipartUploadOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccelerateConfiguration -type AccelerateConfiguration struct { - _ struct{} `type:"structure"` - - // The accelerate configuration of the bucket. - Status *string `type:"string" enum:"BucketAccelerateStatus"` -} - -// String returns the string representation -func (s AccelerateConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AccelerateConfiguration) GoString() string { - return s.String() -} - -// SetStatus sets the Status field's value. -func (s *AccelerateConfiguration) SetStatus(v string) *AccelerateConfiguration { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccessControlPolicy -type AccessControlPolicy struct { - _ struct{} `type:"structure"` - - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` -} - -// String returns the string representation -func (s AccessControlPolicy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AccessControlPolicy) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AccessControlPolicy) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AccessControlPolicy"} - if s.Grants != nil { - for i, v := range s.Grants { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Grants", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetGrants sets the Grants field's value. -func (s *AccessControlPolicy) SetGrants(v []*Grant) *AccessControlPolicy { - s.Grants = v - return s -} - -// SetOwner sets the Owner field's value. -func (s *AccessControlPolicy) SetOwner(v *Owner) *AccessControlPolicy { - s.Owner = v - return s -} - -// Container for information regarding the access control for replicas. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AccessControlTranslation -type AccessControlTranslation struct { - _ struct{} `type:"structure"` - - // The override value for the owner of the replica object. - // - // Owner is a required field - Owner *string `type:"string" required:"true" enum:"OwnerOverride"` -} - -// String returns the string representation -func (s AccessControlTranslation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AccessControlTranslation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AccessControlTranslation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AccessControlTranslation"} - if s.Owner == nil { - invalidParams.Add(request.NewErrParamRequired("Owner")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetOwner sets the Owner field's value. -func (s *AccessControlTranslation) SetOwner(v string) *AccessControlTranslation { - s.Owner = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsAndOperator -type AnalyticsAndOperator struct { - _ struct{} `type:"structure"` - - // The prefix to use when evaluating an AND predicate. - Prefix *string `type:"string"` - - // The list of tags to use when evaluating an AND predicate. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s AnalyticsAndOperator) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AnalyticsAndOperator) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsAndOperator) SetPrefix(v string) *AnalyticsAndOperator { - s.Prefix = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *AnalyticsAndOperator) SetTags(v []*Tag) *AnalyticsAndOperator { - s.Tags = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsConfiguration -type AnalyticsConfiguration struct { - _ struct{} `type:"structure"` - - // The filter used to describe a set of objects for analyses. A filter must - // have exactly one prefix, one tag, or one conjunction (AnalyticsAndOperator). - // If no filter is provided, all objects will be considered in any analysis. - Filter *AnalyticsFilter `type:"structure"` - - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // If present, it indicates that data related to access patterns will be collected - // and made available to analyze the tradeoffs between different storage classes. - // - // StorageClassAnalysis is a required field - StorageClassAnalysis *StorageClassAnalysis `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AnalyticsConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AnalyticsConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsConfiguration"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.StorageClassAnalysis == nil { - invalidParams.Add(request.NewErrParamRequired("StorageClassAnalysis")) - } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } - } - if s.StorageClassAnalysis != nil { - if err := s.StorageClassAnalysis.Validate(); err != nil { - invalidParams.AddNested("StorageClassAnalysis", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilter sets the Filter field's value. -func (s *AnalyticsConfiguration) SetFilter(v *AnalyticsFilter) *AnalyticsConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *AnalyticsConfiguration) SetId(v string) *AnalyticsConfiguration { - s.Id = &v - return s -} - -// SetStorageClassAnalysis sets the StorageClassAnalysis field's value. -func (s *AnalyticsConfiguration) SetStorageClassAnalysis(v *StorageClassAnalysis) *AnalyticsConfiguration { - s.StorageClassAnalysis = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsExportDestination -type AnalyticsExportDestination struct { - _ struct{} `type:"structure"` - - // A destination signifying output to an S3 bucket. - // - // S3BucketDestination is a required field - S3BucketDestination *AnalyticsS3BucketDestination `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AnalyticsExportDestination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AnalyticsExportDestination) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsExportDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsExportDestination"} - if s.S3BucketDestination == nil { - invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) - } - if s.S3BucketDestination != nil { - if err := s.S3BucketDestination.Validate(); err != nil { - invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetS3BucketDestination sets the S3BucketDestination field's value. -func (s *AnalyticsExportDestination) SetS3BucketDestination(v *AnalyticsS3BucketDestination) *AnalyticsExportDestination { - s.S3BucketDestination = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsFilter -type AnalyticsFilter struct { - _ struct{} `type:"structure"` - - // A conjunction (logical AND) of predicates, which is used in evaluating an - // analytics filter. The operator must have at least two predicates. - And *AnalyticsAndOperator `type:"structure"` - - // The prefix to use when evaluating an analytics filter. - Prefix *string `type:"string"` - - // The tag to use when evaluating an analytics filter. - Tag *Tag `type:"structure"` -} - -// String returns the string representation -func (s AnalyticsFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AnalyticsFilter) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } - } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnd sets the And field's value. -func (s *AnalyticsFilter) SetAnd(v *AnalyticsAndOperator) *AnalyticsFilter { - s.And = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsFilter) SetPrefix(v string) *AnalyticsFilter { - s.Prefix = &v - return s -} - -// SetTag sets the Tag field's value. -func (s *AnalyticsFilter) SetTag(v *Tag) *AnalyticsFilter { - s.Tag = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/AnalyticsS3BucketDestination -type AnalyticsS3BucketDestination struct { - _ struct{} `type:"structure"` - - // The Amazon resource name (ARN) of the bucket to which data is exported. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` - - // The account ID that owns the destination bucket. If no account ID is provided, - // the owner will not be validated prior to exporting data. - BucketAccountId *string `type:"string"` - - // The file format used when exporting data to Amazon S3. - // - // Format is a required field - Format *string `type:"string" required:"true" enum:"AnalyticsS3ExportFileFormat"` - - // The prefix to use when exporting data. The exported data begins with this - // prefix. - Prefix *string `type:"string"` -} - -// String returns the string representation -func (s AnalyticsS3BucketDestination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AnalyticsS3BucketDestination) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AnalyticsS3BucketDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AnalyticsS3BucketDestination"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Format == nil { - invalidParams.Add(request.NewErrParamRequired("Format")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *AnalyticsS3BucketDestination) SetBucket(v string) *AnalyticsS3BucketDestination { - s.Bucket = &v - return s -} - -func (s *AnalyticsS3BucketDestination) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetBucketAccountId sets the BucketAccountId field's value. -func (s *AnalyticsS3BucketDestination) SetBucketAccountId(v string) *AnalyticsS3BucketDestination { - s.BucketAccountId = &v - return s -} - -// SetFormat sets the Format field's value. -func (s *AnalyticsS3BucketDestination) SetFormat(v string) *AnalyticsS3BucketDestination { - s.Format = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *AnalyticsS3BucketDestination) SetPrefix(v string) *AnalyticsS3BucketDestination { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Bucket -type Bucket struct { - _ struct{} `type:"structure"` - - // Date the bucket was created. - CreationDate *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // The name of the bucket. - Name *string `type:"string"` -} - -// String returns the string representation -func (s Bucket) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Bucket) GoString() string { - return s.String() -} - -// SetCreationDate sets the CreationDate field's value. -func (s *Bucket) SetCreationDate(v time.Time) *Bucket { - s.CreationDate = &v - return s -} - -// SetName sets the Name field's value. -func (s *Bucket) SetName(v string) *Bucket { - s.Name = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLifecycleConfiguration -type BucketLifecycleConfiguration struct { - _ struct{} `type:"structure"` - - // Rules is a required field - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` -} - -// String returns the string representation -func (s BucketLifecycleConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s BucketLifecycleConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *BucketLifecycleConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BucketLifecycleConfiguration"} - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetRules sets the Rules field's value. -func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifecycleConfiguration { - s.Rules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/BucketLoggingStatus -type BucketLoggingStatus struct { - _ struct{} `type:"structure"` - - LoggingEnabled *LoggingEnabled `type:"structure"` -} - -// String returns the string representation -func (s BucketLoggingStatus) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s BucketLoggingStatus) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *BucketLoggingStatus) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "BucketLoggingStatus"} - if s.LoggingEnabled != nil { - if err := s.LoggingEnabled.Validate(); err != nil { - invalidParams.AddNested("LoggingEnabled", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoggingEnabled sets the LoggingEnabled field's value. -func (s *BucketLoggingStatus) SetLoggingEnabled(v *LoggingEnabled) *BucketLoggingStatus { - s.LoggingEnabled = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSConfiguration -type CORSConfiguration struct { - _ struct{} `type:"structure"` - - // CORSRules is a required field - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true" required:"true"` -} - -// String returns the string representation -func (s CORSConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CORSConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CORSConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CORSConfiguration"} - if s.CORSRules == nil { - invalidParams.Add(request.NewErrParamRequired("CORSRules")) - } - if s.CORSRules != nil { - for i, v := range s.CORSRules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "CORSRules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCORSRules sets the CORSRules field's value. -func (s *CORSConfiguration) SetCORSRules(v []*CORSRule) *CORSConfiguration { - s.CORSRules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CORSRule -type CORSRule struct { - _ struct{} `type:"structure"` - - // Specifies which headers are allowed in a pre-flight OPTIONS request. - AllowedHeaders []*string `locationName:"AllowedHeader" type:"list" flattened:"true"` - - // Identifies HTTP methods that the domain/origin specified in the rule is allowed - // to execute. - // - // AllowedMethods is a required field - AllowedMethods []*string `locationName:"AllowedMethod" type:"list" flattened:"true" required:"true"` - - // One or more origins you want customers to be able to access the bucket from. - // - // AllowedOrigins is a required field - AllowedOrigins []*string `locationName:"AllowedOrigin" type:"list" flattened:"true" required:"true"` - - // One or more headers in the response that you want customers to be able to - // access from their applications (for example, from a JavaScript XMLHttpRequest - // object). - ExposeHeaders []*string `locationName:"ExposeHeader" type:"list" flattened:"true"` - - // The time in seconds that your browser is to cache the preflight response - // for the specified resource. - MaxAgeSeconds *int64 `type:"integer"` -} - -// String returns the string representation -func (s CORSRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CORSRule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CORSRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CORSRule"} - if s.AllowedMethods == nil { - invalidParams.Add(request.NewErrParamRequired("AllowedMethods")) - } - if s.AllowedOrigins == nil { - invalidParams.Add(request.NewErrParamRequired("AllowedOrigins")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAllowedHeaders sets the AllowedHeaders field's value. -func (s *CORSRule) SetAllowedHeaders(v []*string) *CORSRule { - s.AllowedHeaders = v - return s -} - -// SetAllowedMethods sets the AllowedMethods field's value. -func (s *CORSRule) SetAllowedMethods(v []*string) *CORSRule { - s.AllowedMethods = v - return s -} - -// SetAllowedOrigins sets the AllowedOrigins field's value. -func (s *CORSRule) SetAllowedOrigins(v []*string) *CORSRule { - s.AllowedOrigins = v - return s -} - -// SetExposeHeaders sets the ExposeHeaders field's value. -func (s *CORSRule) SetExposeHeaders(v []*string) *CORSRule { - s.ExposeHeaders = v - return s -} - -// SetMaxAgeSeconds sets the MaxAgeSeconds field's value. -func (s *CORSRule) SetMaxAgeSeconds(v int64) *CORSRule { - s.MaxAgeSeconds = &v - return s -} - -// Describes how a CSV-formatted input object is formatted. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CSVInput -type CSVInput struct { - _ struct{} `type:"structure"` - - // Single character used to indicate a row should be ignored when present at - // the start of a row. - Comments *string `type:"string"` - - // Value used to separate individual fields in a record. - FieldDelimiter *string `type:"string"` - - // Describes the first line of input. Valid values: None, Ignore, Use. - FileHeaderInfo *string `type:"string" enum:"FileHeaderInfo"` - - // Value used for escaping where the field delimiter is part of the value. - QuoteCharacter *string `type:"string"` - - // Single character used for escaping the quote character inside an already - // escaped value. - QuoteEscapeCharacter *string `type:"string"` - - // Value used to separate individual records. - RecordDelimiter *string `type:"string"` -} - -// String returns the string representation -func (s CSVInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CSVInput) GoString() string { - return s.String() -} - -// SetComments sets the Comments field's value. -func (s *CSVInput) SetComments(v string) *CSVInput { - s.Comments = &v - return s -} - -// SetFieldDelimiter sets the FieldDelimiter field's value. -func (s *CSVInput) SetFieldDelimiter(v string) *CSVInput { - s.FieldDelimiter = &v - return s -} - -// SetFileHeaderInfo sets the FileHeaderInfo field's value. -func (s *CSVInput) SetFileHeaderInfo(v string) *CSVInput { - s.FileHeaderInfo = &v - return s -} - -// SetQuoteCharacter sets the QuoteCharacter field's value. -func (s *CSVInput) SetQuoteCharacter(v string) *CSVInput { - s.QuoteCharacter = &v - return s -} - -// SetQuoteEscapeCharacter sets the QuoteEscapeCharacter field's value. -func (s *CSVInput) SetQuoteEscapeCharacter(v string) *CSVInput { - s.QuoteEscapeCharacter = &v - return s -} - -// SetRecordDelimiter sets the RecordDelimiter field's value. -func (s *CSVInput) SetRecordDelimiter(v string) *CSVInput { - s.RecordDelimiter = &v - return s -} - -// Describes how CSV-formatted results are formatted. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CSVOutput -type CSVOutput struct { - _ struct{} `type:"structure"` - - // Value used to separate individual fields in a record. - FieldDelimiter *string `type:"string"` - - // Value used for escaping where the field delimiter is part of the value. - QuoteCharacter *string `type:"string"` - - // Single character used for escaping the quote character inside an already - // escaped value. - QuoteEscapeCharacter *string `type:"string"` - - // Indicates whether or not all output fields should be quoted. - QuoteFields *string `type:"string" enum:"QuoteFields"` - - // Value used to separate individual records. - RecordDelimiter *string `type:"string"` -} - -// String returns the string representation -func (s CSVOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CSVOutput) GoString() string { - return s.String() -} - -// SetFieldDelimiter sets the FieldDelimiter field's value. -func (s *CSVOutput) SetFieldDelimiter(v string) *CSVOutput { - s.FieldDelimiter = &v - return s -} - -// SetQuoteCharacter sets the QuoteCharacter field's value. -func (s *CSVOutput) SetQuoteCharacter(v string) *CSVOutput { - s.QuoteCharacter = &v - return s -} - -// SetQuoteEscapeCharacter sets the QuoteEscapeCharacter field's value. -func (s *CSVOutput) SetQuoteEscapeCharacter(v string) *CSVOutput { - s.QuoteEscapeCharacter = &v - return s -} - -// SetQuoteFields sets the QuoteFields field's value. -func (s *CSVOutput) SetQuoteFields(v string) *CSVOutput { - s.QuoteFields = &v - return s -} - -// SetRecordDelimiter sets the RecordDelimiter field's value. -func (s *CSVOutput) SetRecordDelimiter(v string) *CSVOutput { - s.RecordDelimiter = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CloudFunctionConfiguration -type CloudFunctionConfiguration struct { - _ struct{} `type:"structure"` - - CloudFunction *string `type:"string"` - - // Bucket event for which to send notifications. - Event *string `deprecated:"true" type:"string" enum:"Event"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - InvocationRole *string `type:"string"` -} - -// String returns the string representation -func (s CloudFunctionConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloudFunctionConfiguration) GoString() string { - return s.String() -} - -// SetCloudFunction sets the CloudFunction field's value. -func (s *CloudFunctionConfiguration) SetCloudFunction(v string) *CloudFunctionConfiguration { - s.CloudFunction = &v - return s -} - -// SetEvent sets the Event field's value. -func (s *CloudFunctionConfiguration) SetEvent(v string) *CloudFunctionConfiguration { - s.Event = &v - return s -} - -// SetEvents sets the Events field's value. -func (s *CloudFunctionConfiguration) SetEvents(v []*string) *CloudFunctionConfiguration { - s.Events = v - return s -} - -// SetId sets the Id field's value. -func (s *CloudFunctionConfiguration) SetId(v string) *CloudFunctionConfiguration { - s.Id = &v - return s -} - -// SetInvocationRole sets the InvocationRole field's value. -func (s *CloudFunctionConfiguration) SetInvocationRole(v string) *CloudFunctionConfiguration { - s.InvocationRole = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CommonPrefix -type CommonPrefix struct { - _ struct{} `type:"structure"` - - Prefix *string `type:"string"` -} - -// String returns the string representation -func (s CommonPrefix) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CommonPrefix) GoString() string { - return s.String() -} - -// SetPrefix sets the Prefix field's value. -func (s *CommonPrefix) SetPrefix(v string) *CommonPrefix { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadRequest -type CompleteMultipartUploadInput struct { - _ struct{} `type:"structure" payload:"MultipartUpload"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - MultipartUpload *CompletedMultipartUpload `locationName:"CompleteMultipartUpload" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` -} - -// String returns the string representation -func (s CompleteMultipartUploadInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CompleteMultipartUploadInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CompleteMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CompleteMultipartUploadInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *CompleteMultipartUploadInput) SetBucket(v string) *CompleteMultipartUploadInput { - s.Bucket = &v - return s -} - -func (s *CompleteMultipartUploadInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *CompleteMultipartUploadInput) SetKey(v string) *CompleteMultipartUploadInput { - s.Key = &v - return s -} - -// SetMultipartUpload sets the MultipartUpload field's value. -func (s *CompleteMultipartUploadInput) SetMultipartUpload(v *CompletedMultipartUpload) *CompleteMultipartUploadInput { - s.MultipartUpload = v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *CompleteMultipartUploadInput) SetRequestPayer(v string) *CompleteMultipartUploadInput { - s.RequestPayer = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *CompleteMultipartUploadInput) SetUploadId(v string) *CompleteMultipartUploadInput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompleteMultipartUploadOutput -type CompleteMultipartUploadOutput struct { - _ struct{} `type:"structure"` - - Bucket *string `type:"string"` - - // Entity tag of the object. - ETag *string `type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - Key *string `min:"1" type:"string"` - - Location *string `type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s CompleteMultipartUploadOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CompleteMultipartUploadOutput) GoString() string { - return s.String() -} - -// SetBucket sets the Bucket field's value. -func (s *CompleteMultipartUploadOutput) SetBucket(v string) *CompleteMultipartUploadOutput { - s.Bucket = &v - return s -} - -func (s *CompleteMultipartUploadOutput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetETag sets the ETag field's value. -func (s *CompleteMultipartUploadOutput) SetETag(v string) *CompleteMultipartUploadOutput { - s.ETag = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *CompleteMultipartUploadOutput) SetExpiration(v string) *CompleteMultipartUploadOutput { - s.Expiration = &v - return s -} - -// SetKey sets the Key field's value. -func (s *CompleteMultipartUploadOutput) SetKey(v string) *CompleteMultipartUploadOutput { - s.Key = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *CompleteMultipartUploadOutput) SetLocation(v string) *CompleteMultipartUploadOutput { - s.Location = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *CompleteMultipartUploadOutput) SetRequestCharged(v string) *CompleteMultipartUploadOutput { - s.RequestCharged = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CompleteMultipartUploadOutput) SetSSEKMSKeyId(v string) *CompleteMultipartUploadOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CompleteMultipartUploadOutput) SetServerSideEncryption(v string) *CompleteMultipartUploadOutput { - s.ServerSideEncryption = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *CompleteMultipartUploadOutput) SetVersionId(v string) *CompleteMultipartUploadOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedMultipartUpload -type CompletedMultipartUpload struct { - _ struct{} `type:"structure"` - - Parts []*CompletedPart `locationName:"Part" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s CompletedMultipartUpload) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CompletedMultipartUpload) GoString() string { - return s.String() -} - -// SetParts sets the Parts field's value. -func (s *CompletedMultipartUpload) SetParts(v []*CompletedPart) *CompletedMultipartUpload { - s.Parts = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CompletedPart -type CompletedPart struct { - _ struct{} `type:"structure"` - - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` - - // Part number that identifies the part. This is a positive integer between - // 1 and 10,000. - PartNumber *int64 `type:"integer"` -} - -// String returns the string representation -func (s CompletedPart) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CompletedPart) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *CompletedPart) SetETag(v string) *CompletedPart { - s.ETag = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *CompletedPart) SetPartNumber(v int64) *CompletedPart { - s.PartNumber = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Condition -type Condition struct { - _ struct{} `type:"structure"` - - // The HTTP error code when the redirect is applied. In the event of an error, - // if the error code equals this value, then the specified redirect is applied. - // Required when parent element Condition is specified and sibling KeyPrefixEquals - // is not specified. If both are specified, then both must be true for the redirect - // to be applied. - HttpErrorCodeReturnedEquals *string `type:"string"` - - // The object key name prefix when the redirect is applied. For example, to - // redirect requests for ExamplePage.html, the key prefix will be ExamplePage.html. - // To redirect request for all pages with the prefix docs/, the key prefix will - // be /docs, which identifies all objects in the docs/ folder. Required when - // the parent element Condition is specified and sibling HttpErrorCodeReturnedEquals - // is not specified. If both conditions are specified, both must be true for - // the redirect to be applied. - KeyPrefixEquals *string `type:"string"` -} - -// String returns the string representation -func (s Condition) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Condition) GoString() string { - return s.String() -} - -// SetHttpErrorCodeReturnedEquals sets the HttpErrorCodeReturnedEquals field's value. -func (s *Condition) SetHttpErrorCodeReturnedEquals(v string) *Condition { - s.HttpErrorCodeReturnedEquals = &v - return s -} - -// SetKeyPrefixEquals sets the KeyPrefixEquals field's value. -func (s *Condition) SetKeyPrefixEquals(v string) *Condition { - s.KeyPrefixEquals = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectRequest -type CopyObjectInput struct { - _ struct{} `type:"structure"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. - // - // CopySource is a required field - CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` - - // Copies the object if its entity tag (ETag) matches the specified tag. - CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` - - // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Copies the object if its entity tag (ETag) is different than the specified - // ETag. - CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` - - // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Specifies the algorithm to use when decrypting the source object (e.g., AES256). - CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt - // the source object. The encryption key provided in this header must be one - // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Specifies whether the metadata is copied from the source object or replaced - // with metadata provided in the request. - MetadataDirective *string `location:"header" locationName:"x-amz-metadata-directive" type:"string" enum:"MetadataDirective"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - - // The tag-set for the object destination object this value must be used in - // conjunction with the TaggingDirective. The tag-set must be encoded as URL - // Query parameters - Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` - - // Specifies whether the object tag-set are copied from the source object or - // replaced with tag-set provided in the request. - TaggingDirective *string `location:"header" locationName:"x-amz-tagging-directive" type:"string" enum:"TaggingDirective"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` -} - -// String returns the string representation -func (s CopyObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CopyObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CopyObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CopyObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.CopySource == nil { - invalidParams.Add(request.NewErrParamRequired("CopySource")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *CopyObjectInput) SetACL(v string) *CopyObjectInput { - s.ACL = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *CopyObjectInput) SetBucket(v string) *CopyObjectInput { - s.Bucket = &v - return s -} - -func (s *CopyObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCacheControl sets the CacheControl field's value. -func (s *CopyObjectInput) SetCacheControl(v string) *CopyObjectInput { - s.CacheControl = &v - return s -} - -// SetContentDisposition sets the ContentDisposition field's value. -func (s *CopyObjectInput) SetContentDisposition(v string) *CopyObjectInput { - s.ContentDisposition = &v - return s -} - -// SetContentEncoding sets the ContentEncoding field's value. -func (s *CopyObjectInput) SetContentEncoding(v string) *CopyObjectInput { - s.ContentEncoding = &v - return s -} - -// SetContentLanguage sets the ContentLanguage field's value. -func (s *CopyObjectInput) SetContentLanguage(v string) *CopyObjectInput { - s.ContentLanguage = &v - return s -} - -// SetContentType sets the ContentType field's value. -func (s *CopyObjectInput) SetContentType(v string) *CopyObjectInput { - s.ContentType = &v - return s -} - -// SetCopySource sets the CopySource field's value. -func (s *CopyObjectInput) SetCopySource(v string) *CopyObjectInput { - s.CopySource = &v - return s -} - -// SetCopySourceIfMatch sets the CopySourceIfMatch field's value. -func (s *CopyObjectInput) SetCopySourceIfMatch(v string) *CopyObjectInput { - s.CopySourceIfMatch = &v - return s -} - -// SetCopySourceIfModifiedSince sets the CopySourceIfModifiedSince field's value. -func (s *CopyObjectInput) SetCopySourceIfModifiedSince(v time.Time) *CopyObjectInput { - s.CopySourceIfModifiedSince = &v - return s -} - -// SetCopySourceIfNoneMatch sets the CopySourceIfNoneMatch field's value. -func (s *CopyObjectInput) SetCopySourceIfNoneMatch(v string) *CopyObjectInput { - s.CopySourceIfNoneMatch = &v - return s -} - -// SetCopySourceIfUnmodifiedSince sets the CopySourceIfUnmodifiedSince field's value. -func (s *CopyObjectInput) SetCopySourceIfUnmodifiedSince(v time.Time) *CopyObjectInput { - s.CopySourceIfUnmodifiedSince = &v - return s -} - -// SetCopySourceSSECustomerAlgorithm sets the CopySourceSSECustomerAlgorithm field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerAlgorithm(v string) *CopyObjectInput { - s.CopySourceSSECustomerAlgorithm = &v - return s -} - -// SetCopySourceSSECustomerKey sets the CopySourceSSECustomerKey field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerKey(v string) *CopyObjectInput { - s.CopySourceSSECustomerKey = &v - return s -} - -func (s *CopyObjectInput) getCopySourceSSECustomerKey() (v string) { - if s.CopySourceSSECustomerKey == nil { - return v - } - return *s.CopySourceSSECustomerKey -} - -// SetCopySourceSSECustomerKeyMD5 sets the CopySourceSSECustomerKeyMD5 field's value. -func (s *CopyObjectInput) SetCopySourceSSECustomerKeyMD5(v string) *CopyObjectInput { - s.CopySourceSSECustomerKeyMD5 = &v - return s -} - -// SetExpires sets the Expires field's value. -func (s *CopyObjectInput) SetExpires(v time.Time) *CopyObjectInput { - s.Expires = &v - return s -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CopyObjectInput) SetGrantFullControl(v string) *CopyObjectInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *CopyObjectInput) SetGrantRead(v string) *CopyObjectInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CopyObjectInput) SetGrantReadACP(v string) *CopyObjectInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CopyObjectInput) SetGrantWriteACP(v string) *CopyObjectInput { - s.GrantWriteACP = &v - return s -} - -// SetKey sets the Key field's value. -func (s *CopyObjectInput) SetKey(v string) *CopyObjectInput { - s.Key = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *CopyObjectInput) SetMetadata(v map[string]*string) *CopyObjectInput { - s.Metadata = v - return s -} - -// SetMetadataDirective sets the MetadataDirective field's value. -func (s *CopyObjectInput) SetMetadataDirective(v string) *CopyObjectInput { - s.MetadataDirective = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *CopyObjectInput) SetRequestPayer(v string) *CopyObjectInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CopyObjectInput) SetSSECustomerAlgorithm(v string) *CopyObjectInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *CopyObjectInput) SetSSECustomerKey(v string) *CopyObjectInput { - s.SSECustomerKey = &v - return s -} - -func (s *CopyObjectInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CopyObjectInput) SetSSECustomerKeyMD5(v string) *CopyObjectInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CopyObjectInput) SetSSEKMSKeyId(v string) *CopyObjectInput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CopyObjectInput) SetServerSideEncryption(v string) *CopyObjectInput { - s.ServerSideEncryption = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *CopyObjectInput) SetStorageClass(v string) *CopyObjectInput { - s.StorageClass = &v - return s -} - -// SetTagging sets the Tagging field's value. -func (s *CopyObjectInput) SetTagging(v string) *CopyObjectInput { - s.Tagging = &v - return s -} - -// SetTaggingDirective sets the TaggingDirective field's value. -func (s *CopyObjectInput) SetTaggingDirective(v string) *CopyObjectInput { - s.TaggingDirective = &v - return s -} - -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *CopyObjectInput) SetWebsiteRedirectLocation(v string) *CopyObjectInput { - s.WebsiteRedirectLocation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectOutput -type CopyObjectOutput struct { - _ struct{} `type:"structure" payload:"CopyObjectResult"` - - CopyObjectResult *CopyObjectResult `type:"structure"` - - CopySourceVersionId *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` - - // If the object expiration is configured, the response includes this header. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // Version ID of the newly created copy. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s CopyObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CopyObjectOutput) GoString() string { - return s.String() -} - -// SetCopyObjectResult sets the CopyObjectResult field's value. -func (s *CopyObjectOutput) SetCopyObjectResult(v *CopyObjectResult) *CopyObjectOutput { - s.CopyObjectResult = v - return s -} - -// SetCopySourceVersionId sets the CopySourceVersionId field's value. -func (s *CopyObjectOutput) SetCopySourceVersionId(v string) *CopyObjectOutput { - s.CopySourceVersionId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *CopyObjectOutput) SetExpiration(v string) *CopyObjectOutput { - s.Expiration = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *CopyObjectOutput) SetRequestCharged(v string) *CopyObjectOutput { - s.RequestCharged = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CopyObjectOutput) SetSSECustomerAlgorithm(v string) *CopyObjectOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CopyObjectOutput) SetSSECustomerKeyMD5(v string) *CopyObjectOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CopyObjectOutput) SetSSEKMSKeyId(v string) *CopyObjectOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CopyObjectOutput) SetServerSideEncryption(v string) *CopyObjectOutput { - s.ServerSideEncryption = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *CopyObjectOutput) SetVersionId(v string) *CopyObjectOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyObjectResult -type CopyObjectResult struct { - _ struct{} `type:"structure"` - - ETag *string `type:"string"` - - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// String returns the string representation -func (s CopyObjectResult) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CopyObjectResult) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *CopyObjectResult) SetETag(v string) *CopyObjectResult { - s.ETag = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *CopyObjectResult) SetLastModified(v time.Time) *CopyObjectResult { - s.LastModified = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CopyPartResult -type CopyPartResult struct { - _ struct{} `type:"structure"` - - // Entity tag of the object. - ETag *string `type:"string"` - - // Date and time at which the object was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` -} - -// String returns the string representation -func (s CopyPartResult) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CopyPartResult) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *CopyPartResult) SetETag(v string) *CopyPartResult { - s.ETag = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *CopyPartResult) SetLastModified(v time.Time) *CopyPartResult { - s.LastModified = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketConfiguration -type CreateBucketConfiguration struct { - _ struct{} `type:"structure"` - - // Specifies the region where the bucket will be created. If you don't specify - // a region, the bucket will be created in US Standard. - LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` -} - -// String returns the string representation -func (s CreateBucketConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateBucketConfiguration) GoString() string { - return s.String() -} - -// SetLocationConstraint sets the LocationConstraint field's value. -func (s *CreateBucketConfiguration) SetLocationConstraint(v string) *CreateBucketConfiguration { - s.LocationConstraint = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketRequest -type CreateBucketInput struct { - _ struct{} `type:"structure" payload:"CreateBucketConfiguration"` - - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - CreateBucketConfiguration *CreateBucketConfiguration `locationName:"CreateBucketConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` -} - -// String returns the string representation -func (s CreateBucketInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateBucketInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateBucketInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *CreateBucketInput) SetACL(v string) *CreateBucketInput { - s.ACL = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *CreateBucketInput) SetBucket(v string) *CreateBucketInput { - s.Bucket = &v - return s -} - -func (s *CreateBucketInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCreateBucketConfiguration sets the CreateBucketConfiguration field's value. -func (s *CreateBucketInput) SetCreateBucketConfiguration(v *CreateBucketConfiguration) *CreateBucketInput { - s.CreateBucketConfiguration = v - return s -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CreateBucketInput) SetGrantFullControl(v string) *CreateBucketInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *CreateBucketInput) SetGrantRead(v string) *CreateBucketInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CreateBucketInput) SetGrantReadACP(v string) *CreateBucketInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWrite sets the GrantWrite field's value. -func (s *CreateBucketInput) SetGrantWrite(v string) *CreateBucketInput { - s.GrantWrite = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CreateBucketInput) SetGrantWriteACP(v string) *CreateBucketInput { - s.GrantWriteACP = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateBucketOutput -type CreateBucketOutput struct { - _ struct{} `type:"structure"` - - Location *string `location:"header" locationName:"Location" type:"string"` -} - -// String returns the string representation -func (s CreateBucketOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateBucketOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateBucketOutput) SetLocation(v string) *CreateBucketOutput { - s.Location = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadRequest -type CreateMultipartUploadInput struct { - _ struct{} `type:"structure"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - - // The tag-set for the object. The tag-set must be encoded as URL Query parameters - Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` -} - -// String returns the string representation -func (s CreateMultipartUploadInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateMultipartUploadInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateMultipartUploadInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateMultipartUploadInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *CreateMultipartUploadInput) SetACL(v string) *CreateMultipartUploadInput { - s.ACL = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *CreateMultipartUploadInput) SetBucket(v string) *CreateMultipartUploadInput { - s.Bucket = &v - return s -} - -func (s *CreateMultipartUploadInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCacheControl sets the CacheControl field's value. -func (s *CreateMultipartUploadInput) SetCacheControl(v string) *CreateMultipartUploadInput { - s.CacheControl = &v - return s -} - -// SetContentDisposition sets the ContentDisposition field's value. -func (s *CreateMultipartUploadInput) SetContentDisposition(v string) *CreateMultipartUploadInput { - s.ContentDisposition = &v - return s -} - -// SetContentEncoding sets the ContentEncoding field's value. -func (s *CreateMultipartUploadInput) SetContentEncoding(v string) *CreateMultipartUploadInput { - s.ContentEncoding = &v - return s -} - -// SetContentLanguage sets the ContentLanguage field's value. -func (s *CreateMultipartUploadInput) SetContentLanguage(v string) *CreateMultipartUploadInput { - s.ContentLanguage = &v - return s -} - -// SetContentType sets the ContentType field's value. -func (s *CreateMultipartUploadInput) SetContentType(v string) *CreateMultipartUploadInput { - s.ContentType = &v - return s -} - -// SetExpires sets the Expires field's value. -func (s *CreateMultipartUploadInput) SetExpires(v time.Time) *CreateMultipartUploadInput { - s.Expires = &v - return s -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *CreateMultipartUploadInput) SetGrantFullControl(v string) *CreateMultipartUploadInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *CreateMultipartUploadInput) SetGrantRead(v string) *CreateMultipartUploadInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *CreateMultipartUploadInput) SetGrantReadACP(v string) *CreateMultipartUploadInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *CreateMultipartUploadInput) SetGrantWriteACP(v string) *CreateMultipartUploadInput { - s.GrantWriteACP = &v - return s -} - -// SetKey sets the Key field's value. -func (s *CreateMultipartUploadInput) SetKey(v string) *CreateMultipartUploadInput { - s.Key = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *CreateMultipartUploadInput) SetMetadata(v map[string]*string) *CreateMultipartUploadInput { - s.Metadata = v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *CreateMultipartUploadInput) SetRequestPayer(v string) *CreateMultipartUploadInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerKey(v string) *CreateMultipartUploadInput { - s.SSECustomerKey = &v - return s -} - -func (s *CreateMultipartUploadInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CreateMultipartUploadInput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CreateMultipartUploadInput) SetSSEKMSKeyId(v string) *CreateMultipartUploadInput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CreateMultipartUploadInput) SetServerSideEncryption(v string) *CreateMultipartUploadInput { - s.ServerSideEncryption = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *CreateMultipartUploadInput) SetStorageClass(v string) *CreateMultipartUploadInput { - s.StorageClass = &v - return s -} - -// SetTagging sets the Tagging field's value. -func (s *CreateMultipartUploadInput) SetTagging(v string) *CreateMultipartUploadInput { - s.Tagging = &v - return s -} - -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *CreateMultipartUploadInput) SetWebsiteRedirectLocation(v string) *CreateMultipartUploadInput { - s.WebsiteRedirectLocation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/CreateMultipartUploadOutput -type CreateMultipartUploadOutput struct { - _ struct{} `type:"structure"` - - // Date when multipart upload will become eligible for abort operation by lifecycle. - AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp" timestampFormat:"rfc822"` - - // Id of the lifecycle rule that makes a multipart upload eligible for abort - // operation. - AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` - - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `locationName:"Bucket" type:"string"` - - // Object key for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // ID for the initiated multipart upload. - UploadId *string `type:"string"` -} - -// String returns the string representation -func (s CreateMultipartUploadOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateMultipartUploadOutput) GoString() string { - return s.String() -} - -// SetAbortDate sets the AbortDate field's value. -func (s *CreateMultipartUploadOutput) SetAbortDate(v time.Time) *CreateMultipartUploadOutput { - s.AbortDate = &v - return s -} - -// SetAbortRuleId sets the AbortRuleId field's value. -func (s *CreateMultipartUploadOutput) SetAbortRuleId(v string) *CreateMultipartUploadOutput { - s.AbortRuleId = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *CreateMultipartUploadOutput) SetBucket(v string) *CreateMultipartUploadOutput { - s.Bucket = &v - return s -} - -func (s *CreateMultipartUploadOutput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *CreateMultipartUploadOutput) SetKey(v string) *CreateMultipartUploadOutput { - s.Key = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *CreateMultipartUploadOutput) SetRequestCharged(v string) *CreateMultipartUploadOutput { - s.RequestCharged = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *CreateMultipartUploadOutput) SetSSECustomerAlgorithm(v string) *CreateMultipartUploadOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *CreateMultipartUploadOutput) SetSSECustomerKeyMD5(v string) *CreateMultipartUploadOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *CreateMultipartUploadOutput) SetSSEKMSKeyId(v string) *CreateMultipartUploadOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *CreateMultipartUploadOutput) SetServerSideEncryption(v string) *CreateMultipartUploadOutput { - s.ServerSideEncryption = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *CreateMultipartUploadOutput) SetUploadId(v string) *CreateMultipartUploadOutput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Delete -type Delete struct { - _ struct{} `type:"structure"` - - // Objects is a required field - Objects []*ObjectIdentifier `locationName:"Object" type:"list" flattened:"true" required:"true"` - - // Element to enable quiet mode for the request. When you add this element, - // you must set its value to true. - Quiet *bool `type:"boolean"` -} - -// String returns the string representation -func (s Delete) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Delete) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Delete) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Delete"} - if s.Objects == nil { - invalidParams.Add(request.NewErrParamRequired("Objects")) - } - if s.Objects != nil { - for i, v := range s.Objects { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Objects", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetObjects sets the Objects field's value. -func (s *Delete) SetObjects(v []*ObjectIdentifier) *Delete { - s.Objects = v - return s -} - -// SetQuiet sets the Quiet field's value. -func (s *Delete) SetQuiet(v bool) *Delete { - s.Quiet = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationRequest -type DeleteBucketAnalyticsConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket from which an analytics configuration is deleted. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketAnalyticsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketAnalyticsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketAnalyticsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketAnalyticsConfigurationInput) SetBucket(v string) *DeleteBucketAnalyticsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketAnalyticsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *DeleteBucketAnalyticsConfigurationInput) SetId(v string) *DeleteBucketAnalyticsConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketAnalyticsConfigurationOutput -type DeleteBucketAnalyticsConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketAnalyticsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketAnalyticsConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsRequest -type DeleteBucketCorsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketCorsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketCorsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketCorsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketCorsInput) SetBucket(v string) *DeleteBucketCorsInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketCorsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketCorsOutput -type DeleteBucketCorsOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketCorsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketCorsOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryptionRequest -type DeleteBucketEncryptionInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the server-side encryption configuration - // to delete. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketEncryptionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketEncryptionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketEncryptionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketEncryptionInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketEncryptionInput) SetBucket(v string) *DeleteBucketEncryptionInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketEncryptionInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketEncryptionOutput -type DeleteBucketEncryptionOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketEncryptionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketEncryptionOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketRequest -type DeleteBucketInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketInput) SetBucket(v string) *DeleteBucketInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationRequest -type DeleteBucketInventoryConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the inventory configuration to delete. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketInventoryConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketInventoryConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketInventoryConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketInventoryConfigurationInput) SetBucket(v string) *DeleteBucketInventoryConfigurationInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketInventoryConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *DeleteBucketInventoryConfigurationInput) SetId(v string) *DeleteBucketInventoryConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketInventoryConfigurationOutput -type DeleteBucketInventoryConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketInventoryConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketInventoryConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleRequest -type DeleteBucketLifecycleInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketLifecycleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketLifecycleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketLifecycleInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketLifecycleInput) SetBucket(v string) *DeleteBucketLifecycleInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketLifecycleInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketLifecycleOutput -type DeleteBucketLifecycleOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketLifecycleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketLifecycleOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationRequest -type DeleteBucketMetricsConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the metrics configuration to delete. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketMetricsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketMetricsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketMetricsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketMetricsConfigurationInput) SetBucket(v string) *DeleteBucketMetricsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketMetricsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *DeleteBucketMetricsConfigurationInput) SetId(v string) *DeleteBucketMetricsConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketMetricsConfigurationOutput -type DeleteBucketMetricsConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketMetricsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketMetricsConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketOutput -type DeleteBucketOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyRequest -type DeleteBucketPolicyInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketPolicyInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketPolicyInput) SetBucket(v string) *DeleteBucketPolicyInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketPolicyInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketPolicyOutput -type DeleteBucketPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketPolicyOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationRequest -type DeleteBucketReplicationInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketReplicationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketReplicationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketReplicationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketReplicationInput) SetBucket(v string) *DeleteBucketReplicationInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketReplicationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketReplicationOutput -type DeleteBucketReplicationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketReplicationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketReplicationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingRequest -type DeleteBucketTaggingInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketTaggingInput) SetBucket(v string) *DeleteBucketTaggingInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketTaggingOutput -type DeleteBucketTaggingOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketTaggingOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteRequest -type DeleteBucketWebsiteInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteBucketWebsiteInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketWebsiteInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteBucketWebsiteInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteBucketWebsiteInput) SetBucket(v string) *DeleteBucketWebsiteInput { - s.Bucket = &v - return s -} - -func (s *DeleteBucketWebsiteInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteBucketWebsiteOutput -type DeleteBucketWebsiteOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteBucketWebsiteOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteBucketWebsiteOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteMarkerEntry -type DeleteMarkerEntry struct { - _ struct{} `type:"structure"` - - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `min:"1" type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - // Version ID of an object. - VersionId *string `type:"string"` -} - -// String returns the string representation -func (s DeleteMarkerEntry) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteMarkerEntry) GoString() string { - return s.String() -} - -// SetIsLatest sets the IsLatest field's value. -func (s *DeleteMarkerEntry) SetIsLatest(v bool) *DeleteMarkerEntry { - s.IsLatest = &v - return s -} - -// SetKey sets the Key field's value. -func (s *DeleteMarkerEntry) SetKey(v string) *DeleteMarkerEntry { - s.Key = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *DeleteMarkerEntry) SetLastModified(v time.Time) *DeleteMarkerEntry { - s.LastModified = &v - return s -} - -// SetOwner sets the Owner field's value. -func (s *DeleteMarkerEntry) SetOwner(v *Owner) *DeleteMarkerEntry { - s.Owner = v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteMarkerEntry) SetVersionId(v string) *DeleteMarkerEntry { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectRequest -type DeleteObjectInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s DeleteObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteObjectInput) SetBucket(v string) *DeleteObjectInput { - s.Bucket = &v - return s -} - -func (s *DeleteObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *DeleteObjectInput) SetKey(v string) *DeleteObjectInput { - s.Key = &v - return s -} - -// SetMFA sets the MFA field's value. -func (s *DeleteObjectInput) SetMFA(v string) *DeleteObjectInput { - s.MFA = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *DeleteObjectInput) SetRequestPayer(v string) *DeleteObjectInput { - s.RequestPayer = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectInput) SetVersionId(v string) *DeleteObjectInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectOutput -type DeleteObjectOutput struct { - _ struct{} `type:"structure"` - - // Specifies whether the versioned object that was permanently deleted was (true) - // or was not (false) a delete marker. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // Returns the version ID of the delete marker created as a result of the DELETE - // operation. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s DeleteObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectOutput) GoString() string { - return s.String() -} - -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *DeleteObjectOutput) SetDeleteMarker(v bool) *DeleteObjectOutput { - s.DeleteMarker = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *DeleteObjectOutput) SetRequestCharged(v string) *DeleteObjectOutput { - s.RequestCharged = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectOutput) SetVersionId(v string) *DeleteObjectOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingRequest -type DeleteObjectTaggingInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // The versionId of the object that the tag-set will be removed from. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s DeleteObjectTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteObjectTaggingInput) SetBucket(v string) *DeleteObjectTaggingInput { - s.Bucket = &v - return s -} - -func (s *DeleteObjectTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *DeleteObjectTaggingInput) SetKey(v string) *DeleteObjectTaggingInput { - s.Key = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectTaggingInput) SetVersionId(v string) *DeleteObjectTaggingInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectTaggingOutput -type DeleteObjectTaggingOutput struct { - _ struct{} `type:"structure"` - - // The versionId of the object the tag-set was removed from. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s DeleteObjectTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectTaggingOutput) GoString() string { - return s.String() -} - -// SetVersionId sets the VersionId field's value. -func (s *DeleteObjectTaggingOutput) SetVersionId(v string) *DeleteObjectTaggingOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsRequest -type DeleteObjectsInput struct { - _ struct{} `type:"structure" payload:"Delete"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Delete is a required field - Delete *Delete `locationName:"Delete" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` -} - -// String returns the string representation -func (s DeleteObjectsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteObjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteObjectsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Delete == nil { - invalidParams.Add(request.NewErrParamRequired("Delete")) - } - if s.Delete != nil { - if err := s.Delete.Validate(); err != nil { - invalidParams.AddNested("Delete", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *DeleteObjectsInput) SetBucket(v string) *DeleteObjectsInput { - s.Bucket = &v - return s -} - -func (s *DeleteObjectsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetDelete sets the Delete field's value. -func (s *DeleteObjectsInput) SetDelete(v *Delete) *DeleteObjectsInput { - s.Delete = v - return s -} - -// SetMFA sets the MFA field's value. -func (s *DeleteObjectsInput) SetMFA(v string) *DeleteObjectsInput { - s.MFA = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *DeleteObjectsInput) SetRequestPayer(v string) *DeleteObjectsInput { - s.RequestPayer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeleteObjectsOutput -type DeleteObjectsOutput struct { - _ struct{} `type:"structure"` - - Deleted []*DeletedObject `type:"list" flattened:"true"` - - Errors []*Error `locationName:"Error" type:"list" flattened:"true"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -} - -// String returns the string representation -func (s DeleteObjectsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteObjectsOutput) GoString() string { - return s.String() -} - -// SetDeleted sets the Deleted field's value. -func (s *DeleteObjectsOutput) SetDeleted(v []*DeletedObject) *DeleteObjectsOutput { - s.Deleted = v - return s -} - -// SetErrors sets the Errors field's value. -func (s *DeleteObjectsOutput) SetErrors(v []*Error) *DeleteObjectsOutput { - s.Errors = v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *DeleteObjectsOutput) SetRequestCharged(v string) *DeleteObjectsOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/DeletedObject -type DeletedObject struct { - _ struct{} `type:"structure"` - - DeleteMarker *bool `type:"boolean"` - - DeleteMarkerVersionId *string `type:"string"` - - Key *string `min:"1" type:"string"` - - VersionId *string `type:"string"` -} - -// String returns the string representation -func (s DeletedObject) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeletedObject) GoString() string { - return s.String() -} - -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *DeletedObject) SetDeleteMarker(v bool) *DeletedObject { - s.DeleteMarker = &v - return s -} - -// SetDeleteMarkerVersionId sets the DeleteMarkerVersionId field's value. -func (s *DeletedObject) SetDeleteMarkerVersionId(v string) *DeletedObject { - s.DeleteMarkerVersionId = &v - return s -} - -// SetKey sets the Key field's value. -func (s *DeletedObject) SetKey(v string) *DeletedObject { - s.Key = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *DeletedObject) SetVersionId(v string) *DeletedObject { - s.VersionId = &v - return s -} - -// Container for replication destination information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Destination -type Destination struct { - _ struct{} `type:"structure"` - - // Container for information regarding the access control for replicas. - AccessControlTranslation *AccessControlTranslation `type:"structure"` - - // Account ID of the destination bucket. Currently this is only being verified - // if Access Control Translation is enabled - Account *string `type:"string"` - - // Amazon resource name (ARN) of the bucket where you want Amazon S3 to store - // replicas of the object identified by the rule. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` - - // Container for information regarding encryption based configuration for replicas. - EncryptionConfiguration *EncryptionConfiguration `type:"structure"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` -} - -// String returns the string representation -func (s Destination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Destination) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Destination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Destination"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.AccessControlTranslation != nil { - if err := s.AccessControlTranslation.Validate(); err != nil { - invalidParams.AddNested("AccessControlTranslation", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessControlTranslation sets the AccessControlTranslation field's value. -func (s *Destination) SetAccessControlTranslation(v *AccessControlTranslation) *Destination { - s.AccessControlTranslation = v - return s -} - -// SetAccount sets the Account field's value. -func (s *Destination) SetAccount(v string) *Destination { - s.Account = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *Destination) SetBucket(v string) *Destination { - s.Bucket = &v - return s -} - -func (s *Destination) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetEncryptionConfiguration sets the EncryptionConfiguration field's value. -func (s *Destination) SetEncryptionConfiguration(v *EncryptionConfiguration) *Destination { - s.EncryptionConfiguration = v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *Destination) SetStorageClass(v string) *Destination { - s.StorageClass = &v - return s -} - -// Describes the server-side encryption that will be applied to the restore -// results. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Encryption -type Encryption struct { - _ struct{} `type:"structure"` - - // The server-side encryption algorithm used when storing job results in Amazon - // S3 (e.g., AES256, aws:kms). - // - // EncryptionType is a required field - EncryptionType *string `type:"string" required:"true" enum:"ServerSideEncryption"` - - // If the encryption type is aws:kms, this optional value can be used to specify - // the encryption context for the restore results. - KMSContext *string `type:"string"` - - // If the encryption type is aws:kms, this optional value specifies the AWS - // KMS key ID to use for encryption of job results. - KMSKeyId *string `type:"string"` -} - -// String returns the string representation -func (s Encryption) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Encryption) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Encryption) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Encryption"} - if s.EncryptionType == nil { - invalidParams.Add(request.NewErrParamRequired("EncryptionType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEncryptionType sets the EncryptionType field's value. -func (s *Encryption) SetEncryptionType(v string) *Encryption { - s.EncryptionType = &v - return s -} - -// SetKMSContext sets the KMSContext field's value. -func (s *Encryption) SetKMSContext(v string) *Encryption { - s.KMSContext = &v - return s -} - -// SetKMSKeyId sets the KMSKeyId field's value. -func (s *Encryption) SetKMSKeyId(v string) *Encryption { - s.KMSKeyId = &v - return s -} - -// Container for information regarding encryption based configuration for replicas. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/EncryptionConfiguration -type EncryptionConfiguration struct { - _ struct{} `type:"structure"` - - // The id of the KMS key used to encrypt the replica object. - ReplicaKmsKeyID *string `type:"string"` -} - -// String returns the string representation -func (s EncryptionConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s EncryptionConfiguration) GoString() string { - return s.String() -} - -// SetReplicaKmsKeyID sets the ReplicaKmsKeyID field's value. -func (s *EncryptionConfiguration) SetReplicaKmsKeyID(v string) *EncryptionConfiguration { - s.ReplicaKmsKeyID = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Error -type Error struct { - _ struct{} `type:"structure"` - - Code *string `type:"string"` - - Key *string `min:"1" type:"string"` - - Message *string `type:"string"` - - VersionId *string `type:"string"` -} - -// String returns the string representation -func (s Error) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Error) GoString() string { - return s.String() -} - -// SetCode sets the Code field's value. -func (s *Error) SetCode(v string) *Error { - s.Code = &v - return s -} - -// SetKey sets the Key field's value. -func (s *Error) SetKey(v string) *Error { - s.Key = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *Error) SetMessage(v string) *Error { - s.Message = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *Error) SetVersionId(v string) *Error { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ErrorDocument -type ErrorDocument struct { - _ struct{} `type:"structure"` - - // The object key name to use when a 4XX class error occurs. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s ErrorDocument) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ErrorDocument) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ErrorDocument) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ErrorDocument"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKey sets the Key field's value. -func (s *ErrorDocument) SetKey(v string) *ErrorDocument { - s.Key = &v - return s -} - -// Container for key value pair that defines the criteria for the filter rule. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/FilterRule -type FilterRule struct { - _ struct{} `type:"structure"` - - // Object key name prefix or suffix identifying one or more objects to which - // the filtering rule applies. Maximum prefix length can be up to 1,024 characters. - // Overlapping prefixes and suffixes are not supported. For more information, - // go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Name *string `type:"string" enum:"FilterRuleName"` - - Value *string `type:"string"` -} - -// String returns the string representation -func (s FilterRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s FilterRule) GoString() string { - return s.String() -} - -// SetName sets the Name field's value. -func (s *FilterRule) SetName(v string) *FilterRule { - s.Name = &v - return s -} - -// SetValue sets the Value field's value. -func (s *FilterRule) SetValue(v string) *FilterRule { - s.Value = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationRequest -type GetBucketAccelerateConfigurationInput struct { - _ struct{} `type:"structure"` - - // Name of the bucket for which the accelerate configuration is retrieved. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketAccelerateConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAccelerateConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAccelerateConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAccelerateConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketAccelerateConfigurationInput) SetBucket(v string) *GetBucketAccelerateConfigurationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketAccelerateConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAccelerateConfigurationOutput -type GetBucketAccelerateConfigurationOutput struct { - _ struct{} `type:"structure"` - - // The accelerate configuration of the bucket. - Status *string `type:"string" enum:"BucketAccelerateStatus"` -} - -// String returns the string representation -func (s GetBucketAccelerateConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAccelerateConfigurationOutput) GoString() string { - return s.String() -} - -// SetStatus sets the Status field's value. -func (s *GetBucketAccelerateConfigurationOutput) SetStatus(v string) *GetBucketAccelerateConfigurationOutput { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclRequest -type GetBucketAclInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketAclInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAclInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketAclInput) SetBucket(v string) *GetBucketAclInput { - s.Bucket = &v - return s -} - -func (s *GetBucketAclInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAclOutput -type GetBucketAclOutput struct { - _ struct{} `type:"structure"` - - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` -} - -// String returns the string representation -func (s GetBucketAclOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAclOutput) GoString() string { - return s.String() -} - -// SetGrants sets the Grants field's value. -func (s *GetBucketAclOutput) SetGrants(v []*Grant) *GetBucketAclOutput { - s.Grants = v - return s -} - -// SetOwner sets the Owner field's value. -func (s *GetBucketAclOutput) SetOwner(v *Owner) *GetBucketAclOutput { - s.Owner = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationRequest -type GetBucketAnalyticsConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket from which an analytics configuration is retrieved. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketAnalyticsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAnalyticsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketAnalyticsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketAnalyticsConfigurationInput) SetBucket(v string) *GetBucketAnalyticsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketAnalyticsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketAnalyticsConfigurationOutput -type GetBucketAnalyticsConfigurationOutput struct { - _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` - - // The configuration and any analyses for the analytics filter. - AnalyticsConfiguration *AnalyticsConfiguration `type:"structure"` -} - -// String returns the string representation -func (s GetBucketAnalyticsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketAnalyticsConfigurationOutput) GoString() string { - return s.String() -} - -// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. -func (s *GetBucketAnalyticsConfigurationOutput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *GetBucketAnalyticsConfigurationOutput { - s.AnalyticsConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsRequest -type GetBucketCorsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketCorsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketCorsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketCorsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketCorsInput) SetBucket(v string) *GetBucketCorsInput { - s.Bucket = &v - return s -} - -func (s *GetBucketCorsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketCorsOutput -type GetBucketCorsOutput struct { - _ struct{} `type:"structure"` - - CORSRules []*CORSRule `locationName:"CORSRule" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s GetBucketCorsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketCorsOutput) GoString() string { - return s.String() -} - -// SetCORSRules sets the CORSRules field's value. -func (s *GetBucketCorsOutput) SetCORSRules(v []*CORSRule) *GetBucketCorsOutput { - s.CORSRules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryptionRequest -type GetBucketEncryptionInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket from which the server-side encryption configuration - // is retrieved. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketEncryptionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketEncryptionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketEncryptionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketEncryptionInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketEncryptionInput) SetBucket(v string) *GetBucketEncryptionInput { - s.Bucket = &v - return s -} - -func (s *GetBucketEncryptionInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketEncryptionOutput -type GetBucketEncryptionOutput struct { - _ struct{} `type:"structure" payload:"ServerSideEncryptionConfiguration"` - - // Container for server-side encryption configuration rules. Currently S3 supports - // one rule only. - ServerSideEncryptionConfiguration *ServerSideEncryptionConfiguration `type:"structure"` -} - -// String returns the string representation -func (s GetBucketEncryptionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketEncryptionOutput) GoString() string { - return s.String() -} - -// SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value. -func (s *GetBucketEncryptionOutput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *GetBucketEncryptionOutput { - s.ServerSideEncryptionConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationRequest -type GetBucketInventoryConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the inventory configuration to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketInventoryConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketInventoryConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketInventoryConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketInventoryConfigurationInput) SetBucket(v string) *GetBucketInventoryConfigurationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketInventoryConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *GetBucketInventoryConfigurationInput) SetId(v string) *GetBucketInventoryConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketInventoryConfigurationOutput -type GetBucketInventoryConfigurationOutput struct { - _ struct{} `type:"structure" payload:"InventoryConfiguration"` - - // Specifies the inventory configuration. - InventoryConfiguration *InventoryConfiguration `type:"structure"` -} - -// String returns the string representation -func (s GetBucketInventoryConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketInventoryConfigurationOutput) GoString() string { - return s.String() -} - -// SetInventoryConfiguration sets the InventoryConfiguration field's value. -func (s *GetBucketInventoryConfigurationOutput) SetInventoryConfiguration(v *InventoryConfiguration) *GetBucketInventoryConfigurationOutput { - s.InventoryConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationRequest -type GetBucketLifecycleConfigurationInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketLifecycleConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLifecycleConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLifecycleConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketLifecycleConfigurationInput) SetBucket(v string) *GetBucketLifecycleConfigurationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketLifecycleConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleConfigurationOutput -type GetBucketLifecycleConfigurationOutput struct { - _ struct{} `type:"structure"` - - Rules []*LifecycleRule `locationName:"Rule" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s GetBucketLifecycleConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLifecycleConfigurationOutput) GoString() string { - return s.String() -} - -// SetRules sets the Rules field's value. -func (s *GetBucketLifecycleConfigurationOutput) SetRules(v []*LifecycleRule) *GetBucketLifecycleConfigurationOutput { - s.Rules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleRequest -type GetBucketLifecycleInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketLifecycleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLifecycleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLifecycleInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketLifecycleInput) SetBucket(v string) *GetBucketLifecycleInput { - s.Bucket = &v - return s -} - -func (s *GetBucketLifecycleInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLifecycleOutput -type GetBucketLifecycleOutput struct { - _ struct{} `type:"structure"` - - Rules []*Rule `locationName:"Rule" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s GetBucketLifecycleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLifecycleOutput) GoString() string { - return s.String() -} - -// SetRules sets the Rules field's value. -func (s *GetBucketLifecycleOutput) SetRules(v []*Rule) *GetBucketLifecycleOutput { - s.Rules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationRequest -type GetBucketLocationInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketLocationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLocationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLocationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLocationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketLocationInput) SetBucket(v string) *GetBucketLocationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketLocationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLocationOutput -type GetBucketLocationOutput struct { - _ struct{} `type:"structure"` - - LocationConstraint *string `type:"string" enum:"BucketLocationConstraint"` -} - -// String returns the string representation -func (s GetBucketLocationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLocationOutput) GoString() string { - return s.String() -} - -// SetLocationConstraint sets the LocationConstraint field's value. -func (s *GetBucketLocationOutput) SetLocationConstraint(v string) *GetBucketLocationOutput { - s.LocationConstraint = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingRequest -type GetBucketLoggingInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketLoggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLoggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketLoggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketLoggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketLoggingInput) SetBucket(v string) *GetBucketLoggingInput { - s.Bucket = &v - return s -} - -func (s *GetBucketLoggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketLoggingOutput -type GetBucketLoggingOutput struct { - _ struct{} `type:"structure"` - - LoggingEnabled *LoggingEnabled `type:"structure"` -} - -// String returns the string representation -func (s GetBucketLoggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketLoggingOutput) GoString() string { - return s.String() -} - -// SetLoggingEnabled sets the LoggingEnabled field's value. -func (s *GetBucketLoggingOutput) SetLoggingEnabled(v *LoggingEnabled) *GetBucketLoggingOutput { - s.LoggingEnabled = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationRequest -type GetBucketMetricsConfigurationInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the metrics configuration to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketMetricsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketMetricsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketMetricsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketMetricsConfigurationInput) SetBucket(v string) *GetBucketMetricsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketMetricsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *GetBucketMetricsConfigurationInput) SetId(v string) *GetBucketMetricsConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketMetricsConfigurationOutput -type GetBucketMetricsConfigurationOutput struct { - _ struct{} `type:"structure" payload:"MetricsConfiguration"` - - // Specifies the metrics configuration. - MetricsConfiguration *MetricsConfiguration `type:"structure"` -} - -// String returns the string representation -func (s GetBucketMetricsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketMetricsConfigurationOutput) GoString() string { - return s.String() -} - -// SetMetricsConfiguration sets the MetricsConfiguration field's value. -func (s *GetBucketMetricsConfigurationOutput) SetMetricsConfiguration(v *MetricsConfiguration) *GetBucketMetricsConfigurationOutput { - s.MetricsConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketNotificationConfigurationRequest -type GetBucketNotificationConfigurationRequest struct { - _ struct{} `type:"structure"` - - // Name of the bucket to get the notification configuration for. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketNotificationConfigurationRequest) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketNotificationConfigurationRequest) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketNotificationConfigurationRequest) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketNotificationConfigurationRequest"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketNotificationConfigurationRequest) SetBucket(v string) *GetBucketNotificationConfigurationRequest { - s.Bucket = &v - return s -} - -func (s *GetBucketNotificationConfigurationRequest) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyRequest -type GetBucketPolicyInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketPolicyInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketPolicyInput) SetBucket(v string) *GetBucketPolicyInput { - s.Bucket = &v - return s -} - -func (s *GetBucketPolicyInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicyOutput -type GetBucketPolicyOutput struct { - _ struct{} `type:"structure" payload:"Policy"` - - // The bucket policy as a JSON document. - Policy *string `type:"string"` -} - -// String returns the string representation -func (s GetBucketPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketPolicyOutput) GoString() string { - return s.String() -} - -// SetPolicy sets the Policy field's value. -func (s *GetBucketPolicyOutput) SetPolicy(v string) *GetBucketPolicyOutput { - s.Policy = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationRequest -type GetBucketReplicationInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketReplicationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketReplicationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketReplicationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketReplicationInput) SetBucket(v string) *GetBucketReplicationInput { - s.Bucket = &v - return s -} - -func (s *GetBucketReplicationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketReplicationOutput -type GetBucketReplicationOutput struct { - _ struct{} `type:"structure" payload:"ReplicationConfiguration"` - - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - ReplicationConfiguration *ReplicationConfiguration `type:"structure"` -} - -// String returns the string representation -func (s GetBucketReplicationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketReplicationOutput) GoString() string { - return s.String() -} - -// SetReplicationConfiguration sets the ReplicationConfiguration field's value. -func (s *GetBucketReplicationOutput) SetReplicationConfiguration(v *ReplicationConfiguration) *GetBucketReplicationOutput { - s.ReplicationConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentRequest -type GetBucketRequestPaymentInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketRequestPaymentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketRequestPaymentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketRequestPaymentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketRequestPaymentInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketRequestPaymentInput) SetBucket(v string) *GetBucketRequestPaymentInput { - s.Bucket = &v - return s -} - -func (s *GetBucketRequestPaymentInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketRequestPaymentOutput -type GetBucketRequestPaymentOutput struct { - _ struct{} `type:"structure"` - - // Specifies who pays for the download and request fees. - Payer *string `type:"string" enum:"Payer"` -} - -// String returns the string representation -func (s GetBucketRequestPaymentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketRequestPaymentOutput) GoString() string { - return s.String() -} - -// SetPayer sets the Payer field's value. -func (s *GetBucketRequestPaymentOutput) SetPayer(v string) *GetBucketRequestPaymentOutput { - s.Payer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingRequest -type GetBucketTaggingInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketTaggingInput) SetBucket(v string) *GetBucketTaggingInput { - s.Bucket = &v - return s -} - -func (s *GetBucketTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketTaggingOutput -type GetBucketTaggingOutput struct { - _ struct{} `type:"structure"` - - // TagSet is a required field - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` -} - -// String returns the string representation -func (s GetBucketTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketTaggingOutput) GoString() string { - return s.String() -} - -// SetTagSet sets the TagSet field's value. -func (s *GetBucketTaggingOutput) SetTagSet(v []*Tag) *GetBucketTaggingOutput { - s.TagSet = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningRequest -type GetBucketVersioningInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketVersioningInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketVersioningInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketVersioningInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketVersioningInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketVersioningInput) SetBucket(v string) *GetBucketVersioningInput { - s.Bucket = &v - return s -} - -func (s *GetBucketVersioningInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketVersioningOutput -type GetBucketVersioningOutput struct { - _ struct{} `type:"structure"` - - // Specifies whether MFA delete is enabled in the bucket versioning configuration. - // This element is only returned if the bucket has been configured with MFA - // delete. If the bucket has never been so configured, this element is not returned. - MFADelete *string `locationName:"MfaDelete" type:"string" enum:"MFADeleteStatus"` - - // The versioning state of the bucket. - Status *string `type:"string" enum:"BucketVersioningStatus"` -} - -// String returns the string representation -func (s GetBucketVersioningOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketVersioningOutput) GoString() string { - return s.String() -} - -// SetMFADelete sets the MFADelete field's value. -func (s *GetBucketVersioningOutput) SetMFADelete(v string) *GetBucketVersioningOutput { - s.MFADelete = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *GetBucketVersioningOutput) SetStatus(v string) *GetBucketVersioningOutput { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteRequest -type GetBucketWebsiteInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetBucketWebsiteInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketWebsiteInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetBucketWebsiteInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetBucketWebsiteInput) SetBucket(v string) *GetBucketWebsiteInput { - s.Bucket = &v - return s -} - -func (s *GetBucketWebsiteInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketWebsiteOutput -type GetBucketWebsiteOutput struct { - _ struct{} `type:"structure"` - - ErrorDocument *ErrorDocument `type:"structure"` - - IndexDocument *IndexDocument `type:"structure"` - - RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - - RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` -} - -// String returns the string representation -func (s GetBucketWebsiteOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBucketWebsiteOutput) GoString() string { - return s.String() -} - -// SetErrorDocument sets the ErrorDocument field's value. -func (s *GetBucketWebsiteOutput) SetErrorDocument(v *ErrorDocument) *GetBucketWebsiteOutput { - s.ErrorDocument = v - return s -} - -// SetIndexDocument sets the IndexDocument field's value. -func (s *GetBucketWebsiteOutput) SetIndexDocument(v *IndexDocument) *GetBucketWebsiteOutput { - s.IndexDocument = v - return s -} - -// SetRedirectAllRequestsTo sets the RedirectAllRequestsTo field's value. -func (s *GetBucketWebsiteOutput) SetRedirectAllRequestsTo(v *RedirectAllRequestsTo) *GetBucketWebsiteOutput { - s.RedirectAllRequestsTo = v - return s -} - -// SetRoutingRules sets the RoutingRules field's value. -func (s *GetBucketWebsiteOutput) SetRoutingRules(v []*RoutingRule) *GetBucketWebsiteOutput { - s.RoutingRules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclRequest -type GetObjectAclInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s GetObjectAclInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectAclInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetObjectAclInput) SetBucket(v string) *GetObjectAclInput { - s.Bucket = &v - return s -} - -func (s *GetObjectAclInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *GetObjectAclInput) SetKey(v string) *GetObjectAclInput { - s.Key = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectAclInput) SetRequestPayer(v string) *GetObjectAclInput { - s.RequestPayer = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *GetObjectAclInput) SetVersionId(v string) *GetObjectAclInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectAclOutput -type GetObjectAclOutput struct { - _ struct{} `type:"structure"` - - // A list of grants. - Grants []*Grant `locationName:"AccessControlList" locationNameList:"Grant" type:"list"` - - Owner *Owner `type:"structure"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -} - -// String returns the string representation -func (s GetObjectAclOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectAclOutput) GoString() string { - return s.String() -} - -// SetGrants sets the Grants field's value. -func (s *GetObjectAclOutput) SetGrants(v []*Grant) *GetObjectAclOutput { - s.Grants = v - return s -} - -// SetOwner sets the Owner field's value. -func (s *GetObjectAclOutput) SetOwner(v *Owner) *GetObjectAclOutput { - s.Owner = v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectAclOutput) SetRequestCharged(v string) *GetObjectAclOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectRequest -type GetObjectInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` - - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` - - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Part number of the object being read. This is a positive integer between - // 1 and 10,000. Effectively performs a 'ranged' GET request for the part specified. - // Useful for downloading just a part of an object. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` - - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Sets the Cache-Control header of the response. - ResponseCacheControl *string `location:"querystring" locationName:"response-cache-control" type:"string"` - - // Sets the Content-Disposition header of the response - ResponseContentDisposition *string `location:"querystring" locationName:"response-content-disposition" type:"string"` - - // Sets the Content-Encoding header of the response. - ResponseContentEncoding *string `location:"querystring" locationName:"response-content-encoding" type:"string"` - - // Sets the Content-Language header of the response. - ResponseContentLanguage *string `location:"querystring" locationName:"response-content-language" type:"string"` - - // Sets the Content-Type header of the response. - ResponseContentType *string `location:"querystring" locationName:"response-content-type" type:"string"` - - // Sets the Expires header of the response. - ResponseExpires *time.Time `location:"querystring" locationName:"response-expires" type:"timestamp" timestampFormat:"iso8601"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s GetObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetObjectInput) SetBucket(v string) *GetObjectInput { - s.Bucket = &v - return s -} - -func (s *GetObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetIfMatch sets the IfMatch field's value. -func (s *GetObjectInput) SetIfMatch(v string) *GetObjectInput { - s.IfMatch = &v - return s -} - -// SetIfModifiedSince sets the IfModifiedSince field's value. -func (s *GetObjectInput) SetIfModifiedSince(v time.Time) *GetObjectInput { - s.IfModifiedSince = &v - return s -} - -// SetIfNoneMatch sets the IfNoneMatch field's value. -func (s *GetObjectInput) SetIfNoneMatch(v string) *GetObjectInput { - s.IfNoneMatch = &v - return s -} - -// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. -func (s *GetObjectInput) SetIfUnmodifiedSince(v time.Time) *GetObjectInput { - s.IfUnmodifiedSince = &v - return s -} - -// SetKey sets the Key field's value. -func (s *GetObjectInput) SetKey(v string) *GetObjectInput { - s.Key = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *GetObjectInput) SetPartNumber(v int64) *GetObjectInput { - s.PartNumber = &v - return s -} - -// SetRange sets the Range field's value. -func (s *GetObjectInput) SetRange(v string) *GetObjectInput { - s.Range = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectInput) SetRequestPayer(v string) *GetObjectInput { - s.RequestPayer = &v - return s -} - -// SetResponseCacheControl sets the ResponseCacheControl field's value. -func (s *GetObjectInput) SetResponseCacheControl(v string) *GetObjectInput { - s.ResponseCacheControl = &v - return s -} - -// SetResponseContentDisposition sets the ResponseContentDisposition field's value. -func (s *GetObjectInput) SetResponseContentDisposition(v string) *GetObjectInput { - s.ResponseContentDisposition = &v - return s -} - -// SetResponseContentEncoding sets the ResponseContentEncoding field's value. -func (s *GetObjectInput) SetResponseContentEncoding(v string) *GetObjectInput { - s.ResponseContentEncoding = &v - return s -} - -// SetResponseContentLanguage sets the ResponseContentLanguage field's value. -func (s *GetObjectInput) SetResponseContentLanguage(v string) *GetObjectInput { - s.ResponseContentLanguage = &v - return s -} - -// SetResponseContentType sets the ResponseContentType field's value. -func (s *GetObjectInput) SetResponseContentType(v string) *GetObjectInput { - s.ResponseContentType = &v - return s -} - -// SetResponseExpires sets the ResponseExpires field's value. -func (s *GetObjectInput) SetResponseExpires(v time.Time) *GetObjectInput { - s.ResponseExpires = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *GetObjectInput) SetSSECustomerAlgorithm(v string) *GetObjectInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *GetObjectInput) SetSSECustomerKey(v string) *GetObjectInput { - s.SSECustomerKey = &v - return s -} - -func (s *GetObjectInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *GetObjectInput) SetSSECustomerKeyMD5(v string) *GetObjectInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *GetObjectInput) SetVersionId(v string) *GetObjectInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectOutput -type GetObjectOutput struct { - _ struct{} `type:"structure" payload:"Body"` - - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - - // Object data. - Body io.ReadCloser `type:"blob"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - - // The portion of the object returned in the response. - ContentRange *string `location:"header" locationName:"Content-Range" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *string `location:"header" locationName:"Expires" type:"string"` - - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` - - // The count of parts this object has. - PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` - - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - - // The number of tags, if any, on the object. - TagCount *int64 `location:"header" locationName:"x-amz-tagging-count" type:"integer"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` -} - -// String returns the string representation -func (s GetObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectOutput) GoString() string { - return s.String() -} - -// SetAcceptRanges sets the AcceptRanges field's value. -func (s *GetObjectOutput) SetAcceptRanges(v string) *GetObjectOutput { - s.AcceptRanges = &v - return s -} - -// SetBody sets the Body field's value. -func (s *GetObjectOutput) SetBody(v io.ReadCloser) *GetObjectOutput { - s.Body = v - return s -} - -// SetCacheControl sets the CacheControl field's value. -func (s *GetObjectOutput) SetCacheControl(v string) *GetObjectOutput { - s.CacheControl = &v - return s -} - -// SetContentDisposition sets the ContentDisposition field's value. -func (s *GetObjectOutput) SetContentDisposition(v string) *GetObjectOutput { - s.ContentDisposition = &v - return s -} - -// SetContentEncoding sets the ContentEncoding field's value. -func (s *GetObjectOutput) SetContentEncoding(v string) *GetObjectOutput { - s.ContentEncoding = &v - return s -} - -// SetContentLanguage sets the ContentLanguage field's value. -func (s *GetObjectOutput) SetContentLanguage(v string) *GetObjectOutput { - s.ContentLanguage = &v - return s -} - -// SetContentLength sets the ContentLength field's value. -func (s *GetObjectOutput) SetContentLength(v int64) *GetObjectOutput { - s.ContentLength = &v - return s -} - -// SetContentRange sets the ContentRange field's value. -func (s *GetObjectOutput) SetContentRange(v string) *GetObjectOutput { - s.ContentRange = &v - return s -} - -// SetContentType sets the ContentType field's value. -func (s *GetObjectOutput) SetContentType(v string) *GetObjectOutput { - s.ContentType = &v - return s -} - -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *GetObjectOutput) SetDeleteMarker(v bool) *GetObjectOutput { - s.DeleteMarker = &v - return s -} - -// SetETag sets the ETag field's value. -func (s *GetObjectOutput) SetETag(v string) *GetObjectOutput { - s.ETag = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *GetObjectOutput) SetExpiration(v string) *GetObjectOutput { - s.Expiration = &v - return s -} - -// SetExpires sets the Expires field's value. -func (s *GetObjectOutput) SetExpires(v string) *GetObjectOutput { - s.Expires = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *GetObjectOutput) SetLastModified(v time.Time) *GetObjectOutput { - s.LastModified = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *GetObjectOutput) SetMetadata(v map[string]*string) *GetObjectOutput { - s.Metadata = v - return s -} - -// SetMissingMeta sets the MissingMeta field's value. -func (s *GetObjectOutput) SetMissingMeta(v int64) *GetObjectOutput { - s.MissingMeta = &v - return s -} - -// SetPartsCount sets the PartsCount field's value. -func (s *GetObjectOutput) SetPartsCount(v int64) *GetObjectOutput { - s.PartsCount = &v - return s -} - -// SetReplicationStatus sets the ReplicationStatus field's value. -func (s *GetObjectOutput) SetReplicationStatus(v string) *GetObjectOutput { - s.ReplicationStatus = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectOutput) SetRequestCharged(v string) *GetObjectOutput { - s.RequestCharged = &v - return s -} - -// SetRestore sets the Restore field's value. -func (s *GetObjectOutput) SetRestore(v string) *GetObjectOutput { - s.Restore = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *GetObjectOutput) SetSSECustomerAlgorithm(v string) *GetObjectOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *GetObjectOutput) SetSSECustomerKeyMD5(v string) *GetObjectOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *GetObjectOutput) SetSSEKMSKeyId(v string) *GetObjectOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *GetObjectOutput) SetServerSideEncryption(v string) *GetObjectOutput { - s.ServerSideEncryption = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *GetObjectOutput) SetStorageClass(v string) *GetObjectOutput { - s.StorageClass = &v - return s -} - -// SetTagCount sets the TagCount field's value. -func (s *GetObjectOutput) SetTagCount(v int64) *GetObjectOutput { - s.TagCount = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *GetObjectOutput) SetVersionId(v string) *GetObjectOutput { - s.VersionId = &v - return s -} - -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *GetObjectOutput) SetWebsiteRedirectLocation(v string) *GetObjectOutput { - s.WebsiteRedirectLocation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingRequest -type GetObjectTaggingInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s GetObjectTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetObjectTaggingInput) SetBucket(v string) *GetObjectTaggingInput { - s.Bucket = &v - return s -} - -func (s *GetObjectTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *GetObjectTaggingInput) SetKey(v string) *GetObjectTaggingInput { - s.Key = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *GetObjectTaggingInput) SetVersionId(v string) *GetObjectTaggingInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTaggingOutput -type GetObjectTaggingOutput struct { - _ struct{} `type:"structure"` - - // TagSet is a required field - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` - - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s GetObjectTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectTaggingOutput) GoString() string { - return s.String() -} - -// SetTagSet sets the TagSet field's value. -func (s *GetObjectTaggingOutput) SetTagSet(v []*Tag) *GetObjectTaggingOutput { - s.TagSet = v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *GetObjectTaggingOutput) SetVersionId(v string) *GetObjectTaggingOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentRequest -type GetObjectTorrentInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` -} - -// String returns the string representation -func (s GetObjectTorrentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectTorrentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetObjectTorrentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetObjectTorrentInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *GetObjectTorrentInput) SetBucket(v string) *GetObjectTorrentInput { - s.Bucket = &v - return s -} - -func (s *GetObjectTorrentInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *GetObjectTorrentInput) SetKey(v string) *GetObjectTorrentInput { - s.Key = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *GetObjectTorrentInput) SetRequestPayer(v string) *GetObjectTorrentInput { - s.RequestPayer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrentOutput -type GetObjectTorrentOutput struct { - _ struct{} `type:"structure" payload:"Body"` - - Body io.ReadCloser `type:"blob"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -} - -// String returns the string representation -func (s GetObjectTorrentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetObjectTorrentOutput) GoString() string { - return s.String() -} - -// SetBody sets the Body field's value. -func (s *GetObjectTorrentOutput) SetBody(v io.ReadCloser) *GetObjectTorrentOutput { - s.Body = v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *GetObjectTorrentOutput) SetRequestCharged(v string) *GetObjectTorrentOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GlacierJobParameters -type GlacierJobParameters struct { - _ struct{} `type:"structure"` - - // Glacier retrieval tier at which the restore will be processed. - // - // Tier is a required field - Tier *string `type:"string" required:"true" enum:"Tier"` -} - -// String returns the string representation -func (s GlacierJobParameters) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GlacierJobParameters) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GlacierJobParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GlacierJobParameters"} - if s.Tier == nil { - invalidParams.Add(request.NewErrParamRequired("Tier")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetTier sets the Tier field's value. -func (s *GlacierJobParameters) SetTier(v string) *GlacierJobParameters { - s.Tier = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grant -type Grant struct { - _ struct{} `type:"structure"` - - Grantee *Grantee `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - - // Specifies the permission given to the grantee. - Permission *string `type:"string" enum:"Permission"` -} - -// String returns the string representation -func (s Grant) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Grant) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Grant) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Grant"} - if s.Grantee != nil { - if err := s.Grantee.Validate(); err != nil { - invalidParams.AddNested("Grantee", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetGrantee sets the Grantee field's value. -func (s *Grant) SetGrantee(v *Grantee) *Grant { - s.Grantee = v - return s -} - -// SetPermission sets the Permission field's value. -func (s *Grant) SetPermission(v string) *Grant { - s.Permission = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Grantee -type Grantee struct { - _ struct{} `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - - // Screen name of the grantee. - DisplayName *string `type:"string"` - - // Email address of the grantee. - EmailAddress *string `type:"string"` - - // The canonical user ID of the grantee. - ID *string `type:"string"` - - // Type of grantee - // - // Type is a required field - Type *string `locationName:"xsi:type" type:"string" xmlAttribute:"true" required:"true" enum:"Type"` - - // URI of the grantee group. - URI *string `type:"string"` -} - -// String returns the string representation -func (s Grantee) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Grantee) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Grantee) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Grantee"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDisplayName sets the DisplayName field's value. -func (s *Grantee) SetDisplayName(v string) *Grantee { - s.DisplayName = &v - return s -} - -// SetEmailAddress sets the EmailAddress field's value. -func (s *Grantee) SetEmailAddress(v string) *Grantee { - s.EmailAddress = &v - return s -} - -// SetID sets the ID field's value. -func (s *Grantee) SetID(v string) *Grantee { - s.ID = &v - return s -} - -// SetType sets the Type field's value. -func (s *Grantee) SetType(v string) *Grantee { - s.Type = &v - return s -} - -// SetURI sets the URI field's value. -func (s *Grantee) SetURI(v string) *Grantee { - s.URI = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketRequest -type HeadBucketInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s HeadBucketInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HeadBucketInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *HeadBucketInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HeadBucketInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *HeadBucketInput) SetBucket(v string) *HeadBucketInput { - s.Bucket = &v - return s -} - -func (s *HeadBucketInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadBucketOutput -type HeadBucketOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s HeadBucketOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HeadBucketOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectRequest -type HeadObjectInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Return the object only if its entity tag (ETag) is the same as the one specified, - // otherwise return a 412 (precondition failed). - IfMatch *string `location:"header" locationName:"If-Match" type:"string"` - - // Return the object only if it has been modified since the specified time, - // otherwise return a 304 (not modified). - IfModifiedSince *time.Time `location:"header" locationName:"If-Modified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Return the object only if its entity tag (ETag) is different from the one - // specified, otherwise return a 304 (not modified). - IfNoneMatch *string `location:"header" locationName:"If-None-Match" type:"string"` - - // Return the object only if it has not been modified since the specified time, - // otherwise return a 412 (precondition failed). - IfUnmodifiedSince *time.Time `location:"header" locationName:"If-Unmodified-Since" type:"timestamp" timestampFormat:"rfc822"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Part number of the object being read. This is a positive integer between - // 1 and 10,000. Effectively performs a 'ranged' HEAD request for the part specified. - // Useful querying about the size of the part and the number of parts in this - // object. - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer"` - - // Downloads the specified range bytes of an object. For more information about - // the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. - Range *string `location:"header" locationName:"Range" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s HeadObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HeadObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *HeadObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HeadObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *HeadObjectInput) SetBucket(v string) *HeadObjectInput { - s.Bucket = &v - return s -} - -func (s *HeadObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetIfMatch sets the IfMatch field's value. -func (s *HeadObjectInput) SetIfMatch(v string) *HeadObjectInput { - s.IfMatch = &v - return s -} - -// SetIfModifiedSince sets the IfModifiedSince field's value. -func (s *HeadObjectInput) SetIfModifiedSince(v time.Time) *HeadObjectInput { - s.IfModifiedSince = &v - return s -} - -// SetIfNoneMatch sets the IfNoneMatch field's value. -func (s *HeadObjectInput) SetIfNoneMatch(v string) *HeadObjectInput { - s.IfNoneMatch = &v - return s -} - -// SetIfUnmodifiedSince sets the IfUnmodifiedSince field's value. -func (s *HeadObjectInput) SetIfUnmodifiedSince(v time.Time) *HeadObjectInput { - s.IfUnmodifiedSince = &v - return s -} - -// SetKey sets the Key field's value. -func (s *HeadObjectInput) SetKey(v string) *HeadObjectInput { - s.Key = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *HeadObjectInput) SetPartNumber(v int64) *HeadObjectInput { - s.PartNumber = &v - return s -} - -// SetRange sets the Range field's value. -func (s *HeadObjectInput) SetRange(v string) *HeadObjectInput { - s.Range = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *HeadObjectInput) SetRequestPayer(v string) *HeadObjectInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *HeadObjectInput) SetSSECustomerAlgorithm(v string) *HeadObjectInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *HeadObjectInput) SetSSECustomerKey(v string) *HeadObjectInput { - s.SSECustomerKey = &v - return s -} - -func (s *HeadObjectInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *HeadObjectInput) SetSSECustomerKeyMD5(v string) *HeadObjectInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *HeadObjectInput) SetVersionId(v string) *HeadObjectInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/HeadObjectOutput -type HeadObjectOutput struct { - _ struct{} `type:"structure"` - - AcceptRanges *string `location:"header" locationName:"accept-ranges" type:"string"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // Specifies whether the object retrieved was (true) or was not (false) a Delete - // Marker. If false, this response header does not appear in the response. - DeleteMarker *bool `location:"header" locationName:"x-amz-delete-marker" type:"boolean"` - - // An ETag is an opaque identifier assigned by a web server to a specific version - // of a resource found at a URL - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured (see PUT Bucket lifecycle), the response - // includes this header. It includes the expiry-date and rule-id key value pairs - // providing object expiration information. The value of the rule-id is URL - // encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *string `location:"header" locationName:"Expires" type:"string"` - - // Last modified date of the object - LastModified *time.Time `location:"header" locationName:"Last-Modified" type:"timestamp" timestampFormat:"rfc822"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // This is set to the number of metadata entries not returned in x-amz-meta - // headers. This can happen if you create metadata using an API like SOAP that - // supports more flexible metadata than the REST API. For example, using SOAP, - // you can create metadata whose values are not legal HTTP headers. - MissingMeta *int64 `location:"header" locationName:"x-amz-missing-meta" type:"integer"` - - // The count of parts this object has. - PartsCount *int64 `location:"header" locationName:"x-amz-mp-parts-count" type:"integer"` - - ReplicationStatus *string `location:"header" locationName:"x-amz-replication-status" type:"string" enum:"ReplicationStatus"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // Provides information about object restoration operation and expiration time - // of the restored object copy. - Restore *string `location:"header" locationName:"x-amz-restore" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` -} - -// String returns the string representation -func (s HeadObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HeadObjectOutput) GoString() string { - return s.String() -} - -// SetAcceptRanges sets the AcceptRanges field's value. -func (s *HeadObjectOutput) SetAcceptRanges(v string) *HeadObjectOutput { - s.AcceptRanges = &v - return s -} - -// SetCacheControl sets the CacheControl field's value. -func (s *HeadObjectOutput) SetCacheControl(v string) *HeadObjectOutput { - s.CacheControl = &v - return s -} - -// SetContentDisposition sets the ContentDisposition field's value. -func (s *HeadObjectOutput) SetContentDisposition(v string) *HeadObjectOutput { - s.ContentDisposition = &v - return s -} - -// SetContentEncoding sets the ContentEncoding field's value. -func (s *HeadObjectOutput) SetContentEncoding(v string) *HeadObjectOutput { - s.ContentEncoding = &v - return s -} - -// SetContentLanguage sets the ContentLanguage field's value. -func (s *HeadObjectOutput) SetContentLanguage(v string) *HeadObjectOutput { - s.ContentLanguage = &v - return s -} - -// SetContentLength sets the ContentLength field's value. -func (s *HeadObjectOutput) SetContentLength(v int64) *HeadObjectOutput { - s.ContentLength = &v - return s -} - -// SetContentType sets the ContentType field's value. -func (s *HeadObjectOutput) SetContentType(v string) *HeadObjectOutput { - s.ContentType = &v - return s -} - -// SetDeleteMarker sets the DeleteMarker field's value. -func (s *HeadObjectOutput) SetDeleteMarker(v bool) *HeadObjectOutput { - s.DeleteMarker = &v - return s -} - -// SetETag sets the ETag field's value. -func (s *HeadObjectOutput) SetETag(v string) *HeadObjectOutput { - s.ETag = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *HeadObjectOutput) SetExpiration(v string) *HeadObjectOutput { - s.Expiration = &v - return s -} - -// SetExpires sets the Expires field's value. -func (s *HeadObjectOutput) SetExpires(v string) *HeadObjectOutput { - s.Expires = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *HeadObjectOutput) SetLastModified(v time.Time) *HeadObjectOutput { - s.LastModified = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *HeadObjectOutput) SetMetadata(v map[string]*string) *HeadObjectOutput { - s.Metadata = v - return s -} - -// SetMissingMeta sets the MissingMeta field's value. -func (s *HeadObjectOutput) SetMissingMeta(v int64) *HeadObjectOutput { - s.MissingMeta = &v - return s -} - -// SetPartsCount sets the PartsCount field's value. -func (s *HeadObjectOutput) SetPartsCount(v int64) *HeadObjectOutput { - s.PartsCount = &v - return s -} - -// SetReplicationStatus sets the ReplicationStatus field's value. -func (s *HeadObjectOutput) SetReplicationStatus(v string) *HeadObjectOutput { - s.ReplicationStatus = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *HeadObjectOutput) SetRequestCharged(v string) *HeadObjectOutput { - s.RequestCharged = &v - return s -} - -// SetRestore sets the Restore field's value. -func (s *HeadObjectOutput) SetRestore(v string) *HeadObjectOutput { - s.Restore = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *HeadObjectOutput) SetSSECustomerAlgorithm(v string) *HeadObjectOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *HeadObjectOutput) SetSSECustomerKeyMD5(v string) *HeadObjectOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *HeadObjectOutput) SetSSEKMSKeyId(v string) *HeadObjectOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *HeadObjectOutput) SetServerSideEncryption(v string) *HeadObjectOutput { - s.ServerSideEncryption = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *HeadObjectOutput) SetStorageClass(v string) *HeadObjectOutput { - s.StorageClass = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *HeadObjectOutput) SetVersionId(v string) *HeadObjectOutput { - s.VersionId = &v - return s -} - -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *HeadObjectOutput) SetWebsiteRedirectLocation(v string) *HeadObjectOutput { - s.WebsiteRedirectLocation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/IndexDocument -type IndexDocument struct { - _ struct{} `type:"structure"` - - // A suffix that is appended to a request that is for a directory on the website - // endpoint (e.g. if the suffix is index.html and you make a request to samplebucket/images/ - // the data that is returned will be for the object with the key name images/index.html) - // The suffix must not be empty and must not include a slash character. - // - // Suffix is a required field - Suffix *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s IndexDocument) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s IndexDocument) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *IndexDocument) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "IndexDocument"} - if s.Suffix == nil { - invalidParams.Add(request.NewErrParamRequired("Suffix")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetSuffix sets the Suffix field's value. -func (s *IndexDocument) SetSuffix(v string) *IndexDocument { - s.Suffix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Initiator -type Initiator struct { - _ struct{} `type:"structure"` - - // Name of the Principal. - DisplayName *string `type:"string"` - - // If the principal is an AWS account, it provides the Canonical User ID. If - // the principal is an IAM User, it provides a user ARN value. - ID *string `type:"string"` -} - -// String returns the string representation -func (s Initiator) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Initiator) GoString() string { - return s.String() -} - -// SetDisplayName sets the DisplayName field's value. -func (s *Initiator) SetDisplayName(v string) *Initiator { - s.DisplayName = &v - return s -} - -// SetID sets the ID field's value. -func (s *Initiator) SetID(v string) *Initiator { - s.ID = &v - return s -} - -// Describes the serialization format of the object. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InputSerialization -type InputSerialization struct { - _ struct{} `type:"structure"` - - // Describes the serialization of a CSV-encoded object. - CSV *CSVInput `type:"structure"` -} - -// String returns the string representation -func (s InputSerialization) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InputSerialization) GoString() string { - return s.String() -} - -// SetCSV sets the CSV field's value. -func (s *InputSerialization) SetCSV(v *CSVInput) *InputSerialization { - s.CSV = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryConfiguration -type InventoryConfiguration struct { - _ struct{} `type:"structure"` - - // Contains information about where to publish the inventory results. - // - // Destination is a required field - Destination *InventoryDestination `type:"structure" required:"true"` - - // Specifies an inventory filter. The inventory only includes objects that meet - // the filter's criteria. - Filter *InventoryFilter `type:"structure"` - - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // Specifies which object version(s) to included in the inventory results. - // - // IncludedObjectVersions is a required field - IncludedObjectVersions *string `type:"string" required:"true" enum:"InventoryIncludedObjectVersions"` - - // Specifies whether the inventory is enabled or disabled. - // - // IsEnabled is a required field - IsEnabled *bool `type:"boolean" required:"true"` - - // Contains the optional fields that are included in the inventory results. - OptionalFields []*string `locationNameList:"Field" type:"list"` - - // Specifies the schedule for generating inventory results. - // - // Schedule is a required field - Schedule *InventorySchedule `type:"structure" required:"true"` -} - -// String returns the string representation -func (s InventoryConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventoryConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryConfiguration"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.IncludedObjectVersions == nil { - invalidParams.Add(request.NewErrParamRequired("IncludedObjectVersions")) - } - if s.IsEnabled == nil { - invalidParams.Add(request.NewErrParamRequired("IsEnabled")) - } - if s.Schedule == nil { - invalidParams.Add(request.NewErrParamRequired("Schedule")) - } - if s.Destination != nil { - if err := s.Destination.Validate(); err != nil { - invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) - } - } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } - } - if s.Schedule != nil { - if err := s.Schedule.Validate(); err != nil { - invalidParams.AddNested("Schedule", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestination sets the Destination field's value. -func (s *InventoryConfiguration) SetDestination(v *InventoryDestination) *InventoryConfiguration { - s.Destination = v - return s -} - -// SetFilter sets the Filter field's value. -func (s *InventoryConfiguration) SetFilter(v *InventoryFilter) *InventoryConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *InventoryConfiguration) SetId(v string) *InventoryConfiguration { - s.Id = &v - return s -} - -// SetIncludedObjectVersions sets the IncludedObjectVersions field's value. -func (s *InventoryConfiguration) SetIncludedObjectVersions(v string) *InventoryConfiguration { - s.IncludedObjectVersions = &v - return s -} - -// SetIsEnabled sets the IsEnabled field's value. -func (s *InventoryConfiguration) SetIsEnabled(v bool) *InventoryConfiguration { - s.IsEnabled = &v - return s -} - -// SetOptionalFields sets the OptionalFields field's value. -func (s *InventoryConfiguration) SetOptionalFields(v []*string) *InventoryConfiguration { - s.OptionalFields = v - return s -} - -// SetSchedule sets the Schedule field's value. -func (s *InventoryConfiguration) SetSchedule(v *InventorySchedule) *InventoryConfiguration { - s.Schedule = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryDestination -type InventoryDestination struct { - _ struct{} `type:"structure"` - - // Contains the bucket name, file format, bucket owner (optional), and prefix - // (optional) where inventory results are published. - // - // S3BucketDestination is a required field - S3BucketDestination *InventoryS3BucketDestination `type:"structure" required:"true"` -} - -// String returns the string representation -func (s InventoryDestination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventoryDestination) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryDestination"} - if s.S3BucketDestination == nil { - invalidParams.Add(request.NewErrParamRequired("S3BucketDestination")) - } - if s.S3BucketDestination != nil { - if err := s.S3BucketDestination.Validate(); err != nil { - invalidParams.AddNested("S3BucketDestination", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetS3BucketDestination sets the S3BucketDestination field's value. -func (s *InventoryDestination) SetS3BucketDestination(v *InventoryS3BucketDestination) *InventoryDestination { - s.S3BucketDestination = v - return s -} - -// Contains the type of server-side encryption used to encrypt the inventory -// results. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryEncryption -type InventoryEncryption struct { - _ struct{} `type:"structure"` - - // Specifies the use of SSE-KMS to encrypt delievered Inventory reports. - SSEKMS *SSEKMS `locationName:"SSE-KMS" type:"structure"` - - // Specifies the use of SSE-S3 to encrypt delievered Inventory reports. - SSES3 *SSES3 `locationName:"SSE-S3" type:"structure"` -} - -// String returns the string representation -func (s InventoryEncryption) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventoryEncryption) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryEncryption) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryEncryption"} - if s.SSEKMS != nil { - if err := s.SSEKMS.Validate(); err != nil { - invalidParams.AddNested("SSEKMS", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetSSEKMS sets the SSEKMS field's value. -func (s *InventoryEncryption) SetSSEKMS(v *SSEKMS) *InventoryEncryption { - s.SSEKMS = v - return s -} - -// SetSSES3 sets the SSES3 field's value. -func (s *InventoryEncryption) SetSSES3(v *SSES3) *InventoryEncryption { - s.SSES3 = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryFilter -type InventoryFilter struct { - _ struct{} `type:"structure"` - - // The prefix that an object must have to be included in the inventory results. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s InventoryFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventoryFilter) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryFilter"} - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPrefix sets the Prefix field's value. -func (s *InventoryFilter) SetPrefix(v string) *InventoryFilter { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventoryS3BucketDestination -type InventoryS3BucketDestination struct { - _ struct{} `type:"structure"` - - // The ID of the account that owns the destination bucket. - AccountId *string `type:"string"` - - // The Amazon resource name (ARN) of the bucket where inventory results will - // be published. - // - // Bucket is a required field - Bucket *string `type:"string" required:"true"` - - // Contains the type of server-side encryption used to encrypt the inventory - // results. - Encryption *InventoryEncryption `type:"structure"` - - // Specifies the output format of the inventory results. - // - // Format is a required field - Format *string `type:"string" required:"true" enum:"InventoryFormat"` - - // The prefix that is prepended to all inventory results. - Prefix *string `type:"string"` -} - -// String returns the string representation -func (s InventoryS3BucketDestination) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventoryS3BucketDestination) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventoryS3BucketDestination) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventoryS3BucketDestination"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Format == nil { - invalidParams.Add(request.NewErrParamRequired("Format")) - } - if s.Encryption != nil { - if err := s.Encryption.Validate(); err != nil { - invalidParams.AddNested("Encryption", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccountId sets the AccountId field's value. -func (s *InventoryS3BucketDestination) SetAccountId(v string) *InventoryS3BucketDestination { - s.AccountId = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *InventoryS3BucketDestination) SetBucket(v string) *InventoryS3BucketDestination { - s.Bucket = &v - return s -} - -func (s *InventoryS3BucketDestination) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetEncryption sets the Encryption field's value. -func (s *InventoryS3BucketDestination) SetEncryption(v *InventoryEncryption) *InventoryS3BucketDestination { - s.Encryption = v - return s -} - -// SetFormat sets the Format field's value. -func (s *InventoryS3BucketDestination) SetFormat(v string) *InventoryS3BucketDestination { - s.Format = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *InventoryS3BucketDestination) SetPrefix(v string) *InventoryS3BucketDestination { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/InventorySchedule -type InventorySchedule struct { - _ struct{} `type:"structure"` - - // Specifies how frequently inventory results are produced. - // - // Frequency is a required field - Frequency *string `type:"string" required:"true" enum:"InventoryFrequency"` -} - -// String returns the string representation -func (s InventorySchedule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InventorySchedule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *InventorySchedule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "InventorySchedule"} - if s.Frequency == nil { - invalidParams.Add(request.NewErrParamRequired("Frequency")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFrequency sets the Frequency field's value. -func (s *InventorySchedule) SetFrequency(v string) *InventorySchedule { - s.Frequency = &v - return s -} - -// Container for object key name prefix and suffix filtering rules. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/S3KeyFilter -type KeyFilter struct { - _ struct{} `type:"structure"` - - // A list of containers for key value pair that defines the criteria for the - // filter rule. - FilterRules []*FilterRule `locationName:"FilterRule" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s KeyFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s KeyFilter) GoString() string { - return s.String() -} - -// SetFilterRules sets the FilterRules field's value. -func (s *KeyFilter) SetFilterRules(v []*FilterRule) *KeyFilter { - s.FilterRules = v - return s -} - -// Container for specifying the AWS Lambda notification configuration. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LambdaFunctionConfiguration -type LambdaFunctionConfiguration struct { - _ struct{} `type:"structure"` - - // Events is a required field - Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Filter *NotificationConfigurationFilter `type:"structure"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - // Lambda cloud function ARN that Amazon S3 can invoke when it detects events - // of the specified type. - // - // LambdaFunctionArn is a required field - LambdaFunctionArn *string `locationName:"CloudFunction" type:"string" required:"true"` -} - -// String returns the string representation -func (s LambdaFunctionConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LambdaFunctionConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LambdaFunctionConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LambdaFunctionConfiguration"} - if s.Events == nil { - invalidParams.Add(request.NewErrParamRequired("Events")) - } - if s.LambdaFunctionArn == nil { - invalidParams.Add(request.NewErrParamRequired("LambdaFunctionArn")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEvents sets the Events field's value. -func (s *LambdaFunctionConfiguration) SetEvents(v []*string) *LambdaFunctionConfiguration { - s.Events = v - return s -} - -// SetFilter sets the Filter field's value. -func (s *LambdaFunctionConfiguration) SetFilter(v *NotificationConfigurationFilter) *LambdaFunctionConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *LambdaFunctionConfiguration) SetId(v string) *LambdaFunctionConfiguration { - s.Id = &v - return s -} - -// SetLambdaFunctionArn sets the LambdaFunctionArn field's value. -func (s *LambdaFunctionConfiguration) SetLambdaFunctionArn(v string) *LambdaFunctionConfiguration { - s.LambdaFunctionArn = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleConfiguration -type LifecycleConfiguration struct { - _ struct{} `type:"structure"` - - // Rules is a required field - Rules []*Rule `locationName:"Rule" type:"list" flattened:"true" required:"true"` -} - -// String returns the string representation -func (s LifecycleConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LifecycleConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleConfiguration"} - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetRules sets the Rules field's value. -func (s *LifecycleConfiguration) SetRules(v []*Rule) *LifecycleConfiguration { - s.Rules = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleExpiration -type LifecycleExpiration struct { - _ struct{} `type:"structure"` - - // Indicates at what date the object is to be moved or deleted. Should be in - // GMT ISO 8601 Format. - Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Indicates the lifetime, in days, of the objects that are subject to the rule. - // The value must be a non-zero positive integer. - Days *int64 `type:"integer"` - - // Indicates whether Amazon S3 will remove a delete marker with no noncurrent - // versions. If set to true, the delete marker will be expired; if set to false - // the policy takes no action. This cannot be specified with Days or Date in - // a Lifecycle Expiration Policy. - ExpiredObjectDeleteMarker *bool `type:"boolean"` -} - -// String returns the string representation -func (s LifecycleExpiration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LifecycleExpiration) GoString() string { - return s.String() -} - -// SetDate sets the Date field's value. -func (s *LifecycleExpiration) SetDate(v time.Time) *LifecycleExpiration { - s.Date = &v - return s -} - -// SetDays sets the Days field's value. -func (s *LifecycleExpiration) SetDays(v int64) *LifecycleExpiration { - s.Days = &v - return s -} - -// SetExpiredObjectDeleteMarker sets the ExpiredObjectDeleteMarker field's value. -func (s *LifecycleExpiration) SetExpiredObjectDeleteMarker(v bool) *LifecycleExpiration { - s.ExpiredObjectDeleteMarker = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRule -type LifecycleRule struct { - _ struct{} `type:"structure"` - - // Specifies the days since the initiation of an Incomplete Multipart Upload - // that Lifecycle will wait before permanently removing all parts of the upload. - AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` - - Expiration *LifecycleExpiration `type:"structure"` - - // The Filter is used to identify objects that a Lifecycle Rule applies to. - // A Filter must have exactly one of Prefix, Tag, or And specified. - Filter *LifecycleRuleFilter `type:"structure"` - - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` - - // Specifies when noncurrent object versions expire. Upon expiration, Amazon - // S3 permanently deletes the noncurrent object versions. You set this lifecycle - // configuration action on a bucket that has versioning enabled (or suspended) - // to request that Amazon S3 delete noncurrent object versions at a specific - // period in the object's lifetime. - NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` - - NoncurrentVersionTransitions []*NoncurrentVersionTransition `locationName:"NoncurrentVersionTransition" type:"list" flattened:"true"` - - // Prefix identifying one or more objects to which the rule applies. This is - // deprecated; use Filter instead. - Prefix *string `deprecated:"true" type:"string"` - - // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule - // is not currently being applied. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - - Transitions []*Transition `locationName:"Transition" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s LifecycleRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LifecycleRule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRule"} - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) - } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. -func (s *LifecycleRule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *LifecycleRule { - s.AbortIncompleteMultipartUpload = v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *LifecycleRule) SetExpiration(v *LifecycleExpiration) *LifecycleRule { - s.Expiration = v - return s -} - -// SetFilter sets the Filter field's value. -func (s *LifecycleRule) SetFilter(v *LifecycleRuleFilter) *LifecycleRule { - s.Filter = v - return s -} - -// SetID sets the ID field's value. -func (s *LifecycleRule) SetID(v string) *LifecycleRule { - s.ID = &v - return s -} - -// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. -func (s *LifecycleRule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *LifecycleRule { - s.NoncurrentVersionExpiration = v - return s -} - -// SetNoncurrentVersionTransitions sets the NoncurrentVersionTransitions field's value. -func (s *LifecycleRule) SetNoncurrentVersionTransitions(v []*NoncurrentVersionTransition) *LifecycleRule { - s.NoncurrentVersionTransitions = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *LifecycleRule) SetPrefix(v string) *LifecycleRule { - s.Prefix = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *LifecycleRule) SetStatus(v string) *LifecycleRule { - s.Status = &v - return s -} - -// SetTransitions sets the Transitions field's value. -func (s *LifecycleRule) SetTransitions(v []*Transition) *LifecycleRule { - s.Transitions = v - return s -} - -// This is used in a Lifecycle Rule Filter to apply a logical AND to two or -// more predicates. The Lifecycle Rule will apply to any object matching all -// of the predicates configured inside the And operator. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleAndOperator -type LifecycleRuleAndOperator struct { - _ struct{} `type:"structure"` - - Prefix *string `type:"string"` - - // All of these tags must exist in the object's tag set in order for the rule - // to apply. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s LifecycleRuleAndOperator) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LifecycleRuleAndOperator) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRuleAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPrefix sets the Prefix field's value. -func (s *LifecycleRuleAndOperator) SetPrefix(v string) *LifecycleRuleAndOperator { - s.Prefix = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *LifecycleRuleAndOperator) SetTags(v []*Tag) *LifecycleRuleAndOperator { - s.Tags = v - return s -} - -// The Filter is used to identify objects that a Lifecycle Rule applies to. -// A Filter must have exactly one of Prefix, Tag, or And specified. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LifecycleRuleFilter -type LifecycleRuleFilter struct { - _ struct{} `type:"structure"` - - // This is used in a Lifecycle Rule Filter to apply a logical AND to two or - // more predicates. The Lifecycle Rule will apply to any object matching all - // of the predicates configured inside the And operator. - And *LifecycleRuleAndOperator `type:"structure"` - - // Prefix identifying one or more objects to which the rule applies. - Prefix *string `type:"string"` - - // This tag must exist in the object's tag set in order for the rule to apply. - Tag *Tag `type:"structure"` -} - -// String returns the string representation -func (s LifecycleRuleFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LifecycleRuleFilter) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LifecycleRuleFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LifecycleRuleFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } - } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnd sets the And field's value. -func (s *LifecycleRuleFilter) SetAnd(v *LifecycleRuleAndOperator) *LifecycleRuleFilter { - s.And = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *LifecycleRuleFilter) SetPrefix(v string) *LifecycleRuleFilter { - s.Prefix = &v - return s -} - -// SetTag sets the Tag field's value. -func (s *LifecycleRuleFilter) SetTag(v *Tag) *LifecycleRuleFilter { - s.Tag = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsRequest -type ListBucketAnalyticsConfigurationsInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket from which analytics configurations are retrieved. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ContinuationToken that represents a placeholder from where this request - // should begin. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` -} - -// String returns the string representation -func (s ListBucketAnalyticsConfigurationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketAnalyticsConfigurationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketAnalyticsConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketAnalyticsConfigurationsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListBucketAnalyticsConfigurationsInput) SetBucket(v string) *ListBucketAnalyticsConfigurationsInput { - s.Bucket = &v - return s -} - -func (s *ListBucketAnalyticsConfigurationsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsInput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsInput { - s.ContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketAnalyticsConfigurationsOutput -type ListBucketAnalyticsConfigurationsOutput struct { - _ struct{} `type:"structure"` - - // The list of analytics configurations for a bucket. - AnalyticsConfigurationList []*AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"list" flattened:"true"` - - // The ContinuationToken that represents where this request began. - ContinuationToken *string `type:"string"` - - // Indicates whether the returned list of analytics configurations is complete. - // A value of true indicates that the list is not complete and the NextContinuationToken - // will be provided for a subsequent request. - IsTruncated *bool `type:"boolean"` - - // NextContinuationToken is sent when isTruncated is true, which indicates that - // there are more analytics configurations to list. The next request must include - // this NextContinuationToken. The token is obfuscated and is not a usable value. - NextContinuationToken *string `type:"string"` -} - -// String returns the string representation -func (s ListBucketAnalyticsConfigurationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketAnalyticsConfigurationsOutput) GoString() string { - return s.String() -} - -// SetAnalyticsConfigurationList sets the AnalyticsConfigurationList field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetAnalyticsConfigurationList(v []*AnalyticsConfiguration) *ListBucketAnalyticsConfigurationsOutput { - s.AnalyticsConfigurationList = v - return s -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { - s.ContinuationToken = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketAnalyticsConfigurationsOutput { - s.IsTruncated = &v - return s -} - -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketAnalyticsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketAnalyticsConfigurationsOutput { - s.NextContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsRequest -type ListBucketInventoryConfigurationsInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the inventory configurations to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The marker used to continue an inventory configuration listing that has been - // truncated. Use the NextContinuationToken from a previously truncated list - // response to continue the listing. The continuation token is an opaque value - // that Amazon S3 understands. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` -} - -// String returns the string representation -func (s ListBucketInventoryConfigurationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketInventoryConfigurationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketInventoryConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketInventoryConfigurationsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListBucketInventoryConfigurationsInput) SetBucket(v string) *ListBucketInventoryConfigurationsInput { - s.Bucket = &v - return s -} - -func (s *ListBucketInventoryConfigurationsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsInput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsInput { - s.ContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketInventoryConfigurationsOutput -type ListBucketInventoryConfigurationsOutput struct { - _ struct{} `type:"structure"` - - // If sent in the request, the marker that is used as a starting point for this - // inventory configuration list response. - ContinuationToken *string `type:"string"` - - // The list of inventory configurations for a bucket. - InventoryConfigurationList []*InventoryConfiguration `locationName:"InventoryConfiguration" type:"list" flattened:"true"` - - // Indicates whether the returned list of inventory configurations is truncated - // in this response. A value of true indicates that the list is truncated. - IsTruncated *bool `type:"boolean"` - - // The marker used to continue this inventory configuration listing. Use the - // NextContinuationToken from this response to continue the listing in a subsequent - // request. The continuation token is an opaque value that Amazon S3 understands. - NextContinuationToken *string `type:"string"` -} - -// String returns the string representation -func (s ListBucketInventoryConfigurationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketInventoryConfigurationsOutput) GoString() string { - return s.String() -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { - s.ContinuationToken = &v - return s -} - -// SetInventoryConfigurationList sets the InventoryConfigurationList field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetInventoryConfigurationList(v []*InventoryConfiguration) *ListBucketInventoryConfigurationsOutput { - s.InventoryConfigurationList = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetIsTruncated(v bool) *ListBucketInventoryConfigurationsOutput { - s.IsTruncated = &v - return s -} - -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketInventoryConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketInventoryConfigurationsOutput { - s.NextContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsRequest -type ListBucketMetricsConfigurationsInput struct { - _ struct{} `type:"structure"` - - // The name of the bucket containing the metrics configurations to retrieve. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The marker that is used to continue a metrics configuration listing that - // has been truncated. Use the NextContinuationToken from a previously truncated - // list response to continue the listing. The continuation token is an opaque - // value that Amazon S3 understands. - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` -} - -// String returns the string representation -func (s ListBucketMetricsConfigurationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketMetricsConfigurationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListBucketMetricsConfigurationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListBucketMetricsConfigurationsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListBucketMetricsConfigurationsInput) SetBucket(v string) *ListBucketMetricsConfigurationsInput { - s.Bucket = &v - return s -} - -func (s *ListBucketMetricsConfigurationsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsInput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsInput { - s.ContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketMetricsConfigurationsOutput -type ListBucketMetricsConfigurationsOutput struct { - _ struct{} `type:"structure"` - - // The marker that is used as a starting point for this metrics configuration - // list response. This value is present if it was sent in the request. - ContinuationToken *string `type:"string"` - - // Indicates whether the returned list of metrics configurations is complete. - // A value of true indicates that the list is not complete and the NextContinuationToken - // will be provided for a subsequent request. - IsTruncated *bool `type:"boolean"` - - // The list of metrics configurations for a bucket. - MetricsConfigurationList []*MetricsConfiguration `locationName:"MetricsConfiguration" type:"list" flattened:"true"` - - // The marker used to continue a metrics configuration listing that has been - // truncated. Use the NextContinuationToken from a previously truncated list - // response to continue the listing. The continuation token is an opaque value - // that Amazon S3 understands. - NextContinuationToken *string `type:"string"` -} - -// String returns the string representation -func (s ListBucketMetricsConfigurationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketMetricsConfigurationsOutput) GoString() string { - return s.String() -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { - s.ContinuationToken = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetIsTruncated(v bool) *ListBucketMetricsConfigurationsOutput { - s.IsTruncated = &v - return s -} - -// SetMetricsConfigurationList sets the MetricsConfigurationList field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetMetricsConfigurationList(v []*MetricsConfiguration) *ListBucketMetricsConfigurationsOutput { - s.MetricsConfigurationList = v - return s -} - -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListBucketMetricsConfigurationsOutput) SetNextContinuationToken(v string) *ListBucketMetricsConfigurationsOutput { - s.NextContinuationToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsInput -type ListBucketsInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s ListBucketsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketsInput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListBucketsOutput -type ListBucketsOutput struct { - _ struct{} `type:"structure"` - - Buckets []*Bucket `locationNameList:"Bucket" type:"list"` - - Owner *Owner `type:"structure"` -} - -// String returns the string representation -func (s ListBucketsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListBucketsOutput) GoString() string { - return s.String() -} - -// SetBuckets sets the Buckets field's value. -func (s *ListBucketsOutput) SetBuckets(v []*Bucket) *ListBucketsOutput { - s.Buckets = v - return s -} - -// SetOwner sets the Owner field's value. -func (s *ListBucketsOutput) SetOwner(v *Owner) *ListBucketsOutput { - s.Owner = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsRequest -type ListMultipartUploadsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - - // Together with upload-id-marker, this parameter specifies the multipart upload - // after which listing should begin. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - - // Sets the maximum number of multipart uploads, from 1 to 1,000, to return - // in the response body. 1,000 is the maximum number of uploads that can be - // returned in a response. - MaxUploads *int64 `location:"querystring" locationName:"max-uploads" type:"integer"` - - // Lists in-progress uploads only for those keys that begin with the specified - // prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Together with key-marker, specifies the multipart upload after which listing - // should begin. If key-marker is not specified, the upload-id-marker parameter - // is ignored. - UploadIdMarker *string `location:"querystring" locationName:"upload-id-marker" type:"string"` -} - -// String returns the string representation -func (s ListMultipartUploadsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListMultipartUploadsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListMultipartUploadsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListMultipartUploadsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListMultipartUploadsInput) SetBucket(v string) *ListMultipartUploadsInput { - s.Bucket = &v - return s -} - -func (s *ListMultipartUploadsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListMultipartUploadsInput) SetDelimiter(v string) *ListMultipartUploadsInput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListMultipartUploadsInput) SetEncodingType(v string) *ListMultipartUploadsInput { - s.EncodingType = &v - return s -} - -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListMultipartUploadsInput) SetKeyMarker(v string) *ListMultipartUploadsInput { - s.KeyMarker = &v - return s -} - -// SetMaxUploads sets the MaxUploads field's value. -func (s *ListMultipartUploadsInput) SetMaxUploads(v int64) *ListMultipartUploadsInput { - s.MaxUploads = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListMultipartUploadsInput) SetPrefix(v string) *ListMultipartUploadsInput { - s.Prefix = &v - return s -} - -// SetUploadIdMarker sets the UploadIdMarker field's value. -func (s *ListMultipartUploadsInput) SetUploadIdMarker(v string) *ListMultipartUploadsInput { - s.UploadIdMarker = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListMultipartUploadsOutput -type ListMultipartUploadsOutput struct { - _ struct{} `type:"structure"` - - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` - - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` - - // Indicates whether the returned list of multipart uploads is truncated. A - // value of true indicates that the list was truncated. The list can be truncated - // if the number of multipart uploads exceeds the limit allowed or specified - // by max uploads. - IsTruncated *bool `type:"boolean"` - - // The key at or after which the listing began. - KeyMarker *string `type:"string"` - - // Maximum number of multipart uploads that could have been included in the - // response. - MaxUploads *int64 `type:"integer"` - - // When a list is truncated, this element specifies the value that should be - // used for the key-marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` - - // When a list is truncated, this element specifies the value that should be - // used for the upload-id-marker request parameter in a subsequent request. - NextUploadIdMarker *string `type:"string"` - - // When a prefix is provided in the request, this field contains the specified - // prefix. The result contains only keys starting with the specified prefix. - Prefix *string `type:"string"` - - // Upload ID after which listing began. - UploadIdMarker *string `type:"string"` - - Uploads []*MultipartUpload `locationName:"Upload" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s ListMultipartUploadsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListMultipartUploadsOutput) GoString() string { - return s.String() -} - -// SetBucket sets the Bucket field's value. -func (s *ListMultipartUploadsOutput) SetBucket(v string) *ListMultipartUploadsOutput { - s.Bucket = &v - return s -} - -func (s *ListMultipartUploadsOutput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListMultipartUploadsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListMultipartUploadsOutput { - s.CommonPrefixes = v - return s -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListMultipartUploadsOutput) SetDelimiter(v string) *ListMultipartUploadsOutput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListMultipartUploadsOutput) SetEncodingType(v string) *ListMultipartUploadsOutput { - s.EncodingType = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListMultipartUploadsOutput) SetIsTruncated(v bool) *ListMultipartUploadsOutput { - s.IsTruncated = &v - return s -} - -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListMultipartUploadsOutput) SetKeyMarker(v string) *ListMultipartUploadsOutput { - s.KeyMarker = &v - return s -} - -// SetMaxUploads sets the MaxUploads field's value. -func (s *ListMultipartUploadsOutput) SetMaxUploads(v int64) *ListMultipartUploadsOutput { - s.MaxUploads = &v - return s -} - -// SetNextKeyMarker sets the NextKeyMarker field's value. -func (s *ListMultipartUploadsOutput) SetNextKeyMarker(v string) *ListMultipartUploadsOutput { - s.NextKeyMarker = &v - return s -} - -// SetNextUploadIdMarker sets the NextUploadIdMarker field's value. -func (s *ListMultipartUploadsOutput) SetNextUploadIdMarker(v string) *ListMultipartUploadsOutput { - s.NextUploadIdMarker = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListMultipartUploadsOutput) SetPrefix(v string) *ListMultipartUploadsOutput { - s.Prefix = &v - return s -} - -// SetUploadIdMarker sets the UploadIdMarker field's value. -func (s *ListMultipartUploadsOutput) SetUploadIdMarker(v string) *ListMultipartUploadsOutput { - s.UploadIdMarker = &v - return s -} - -// SetUploads sets the Uploads field's value. -func (s *ListMultipartUploadsOutput) SetUploads(v []*MultipartUpload) *ListMultipartUploadsOutput { - s.Uploads = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsRequest -type ListObjectVersionsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - - // Specifies the key to start with when listing objects in a bucket. - KeyMarker *string `location:"querystring" locationName:"key-marker" type:"string"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Specifies the object version you want to start listing from. - VersionIdMarker *string `location:"querystring" locationName:"version-id-marker" type:"string"` -} - -// String returns the string representation -func (s ListObjectVersionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectVersionsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectVersionsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListObjectVersionsInput) SetBucket(v string) *ListObjectVersionsInput { - s.Bucket = &v - return s -} - -func (s *ListObjectVersionsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectVersionsInput) SetDelimiter(v string) *ListObjectVersionsInput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectVersionsInput) SetEncodingType(v string) *ListObjectVersionsInput { - s.EncodingType = &v - return s -} - -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListObjectVersionsInput) SetKeyMarker(v string) *ListObjectVersionsInput { - s.KeyMarker = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectVersionsInput) SetMaxKeys(v int64) *ListObjectVersionsInput { - s.MaxKeys = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectVersionsInput) SetPrefix(v string) *ListObjectVersionsInput { - s.Prefix = &v - return s -} - -// SetVersionIdMarker sets the VersionIdMarker field's value. -func (s *ListObjectVersionsInput) SetVersionIdMarker(v string) *ListObjectVersionsInput { - s.VersionIdMarker = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectVersionsOutput -type ListObjectVersionsOutput struct { - _ struct{} `type:"structure"` - - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - DeleteMarkers []*DeleteMarkerEntry `locationName:"DeleteMarker" type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` - - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. If your results were truncated, you can - // make a follow-up paginated request using the NextKeyMarker and NextVersionIdMarker - // response parameters as a starting place in another request to return the - // rest of the results. - IsTruncated *bool `type:"boolean"` - - // Marks the last Key returned in a truncated response. - KeyMarker *string `type:"string"` - - MaxKeys *int64 `type:"integer"` - - Name *string `type:"string"` - - // Use this value for the key marker request parameter in a subsequent request. - NextKeyMarker *string `type:"string"` - - // Use this value for the next version id marker parameter in a subsequent request. - NextVersionIdMarker *string `type:"string"` - - Prefix *string `type:"string"` - - VersionIdMarker *string `type:"string"` - - Versions []*ObjectVersion `locationName:"Version" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s ListObjectVersionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectVersionsOutput) GoString() string { - return s.String() -} - -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectVersionsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectVersionsOutput { - s.CommonPrefixes = v - return s -} - -// SetDeleteMarkers sets the DeleteMarkers field's value. -func (s *ListObjectVersionsOutput) SetDeleteMarkers(v []*DeleteMarkerEntry) *ListObjectVersionsOutput { - s.DeleteMarkers = v - return s -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectVersionsOutput) SetDelimiter(v string) *ListObjectVersionsOutput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectVersionsOutput) SetEncodingType(v string) *ListObjectVersionsOutput { - s.EncodingType = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectVersionsOutput) SetIsTruncated(v bool) *ListObjectVersionsOutput { - s.IsTruncated = &v - return s -} - -// SetKeyMarker sets the KeyMarker field's value. -func (s *ListObjectVersionsOutput) SetKeyMarker(v string) *ListObjectVersionsOutput { - s.KeyMarker = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectVersionsOutput) SetMaxKeys(v int64) *ListObjectVersionsOutput { - s.MaxKeys = &v - return s -} - -// SetName sets the Name field's value. -func (s *ListObjectVersionsOutput) SetName(v string) *ListObjectVersionsOutput { - s.Name = &v - return s -} - -// SetNextKeyMarker sets the NextKeyMarker field's value. -func (s *ListObjectVersionsOutput) SetNextKeyMarker(v string) *ListObjectVersionsOutput { - s.NextKeyMarker = &v - return s -} - -// SetNextVersionIdMarker sets the NextVersionIdMarker field's value. -func (s *ListObjectVersionsOutput) SetNextVersionIdMarker(v string) *ListObjectVersionsOutput { - s.NextVersionIdMarker = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectVersionsOutput) SetPrefix(v string) *ListObjectVersionsOutput { - s.Prefix = &v - return s -} - -// SetVersionIdMarker sets the VersionIdMarker field's value. -func (s *ListObjectVersionsOutput) SetVersionIdMarker(v string) *ListObjectVersionsOutput { - s.VersionIdMarker = &v - return s -} - -// SetVersions sets the Versions field's value. -func (s *ListObjectVersionsOutput) SetVersions(v []*ObjectVersion) *ListObjectVersionsOutput { - s.Versions = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsRequest -type ListObjectsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Requests Amazon S3 to encode the object keys in the response and specifies - // the encoding method to use. An object key may contain any Unicode character; - // however, XML 1.0 parser cannot parse some characters, such as characters - // with an ASCII value from 0 to 10. For characters that are not supported in - // XML 1.0, you can add this parameter to request that Amazon S3 encode the - // keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - - // Specifies the key to start with when listing objects in a bucket. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // list objects request. Bucket owners need not specify this parameter in their - // requests. - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` -} - -// String returns the string representation -func (s ListObjectsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListObjectsInput) SetBucket(v string) *ListObjectsInput { - s.Bucket = &v - return s -} - -func (s *ListObjectsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsInput) SetDelimiter(v string) *ListObjectsInput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsInput) SetEncodingType(v string) *ListObjectsInput { - s.EncodingType = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListObjectsInput) SetMarker(v string) *ListObjectsInput { - s.Marker = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsInput) SetMaxKeys(v int64) *ListObjectsInput { - s.MaxKeys = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsInput) SetPrefix(v string) *ListObjectsInput { - s.Prefix = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListObjectsInput) SetRequestPayer(v string) *ListObjectsInput { - s.RequestPayer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsOutput -type ListObjectsOutput struct { - _ struct{} `type:"structure"` - - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - Contents []*Object `type:"list" flattened:"true"` - - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` - - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. - IsTruncated *bool `type:"boolean"` - - Marker *string `type:"string"` - - MaxKeys *int64 `type:"integer"` - - Name *string `type:"string"` - - // When response is truncated (the IsTruncated element value in the response - // is true), you can use the key name in this field as marker in the subsequent - // request to get next set of objects. Amazon S3 lists objects in alphabetical - // order Note: This element is returned only if you have delimiter request parameter - // specified. If response does not include the NextMaker and it is truncated, - // you can use the value of the last Key in the response as the marker in the - // subsequent request to get the next set of object keys. - NextMarker *string `type:"string"` - - Prefix *string `type:"string"` -} - -// String returns the string representation -func (s ListObjectsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectsOutput) GoString() string { - return s.String() -} - -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectsOutput) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsOutput { - s.CommonPrefixes = v - return s -} - -// SetContents sets the Contents field's value. -func (s *ListObjectsOutput) SetContents(v []*Object) *ListObjectsOutput { - s.Contents = v - return s -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsOutput) SetDelimiter(v string) *ListObjectsOutput { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsOutput) SetEncodingType(v string) *ListObjectsOutput { - s.EncodingType = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectsOutput) SetIsTruncated(v bool) *ListObjectsOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListObjectsOutput) SetMarker(v string) *ListObjectsOutput { - s.Marker = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsOutput) SetMaxKeys(v int64) *ListObjectsOutput { - s.MaxKeys = &v - return s -} - -// SetName sets the Name field's value. -func (s *ListObjectsOutput) SetName(v string) *ListObjectsOutput { - s.Name = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListObjectsOutput) SetNextMarker(v string) *ListObjectsOutput { - s.NextMarker = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsOutput) SetPrefix(v string) *ListObjectsOutput { - s.Prefix = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Request -type ListObjectsV2Input struct { - _ struct{} `type:"structure"` - - // Name of the bucket to list. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // ContinuationToken indicates Amazon S3 that the list is being continued on - // this bucket with a token. ContinuationToken is obfuscated and is not a real - // key - ContinuationToken *string `location:"querystring" locationName:"continuation-token" type:"string"` - - // A delimiter is a character you use to group keys. - Delimiter *string `location:"querystring" locationName:"delimiter" type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `location:"querystring" locationName:"encoding-type" type:"string" enum:"EncodingType"` - - // The owner field is not present in listV2 by default, if you want to return - // owner field with each key in the result then set the fetch owner field to - // true - FetchOwner *bool `location:"querystring" locationName:"fetch-owner" type:"boolean"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `location:"querystring" locationName:"max-keys" type:"integer"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `location:"querystring" locationName:"prefix" type:"string"` - - // Confirms that the requester knows that she or he will be charged for the - // list objects request in V2 style. Bucket owners need not specify this parameter - // in their requests. - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts - // listing after this specified key. StartAfter can be any key in the bucket - StartAfter *string `location:"querystring" locationName:"start-after" type:"string"` -} - -// String returns the string representation -func (s ListObjectsV2Input) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectsV2Input) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListObjectsV2Input) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListObjectsV2Input"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListObjectsV2Input) SetBucket(v string) *ListObjectsV2Input { - s.Bucket = &v - return s -} - -func (s *ListObjectsV2Input) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListObjectsV2Input) SetContinuationToken(v string) *ListObjectsV2Input { - s.ContinuationToken = &v - return s -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsV2Input) SetDelimiter(v string) *ListObjectsV2Input { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsV2Input) SetEncodingType(v string) *ListObjectsV2Input { - s.EncodingType = &v - return s -} - -// SetFetchOwner sets the FetchOwner field's value. -func (s *ListObjectsV2Input) SetFetchOwner(v bool) *ListObjectsV2Input { - s.FetchOwner = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsV2Input) SetMaxKeys(v int64) *ListObjectsV2Input { - s.MaxKeys = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsV2Input) SetPrefix(v string) *ListObjectsV2Input { - s.Prefix = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListObjectsV2Input) SetRequestPayer(v string) *ListObjectsV2Input { - s.RequestPayer = &v - return s -} - -// SetStartAfter sets the StartAfter field's value. -func (s *ListObjectsV2Input) SetStartAfter(v string) *ListObjectsV2Input { - s.StartAfter = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListObjectsV2Output -type ListObjectsV2Output struct { - _ struct{} `type:"structure"` - - // CommonPrefixes contains all (if there are any) keys between Prefix and the - // next occurrence of the string specified by delimiter - CommonPrefixes []*CommonPrefix `type:"list" flattened:"true"` - - // Metadata about each object returned. - Contents []*Object `type:"list" flattened:"true"` - - // ContinuationToken indicates Amazon S3 that the list is being continued on - // this bucket with a token. ContinuationToken is obfuscated and is not a real - // key - ContinuationToken *string `type:"string"` - - // A delimiter is a character you use to group keys. - Delimiter *string `type:"string"` - - // Encoding type used by Amazon S3 to encode object keys in the response. - EncodingType *string `type:"string" enum:"EncodingType"` - - // A flag that indicates whether or not Amazon S3 returned all of the results - // that satisfied the search criteria. - IsTruncated *bool `type:"boolean"` - - // KeyCount is the number of keys returned with this request. KeyCount will - // always be less than equals to MaxKeys field. Say you ask for 50 keys, your - // result will include less than equals 50 keys - KeyCount *int64 `type:"integer"` - - // Sets the maximum number of keys returned in the response. The response might - // contain fewer keys but will never contain more. - MaxKeys *int64 `type:"integer"` - - // Name of the bucket to list. - Name *string `type:"string"` - - // NextContinuationToken is sent when isTruncated is true which means there - // are more keys in the bucket that can be listed. The next list requests to - // Amazon S3 can be continued with this NextContinuationToken. NextContinuationToken - // is obfuscated and is not a real key - NextContinuationToken *string `type:"string"` - - // Limits the response to keys that begin with the specified prefix. - Prefix *string `type:"string"` - - // StartAfter is where you want Amazon S3 to start listing from. Amazon S3 starts - // listing after this specified key. StartAfter can be any key in the bucket - StartAfter *string `type:"string"` -} - -// String returns the string representation -func (s ListObjectsV2Output) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListObjectsV2Output) GoString() string { - return s.String() -} - -// SetCommonPrefixes sets the CommonPrefixes field's value. -func (s *ListObjectsV2Output) SetCommonPrefixes(v []*CommonPrefix) *ListObjectsV2Output { - s.CommonPrefixes = v - return s -} - -// SetContents sets the Contents field's value. -func (s *ListObjectsV2Output) SetContents(v []*Object) *ListObjectsV2Output { - s.Contents = v - return s -} - -// SetContinuationToken sets the ContinuationToken field's value. -func (s *ListObjectsV2Output) SetContinuationToken(v string) *ListObjectsV2Output { - s.ContinuationToken = &v - return s -} - -// SetDelimiter sets the Delimiter field's value. -func (s *ListObjectsV2Output) SetDelimiter(v string) *ListObjectsV2Output { - s.Delimiter = &v - return s -} - -// SetEncodingType sets the EncodingType field's value. -func (s *ListObjectsV2Output) SetEncodingType(v string) *ListObjectsV2Output { - s.EncodingType = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListObjectsV2Output) SetIsTruncated(v bool) *ListObjectsV2Output { - s.IsTruncated = &v - return s -} - -// SetKeyCount sets the KeyCount field's value. -func (s *ListObjectsV2Output) SetKeyCount(v int64) *ListObjectsV2Output { - s.KeyCount = &v - return s -} - -// SetMaxKeys sets the MaxKeys field's value. -func (s *ListObjectsV2Output) SetMaxKeys(v int64) *ListObjectsV2Output { - s.MaxKeys = &v - return s -} - -// SetName sets the Name field's value. -func (s *ListObjectsV2Output) SetName(v string) *ListObjectsV2Output { - s.Name = &v - return s -} - -// SetNextContinuationToken sets the NextContinuationToken field's value. -func (s *ListObjectsV2Output) SetNextContinuationToken(v string) *ListObjectsV2Output { - s.NextContinuationToken = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ListObjectsV2Output) SetPrefix(v string) *ListObjectsV2Output { - s.Prefix = &v - return s -} - -// SetStartAfter sets the StartAfter field's value. -func (s *ListObjectsV2Output) SetStartAfter(v string) *ListObjectsV2Output { - s.StartAfter = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsRequest -type ListPartsInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Sets the maximum number of parts to return. - MaxParts *int64 `location:"querystring" locationName:"max-parts" type:"integer"` - - // Specifies the part after which listing should begin. Only parts with higher - // part numbers will be listed. - PartNumberMarker *int64 `location:"querystring" locationName:"part-number-marker" type:"integer"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Upload ID identifying the multipart upload whose parts are being listed. - // - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` -} - -// String returns the string representation -func (s ListPartsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListPartsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListPartsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListPartsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *ListPartsInput) SetBucket(v string) *ListPartsInput { - s.Bucket = &v - return s -} - -func (s *ListPartsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *ListPartsInput) SetKey(v string) *ListPartsInput { - s.Key = &v - return s -} - -// SetMaxParts sets the MaxParts field's value. -func (s *ListPartsInput) SetMaxParts(v int64) *ListPartsInput { - s.MaxParts = &v - return s -} - -// SetPartNumberMarker sets the PartNumberMarker field's value. -func (s *ListPartsInput) SetPartNumberMarker(v int64) *ListPartsInput { - s.PartNumberMarker = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *ListPartsInput) SetRequestPayer(v string) *ListPartsInput { - s.RequestPayer = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *ListPartsInput) SetUploadId(v string) *ListPartsInput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ListPartsOutput -type ListPartsOutput struct { - _ struct{} `type:"structure"` - - // Date when multipart upload will become eligible for abort operation by lifecycle. - AbortDate *time.Time `location:"header" locationName:"x-amz-abort-date" type:"timestamp" timestampFormat:"rfc822"` - - // Id of the lifecycle rule that makes a multipart upload eligible for abort - // operation. - AbortRuleId *string `location:"header" locationName:"x-amz-abort-rule-id" type:"string"` - - // Name of the bucket to which the multipart upload was initiated. - Bucket *string `type:"string"` - - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` - - // Indicates whether the returned list of parts is truncated. - IsTruncated *bool `type:"boolean"` - - // Object key for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` - - // Maximum number of parts that were allowed in the response. - MaxParts *int64 `type:"integer"` - - // When a list is truncated, this element specifies the last part in the list, - // as well as the value to use for the part-number-marker request parameter - // in a subsequent request. - NextPartNumberMarker *int64 `type:"integer"` - - Owner *Owner `type:"structure"` - - // Part number after which listing begins. - PartNumberMarker *int64 `type:"integer"` - - Parts []*Part `locationName:"Part" type:"list" flattened:"true"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` - - // Upload ID identifying the multipart upload whose parts are being listed. - UploadId *string `type:"string"` -} - -// String returns the string representation -func (s ListPartsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListPartsOutput) GoString() string { - return s.String() -} - -// SetAbortDate sets the AbortDate field's value. -func (s *ListPartsOutput) SetAbortDate(v time.Time) *ListPartsOutput { - s.AbortDate = &v - return s -} - -// SetAbortRuleId sets the AbortRuleId field's value. -func (s *ListPartsOutput) SetAbortRuleId(v string) *ListPartsOutput { - s.AbortRuleId = &v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *ListPartsOutput) SetBucket(v string) *ListPartsOutput { - s.Bucket = &v - return s -} - -func (s *ListPartsOutput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetInitiator sets the Initiator field's value. -func (s *ListPartsOutput) SetInitiator(v *Initiator) *ListPartsOutput { - s.Initiator = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListPartsOutput) SetIsTruncated(v bool) *ListPartsOutput { - s.IsTruncated = &v - return s -} - -// SetKey sets the Key field's value. -func (s *ListPartsOutput) SetKey(v string) *ListPartsOutput { - s.Key = &v - return s -} - -// SetMaxParts sets the MaxParts field's value. -func (s *ListPartsOutput) SetMaxParts(v int64) *ListPartsOutput { - s.MaxParts = &v - return s -} - -// SetNextPartNumberMarker sets the NextPartNumberMarker field's value. -func (s *ListPartsOutput) SetNextPartNumberMarker(v int64) *ListPartsOutput { - s.NextPartNumberMarker = &v - return s -} - -// SetOwner sets the Owner field's value. -func (s *ListPartsOutput) SetOwner(v *Owner) *ListPartsOutput { - s.Owner = v - return s -} - -// SetPartNumberMarker sets the PartNumberMarker field's value. -func (s *ListPartsOutput) SetPartNumberMarker(v int64) *ListPartsOutput { - s.PartNumberMarker = &v - return s -} - -// SetParts sets the Parts field's value. -func (s *ListPartsOutput) SetParts(v []*Part) *ListPartsOutput { - s.Parts = v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *ListPartsOutput) SetRequestCharged(v string) *ListPartsOutput { - s.RequestCharged = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *ListPartsOutput) SetStorageClass(v string) *ListPartsOutput { - s.StorageClass = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *ListPartsOutput) SetUploadId(v string) *ListPartsOutput { - s.UploadId = &v - return s -} - -// Describes an S3 location that will receive the results of the restore request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/S3Location -type Location struct { - _ struct{} `type:"structure"` - - // A list of grants that control access to the staged results. - AccessControlList []*Grant `locationNameList:"Grant" type:"list"` - - // The name of the bucket where the restore results will be placed. - // - // BucketName is a required field - BucketName *string `type:"string" required:"true"` - - // The canned ACL to apply to the restore results. - CannedACL *string `type:"string" enum:"ObjectCannedACL"` - - // Describes the server-side encryption that will be applied to the restore - // results. - Encryption *Encryption `type:"structure"` - - // The prefix that is prepended to the restore results for this request. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` - - // The class of storage used to store the restore results. - StorageClass *string `type:"string" enum:"StorageClass"` - - // The tag-set that is applied to the restore results. - Tagging *Tagging `type:"structure"` - - // A list of metadata to store with the restore results in S3. - UserMetadata []*MetadataEntry `locationNameList:"MetadataEntry" type:"list"` -} - -// String returns the string representation -func (s Location) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Location) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Location) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Location"} - if s.BucketName == nil { - invalidParams.Add(request.NewErrParamRequired("BucketName")) - } - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } - if s.AccessControlList != nil { - for i, v := range s.AccessControlList { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "AccessControlList", i), err.(request.ErrInvalidParams)) - } - } - } - if s.Encryption != nil { - if err := s.Encryption.Validate(); err != nil { - invalidParams.AddNested("Encryption", err.(request.ErrInvalidParams)) - } - } - if s.Tagging != nil { - if err := s.Tagging.Validate(); err != nil { - invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccessControlList sets the AccessControlList field's value. -func (s *Location) SetAccessControlList(v []*Grant) *Location { - s.AccessControlList = v - return s -} - -// SetBucketName sets the BucketName field's value. -func (s *Location) SetBucketName(v string) *Location { - s.BucketName = &v - return s -} - -// SetCannedACL sets the CannedACL field's value. -func (s *Location) SetCannedACL(v string) *Location { - s.CannedACL = &v - return s -} - -// SetEncryption sets the Encryption field's value. -func (s *Location) SetEncryption(v *Encryption) *Location { - s.Encryption = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *Location) SetPrefix(v string) *Location { - s.Prefix = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *Location) SetStorageClass(v string) *Location { - s.StorageClass = &v - return s -} - -// SetTagging sets the Tagging field's value. -func (s *Location) SetTagging(v *Tagging) *Location { - s.Tagging = v - return s -} - -// SetUserMetadata sets the UserMetadata field's value. -func (s *Location) SetUserMetadata(v []*MetadataEntry) *Location { - s.UserMetadata = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/LoggingEnabled -type LoggingEnabled struct { - _ struct{} `type:"structure"` - - // Specifies the bucket where you want Amazon S3 to store server access logs. - // You can have your logs delivered to any bucket that you own, including the - // same bucket that is being logged. You can also configure multiple buckets - // to deliver their logs to the same target bucket. In this case you should - // choose a different TargetPrefix for each source bucket so that the delivered - // log files can be distinguished by key. - TargetBucket *string `type:"string"` - - TargetGrants []*TargetGrant `locationNameList:"Grant" type:"list"` - - // This element lets you specify a prefix for the keys that the log files will - // be stored under. - TargetPrefix *string `type:"string"` -} - -// String returns the string representation -func (s LoggingEnabled) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoggingEnabled) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *LoggingEnabled) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "LoggingEnabled"} - if s.TargetGrants != nil { - for i, v := range s.TargetGrants { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TargetGrants", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetTargetBucket sets the TargetBucket field's value. -func (s *LoggingEnabled) SetTargetBucket(v string) *LoggingEnabled { - s.TargetBucket = &v - return s -} - -// SetTargetGrants sets the TargetGrants field's value. -func (s *LoggingEnabled) SetTargetGrants(v []*TargetGrant) *LoggingEnabled { - s.TargetGrants = v - return s -} - -// SetTargetPrefix sets the TargetPrefix field's value. -func (s *LoggingEnabled) SetTargetPrefix(v string) *LoggingEnabled { - s.TargetPrefix = &v - return s -} - -// A metadata key-value pair to store with an object. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetadataEntry -type MetadataEntry struct { - _ struct{} `type:"structure"` - - Name *string `type:"string"` - - Value *string `type:"string"` -} - -// String returns the string representation -func (s MetadataEntry) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetadataEntry) GoString() string { - return s.String() -} - -// SetName sets the Name field's value. -func (s *MetadataEntry) SetName(v string) *MetadataEntry { - s.Name = &v - return s -} - -// SetValue sets the Value field's value. -func (s *MetadataEntry) SetValue(v string) *MetadataEntry { - s.Value = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsAndOperator -type MetricsAndOperator struct { - _ struct{} `type:"structure"` - - // The prefix used when evaluating an AND predicate. - Prefix *string `type:"string"` - - // The list of tags used when evaluating an AND predicate. - Tags []*Tag `locationName:"Tag" locationNameList:"Tag" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s MetricsAndOperator) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetricsAndOperator) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsAndOperator) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsAndOperator"} - if s.Tags != nil { - for i, v := range s.Tags { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Tags", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPrefix sets the Prefix field's value. -func (s *MetricsAndOperator) SetPrefix(v string) *MetricsAndOperator { - s.Prefix = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *MetricsAndOperator) SetTags(v []*Tag) *MetricsAndOperator { - s.Tags = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsConfiguration -type MetricsConfiguration struct { - _ struct{} `type:"structure"` - - // Specifies a metrics configuration filter. The metrics configuration will - // only include objects that meet the filter's criteria. A filter must be a - // prefix, a tag, or a conjunction (MetricsAndOperator). - Filter *MetricsFilter `type:"structure"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s MetricsConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetricsConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsConfiguration"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Filter != nil { - if err := s.Filter.Validate(); err != nil { - invalidParams.AddNested("Filter", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetFilter sets the Filter field's value. -func (s *MetricsConfiguration) SetFilter(v *MetricsFilter) *MetricsConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *MetricsConfiguration) SetId(v string) *MetricsConfiguration { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MetricsFilter -type MetricsFilter struct { - _ struct{} `type:"structure"` - - // A conjunction (logical AND) of predicates, which is used in evaluating a - // metrics filter. The operator must have at least two predicates, and an object - // must match all of the predicates in order for the filter to apply. - And *MetricsAndOperator `type:"structure"` - - // The prefix used when evaluating a metrics filter. - Prefix *string `type:"string"` - - // The tag used when evaluating a metrics filter. - Tag *Tag `type:"structure"` -} - -// String returns the string representation -func (s MetricsFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetricsFilter) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *MetricsFilter) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "MetricsFilter"} - if s.And != nil { - if err := s.And.Validate(); err != nil { - invalidParams.AddNested("And", err.(request.ErrInvalidParams)) - } - } - if s.Tag != nil { - if err := s.Tag.Validate(); err != nil { - invalidParams.AddNested("Tag", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnd sets the And field's value. -func (s *MetricsFilter) SetAnd(v *MetricsAndOperator) *MetricsFilter { - s.And = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *MetricsFilter) SetPrefix(v string) *MetricsFilter { - s.Prefix = &v - return s -} - -// SetTag sets the Tag field's value. -func (s *MetricsFilter) SetTag(v *Tag) *MetricsFilter { - s.Tag = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/MultipartUpload -type MultipartUpload struct { - _ struct{} `type:"structure"` - - // Date and time at which the multipart upload was initiated. - Initiated *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Identifies who initiated the multipart upload. - Initiator *Initiator `type:"structure"` - - // Key of the object for which the multipart upload was initiated. - Key *string `min:"1" type:"string"` - - Owner *Owner `type:"structure"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"StorageClass"` - - // Upload ID that identifies the multipart upload. - UploadId *string `type:"string"` -} - -// String returns the string representation -func (s MultipartUpload) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MultipartUpload) GoString() string { - return s.String() -} - -// SetInitiated sets the Initiated field's value. -func (s *MultipartUpload) SetInitiated(v time.Time) *MultipartUpload { - s.Initiated = &v - return s -} - -// SetInitiator sets the Initiator field's value. -func (s *MultipartUpload) SetInitiator(v *Initiator) *MultipartUpload { - s.Initiator = v - return s -} - -// SetKey sets the Key field's value. -func (s *MultipartUpload) SetKey(v string) *MultipartUpload { - s.Key = &v - return s -} - -// SetOwner sets the Owner field's value. -func (s *MultipartUpload) SetOwner(v *Owner) *MultipartUpload { - s.Owner = v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *MultipartUpload) SetStorageClass(v string) *MultipartUpload { - s.StorageClass = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *MultipartUpload) SetUploadId(v string) *MultipartUpload { - s.UploadId = &v - return s -} - -// Specifies when noncurrent object versions expire. Upon expiration, Amazon -// S3 permanently deletes the noncurrent object versions. You set this lifecycle -// configuration action on a bucket that has versioning enabled (or suspended) -// to request that Amazon S3 delete noncurrent object versions at a specific -// period in the object's lifetime. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionExpiration -type NoncurrentVersionExpiration struct { - _ struct{} `type:"structure"` - - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) - NoncurrentDays *int64 `type:"integer"` -} - -// String returns the string representation -func (s NoncurrentVersionExpiration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s NoncurrentVersionExpiration) GoString() string { - return s.String() -} - -// SetNoncurrentDays sets the NoncurrentDays field's value. -func (s *NoncurrentVersionExpiration) SetNoncurrentDays(v int64) *NoncurrentVersionExpiration { - s.NoncurrentDays = &v - return s -} - -// Container for the transition rule that describes when noncurrent objects -// transition to the STANDARD_IA or GLACIER storage class. If your bucket is -// versioning-enabled (or versioning is suspended), you can set this action -// to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA -// or GLACIER storage class at a specific period in the object's lifetime. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NoncurrentVersionTransition -type NoncurrentVersionTransition struct { - _ struct{} `type:"structure"` - - // Specifies the number of days an object is noncurrent before Amazon S3 can - // perform the associated action. For information about the noncurrent days - // calculations, see How Amazon S3 Calculates When an Object Became Noncurrent - // (http://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) - NoncurrentDays *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"TransitionStorageClass"` -} - -// String returns the string representation -func (s NoncurrentVersionTransition) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s NoncurrentVersionTransition) GoString() string { - return s.String() -} - -// SetNoncurrentDays sets the NoncurrentDays field's value. -func (s *NoncurrentVersionTransition) SetNoncurrentDays(v int64) *NoncurrentVersionTransition { - s.NoncurrentDays = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *NoncurrentVersionTransition) SetStorageClass(v string) *NoncurrentVersionTransition { - s.StorageClass = &v - return s -} - -// Container for specifying the notification configuration of the bucket. If -// this element is empty, notifications are turned off on the bucket. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfiguration -type NotificationConfiguration struct { - _ struct{} `type:"structure"` - - LambdaFunctionConfigurations []*LambdaFunctionConfiguration `locationName:"CloudFunctionConfiguration" type:"list" flattened:"true"` - - QueueConfigurations []*QueueConfiguration `locationName:"QueueConfiguration" type:"list" flattened:"true"` - - TopicConfigurations []*TopicConfiguration `locationName:"TopicConfiguration" type:"list" flattened:"true"` -} - -// String returns the string representation -func (s NotificationConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s NotificationConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *NotificationConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "NotificationConfiguration"} - if s.LambdaFunctionConfigurations != nil { - for i, v := range s.LambdaFunctionConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "LambdaFunctionConfigurations", i), err.(request.ErrInvalidParams)) - } - } - } - if s.QueueConfigurations != nil { - for i, v := range s.QueueConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "QueueConfigurations", i), err.(request.ErrInvalidParams)) - } - } - } - if s.TopicConfigurations != nil { - for i, v := range s.TopicConfigurations { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TopicConfigurations", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLambdaFunctionConfigurations sets the LambdaFunctionConfigurations field's value. -func (s *NotificationConfiguration) SetLambdaFunctionConfigurations(v []*LambdaFunctionConfiguration) *NotificationConfiguration { - s.LambdaFunctionConfigurations = v - return s -} - -// SetQueueConfigurations sets the QueueConfigurations field's value. -func (s *NotificationConfiguration) SetQueueConfigurations(v []*QueueConfiguration) *NotificationConfiguration { - s.QueueConfigurations = v - return s -} - -// SetTopicConfigurations sets the TopicConfigurations field's value. -func (s *NotificationConfiguration) SetTopicConfigurations(v []*TopicConfiguration) *NotificationConfiguration { - s.TopicConfigurations = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationDeprecated -type NotificationConfigurationDeprecated struct { - _ struct{} `type:"structure"` - - CloudFunctionConfiguration *CloudFunctionConfiguration `type:"structure"` - - QueueConfiguration *QueueConfigurationDeprecated `type:"structure"` - - TopicConfiguration *TopicConfigurationDeprecated `type:"structure"` -} - -// String returns the string representation -func (s NotificationConfigurationDeprecated) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s NotificationConfigurationDeprecated) GoString() string { - return s.String() -} - -// SetCloudFunctionConfiguration sets the CloudFunctionConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetCloudFunctionConfiguration(v *CloudFunctionConfiguration) *NotificationConfigurationDeprecated { - s.CloudFunctionConfiguration = v - return s -} - -// SetQueueConfiguration sets the QueueConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetQueueConfiguration(v *QueueConfigurationDeprecated) *NotificationConfigurationDeprecated { - s.QueueConfiguration = v - return s -} - -// SetTopicConfiguration sets the TopicConfiguration field's value. -func (s *NotificationConfigurationDeprecated) SetTopicConfiguration(v *TopicConfigurationDeprecated) *NotificationConfigurationDeprecated { - s.TopicConfiguration = v - return s -} - -// Container for object key name filtering rules. For information about key -// name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/NotificationConfigurationFilter -type NotificationConfigurationFilter struct { - _ struct{} `type:"structure"` - - // Container for object key name prefix and suffix filtering rules. - Key *KeyFilter `locationName:"S3Key" type:"structure"` -} - -// String returns the string representation -func (s NotificationConfigurationFilter) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s NotificationConfigurationFilter) GoString() string { - return s.String() -} - -// SetKey sets the Key field's value. -func (s *NotificationConfigurationFilter) SetKey(v *KeyFilter) *NotificationConfigurationFilter { - s.Key = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Object -type Object struct { - _ struct{} `type:"structure"` - - ETag *string `type:"string"` - - Key *string `min:"1" type:"string"` - - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - Size *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"ObjectStorageClass"` -} - -// String returns the string representation -func (s Object) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Object) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *Object) SetETag(v string) *Object { - s.ETag = &v - return s -} - -// SetKey sets the Key field's value. -func (s *Object) SetKey(v string) *Object { - s.Key = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *Object) SetLastModified(v time.Time) *Object { - s.LastModified = &v - return s -} - -// SetOwner sets the Owner field's value. -func (s *Object) SetOwner(v *Owner) *Object { - s.Owner = v - return s -} - -// SetSize sets the Size field's value. -func (s *Object) SetSize(v int64) *Object { - s.Size = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *Object) SetStorageClass(v string) *Object { - s.StorageClass = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectIdentifier -type ObjectIdentifier struct { - _ struct{} `type:"structure"` - - // Key name of the object to delete. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` - - // VersionId for the specific version of the object to delete. - VersionId *string `type:"string"` -} - -// String returns the string representation -func (s ObjectIdentifier) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ObjectIdentifier) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ObjectIdentifier) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ObjectIdentifier"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKey sets the Key field's value. -func (s *ObjectIdentifier) SetKey(v string) *ObjectIdentifier { - s.Key = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *ObjectIdentifier) SetVersionId(v string) *ObjectIdentifier { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ObjectVersion -type ObjectVersion struct { - _ struct{} `type:"structure"` - - ETag *string `type:"string"` - - // Specifies whether the object is (true) or is not (false) the latest version - // of an object. - IsLatest *bool `type:"boolean"` - - // The object key. - Key *string `min:"1" type:"string"` - - // Date and time the object was last modified. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - Owner *Owner `type:"structure"` - - // Size in bytes of the object. - Size *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"ObjectVersionStorageClass"` - - // Version ID of an object. - VersionId *string `type:"string"` -} - -// String returns the string representation -func (s ObjectVersion) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ObjectVersion) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *ObjectVersion) SetETag(v string) *ObjectVersion { - s.ETag = &v - return s -} - -// SetIsLatest sets the IsLatest field's value. -func (s *ObjectVersion) SetIsLatest(v bool) *ObjectVersion { - s.IsLatest = &v - return s -} - -// SetKey sets the Key field's value. -func (s *ObjectVersion) SetKey(v string) *ObjectVersion { - s.Key = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *ObjectVersion) SetLastModified(v time.Time) *ObjectVersion { - s.LastModified = &v - return s -} - -// SetOwner sets the Owner field's value. -func (s *ObjectVersion) SetOwner(v *Owner) *ObjectVersion { - s.Owner = v - return s -} - -// SetSize sets the Size field's value. -func (s *ObjectVersion) SetSize(v int64) *ObjectVersion { - s.Size = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *ObjectVersion) SetStorageClass(v string) *ObjectVersion { - s.StorageClass = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *ObjectVersion) SetVersionId(v string) *ObjectVersion { - s.VersionId = &v - return s -} - -// Describes the location where the restore job's output is stored. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/OutputLocation -type OutputLocation struct { - _ struct{} `type:"structure"` - - // Describes an S3 location that will receive the results of the restore request. - S3 *Location `type:"structure"` -} - -// String returns the string representation -func (s OutputLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OutputLocation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *OutputLocation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OutputLocation"} - if s.S3 != nil { - if err := s.S3.Validate(); err != nil { - invalidParams.AddNested("S3", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetS3 sets the S3 field's value. -func (s *OutputLocation) SetS3(v *Location) *OutputLocation { - s.S3 = v - return s -} - -// Describes how results of the Select job are serialized. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/OutputSerialization -type OutputSerialization struct { - _ struct{} `type:"structure"` - - // Describes the serialization of CSV-encoded Select results. - CSV *CSVOutput `type:"structure"` -} - -// String returns the string representation -func (s OutputSerialization) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OutputSerialization) GoString() string { - return s.String() -} - -// SetCSV sets the CSV field's value. -func (s *OutputSerialization) SetCSV(v *CSVOutput) *OutputSerialization { - s.CSV = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Owner -type Owner struct { - _ struct{} `type:"structure"` - - DisplayName *string `type:"string"` - - ID *string `type:"string"` -} - -// String returns the string representation -func (s Owner) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Owner) GoString() string { - return s.String() -} - -// SetDisplayName sets the DisplayName field's value. -func (s *Owner) SetDisplayName(v string) *Owner { - s.DisplayName = &v - return s -} - -// SetID sets the ID field's value. -func (s *Owner) SetID(v string) *Owner { - s.ID = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Part -type Part struct { - _ struct{} `type:"structure"` - - // Entity tag returned when the part was uploaded. - ETag *string `type:"string"` - - // Date and time at which the part was uploaded. - LastModified *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Part number identifying the part. This is a positive integer between 1 and - // 10,000. - PartNumber *int64 `type:"integer"` - - // Size of the uploaded part data. - Size *int64 `type:"integer"` -} - -// String returns the string representation -func (s Part) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Part) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *Part) SetETag(v string) *Part { - s.ETag = &v - return s -} - -// SetLastModified sets the LastModified field's value. -func (s *Part) SetLastModified(v time.Time) *Part { - s.LastModified = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *Part) SetPartNumber(v int64) *Part { - s.PartNumber = &v - return s -} - -// SetSize sets the Size field's value. -func (s *Part) SetSize(v int64) *Part { - s.Size = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationRequest -type PutBucketAccelerateConfigurationInput struct { - _ struct{} `type:"structure" payload:"AccelerateConfiguration"` - - // Specifies the Accelerate Configuration you want to set for the bucket. - // - // AccelerateConfiguration is a required field - AccelerateConfiguration *AccelerateConfiguration `locationName:"AccelerateConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // Name of the bucket for which the accelerate configuration is set. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` -} - -// String returns the string representation -func (s PutBucketAccelerateConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAccelerateConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAccelerateConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAccelerateConfigurationInput"} - if s.AccelerateConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("AccelerateConfiguration")) - } - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAccelerateConfiguration sets the AccelerateConfiguration field's value. -func (s *PutBucketAccelerateConfigurationInput) SetAccelerateConfiguration(v *AccelerateConfiguration) *PutBucketAccelerateConfigurationInput { - s.AccelerateConfiguration = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketAccelerateConfigurationInput) SetBucket(v string) *PutBucketAccelerateConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketAccelerateConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAccelerateConfigurationOutput -type PutBucketAccelerateConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketAccelerateConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAccelerateConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclRequest -type PutBucketAclInput struct { - _ struct{} `type:"structure" payload:"AccessControlPolicy"` - - // The canned ACL to apply to the bucket. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"BucketCannedACL"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` -} - -// String returns the string representation -func (s PutBucketAclInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAclInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.AccessControlPolicy != nil { - if err := s.AccessControlPolicy.Validate(); err != nil { - invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *PutBucketAclInput) SetACL(v string) *PutBucketAclInput { - s.ACL = &v - return s -} - -// SetAccessControlPolicy sets the AccessControlPolicy field's value. -func (s *PutBucketAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutBucketAclInput { - s.AccessControlPolicy = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketAclInput) SetBucket(v string) *PutBucketAclInput { - s.Bucket = &v - return s -} - -func (s *PutBucketAclInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutBucketAclInput) SetGrantFullControl(v string) *PutBucketAclInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *PutBucketAclInput) SetGrantRead(v string) *PutBucketAclInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutBucketAclInput) SetGrantReadACP(v string) *PutBucketAclInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWrite sets the GrantWrite field's value. -func (s *PutBucketAclInput) SetGrantWrite(v string) *PutBucketAclInput { - s.GrantWrite = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutBucketAclInput) SetGrantWriteACP(v string) *PutBucketAclInput { - s.GrantWriteACP = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAclOutput -type PutBucketAclOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketAclOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAclOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationRequest -type PutBucketAnalyticsConfigurationInput struct { - _ struct{} `type:"structure" payload:"AnalyticsConfiguration"` - - // The configuration and any analyses for the analytics filter. - // - // AnalyticsConfiguration is a required field - AnalyticsConfiguration *AnalyticsConfiguration `locationName:"AnalyticsConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // The name of the bucket to which an analytics configuration is stored. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The identifier used to represent an analytics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` -} - -// String returns the string representation -func (s PutBucketAnalyticsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAnalyticsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketAnalyticsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketAnalyticsConfigurationInput"} - if s.AnalyticsConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("AnalyticsConfiguration")) - } - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.AnalyticsConfiguration != nil { - if err := s.AnalyticsConfiguration.Validate(); err != nil { - invalidParams.AddNested("AnalyticsConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAnalyticsConfiguration sets the AnalyticsConfiguration field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetAnalyticsConfiguration(v *AnalyticsConfiguration) *PutBucketAnalyticsConfigurationInput { - s.AnalyticsConfiguration = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetBucket(v string) *PutBucketAnalyticsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketAnalyticsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *PutBucketAnalyticsConfigurationInput) SetId(v string) *PutBucketAnalyticsConfigurationInput { - s.Id = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketAnalyticsConfigurationOutput -type PutBucketAnalyticsConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketAnalyticsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketAnalyticsConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsRequest -type PutBucketCorsInput struct { - _ struct{} `type:"structure" payload:"CORSConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // CORSConfiguration is a required field - CORSConfiguration *CORSConfiguration `locationName:"CORSConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketCorsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketCorsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketCorsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketCorsInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.CORSConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("CORSConfiguration")) - } - if s.CORSConfiguration != nil { - if err := s.CORSConfiguration.Validate(); err != nil { - invalidParams.AddNested("CORSConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketCorsInput) SetBucket(v string) *PutBucketCorsInput { - s.Bucket = &v - return s -} - -func (s *PutBucketCorsInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCORSConfiguration sets the CORSConfiguration field's value. -func (s *PutBucketCorsInput) SetCORSConfiguration(v *CORSConfiguration) *PutBucketCorsInput { - s.CORSConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketCorsOutput -type PutBucketCorsOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketCorsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketCorsOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryptionRequest -type PutBucketEncryptionInput struct { - _ struct{} `type:"structure" payload:"ServerSideEncryptionConfiguration"` - - // The name of the bucket for which the server-side encryption configuration - // is set. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Container for server-side encryption configuration rules. Currently S3 supports - // one rule only. - // - // ServerSideEncryptionConfiguration is a required field - ServerSideEncryptionConfiguration *ServerSideEncryptionConfiguration `locationName:"ServerSideEncryptionConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketEncryptionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketEncryptionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketEncryptionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketEncryptionInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.ServerSideEncryptionConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("ServerSideEncryptionConfiguration")) - } - if s.ServerSideEncryptionConfiguration != nil { - if err := s.ServerSideEncryptionConfiguration.Validate(); err != nil { - invalidParams.AddNested("ServerSideEncryptionConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketEncryptionInput) SetBucket(v string) *PutBucketEncryptionInput { - s.Bucket = &v - return s -} - -func (s *PutBucketEncryptionInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetServerSideEncryptionConfiguration sets the ServerSideEncryptionConfiguration field's value. -func (s *PutBucketEncryptionInput) SetServerSideEncryptionConfiguration(v *ServerSideEncryptionConfiguration) *PutBucketEncryptionInput { - s.ServerSideEncryptionConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketEncryptionOutput -type PutBucketEncryptionOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketEncryptionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketEncryptionOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationRequest -type PutBucketInventoryConfigurationInput struct { - _ struct{} `type:"structure" payload:"InventoryConfiguration"` - - // The name of the bucket where the inventory configuration will be stored. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the inventory configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // Specifies the inventory configuration. - // - // InventoryConfiguration is a required field - InventoryConfiguration *InventoryConfiguration `locationName:"InventoryConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketInventoryConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketInventoryConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketInventoryConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketInventoryConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.InventoryConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("InventoryConfiguration")) - } - if s.InventoryConfiguration != nil { - if err := s.InventoryConfiguration.Validate(); err != nil { - invalidParams.AddNested("InventoryConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketInventoryConfigurationInput) SetBucket(v string) *PutBucketInventoryConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketInventoryConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *PutBucketInventoryConfigurationInput) SetId(v string) *PutBucketInventoryConfigurationInput { - s.Id = &v - return s -} - -// SetInventoryConfiguration sets the InventoryConfiguration field's value. -func (s *PutBucketInventoryConfigurationInput) SetInventoryConfiguration(v *InventoryConfiguration) *PutBucketInventoryConfigurationInput { - s.InventoryConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketInventoryConfigurationOutput -type PutBucketInventoryConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketInventoryConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketInventoryConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationRequest -type PutBucketLifecycleConfigurationInput struct { - _ struct{} `type:"structure" payload:"LifecycleConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - LifecycleConfiguration *BucketLifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketLifecycleConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLifecycleConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLifecycleConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.LifecycleConfiguration != nil { - if err := s.LifecycleConfiguration.Validate(); err != nil { - invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketLifecycleConfigurationInput) SetBucket(v string) *PutBucketLifecycleConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketLifecycleConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. -func (s *PutBucketLifecycleConfigurationInput) SetLifecycleConfiguration(v *BucketLifecycleConfiguration) *PutBucketLifecycleConfigurationInput { - s.LifecycleConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleConfigurationOutput -type PutBucketLifecycleConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketLifecycleConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLifecycleConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleRequest -type PutBucketLifecycleInput struct { - _ struct{} `type:"structure" payload:"LifecycleConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - LifecycleConfiguration *LifecycleConfiguration `locationName:"LifecycleConfiguration" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketLifecycleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLifecycleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLifecycleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLifecycleInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.LifecycleConfiguration != nil { - if err := s.LifecycleConfiguration.Validate(); err != nil { - invalidParams.AddNested("LifecycleConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketLifecycleInput) SetBucket(v string) *PutBucketLifecycleInput { - s.Bucket = &v - return s -} - -func (s *PutBucketLifecycleInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetLifecycleConfiguration sets the LifecycleConfiguration field's value. -func (s *PutBucketLifecycleInput) SetLifecycleConfiguration(v *LifecycleConfiguration) *PutBucketLifecycleInput { - s.LifecycleConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLifecycleOutput -type PutBucketLifecycleOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketLifecycleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLifecycleOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingRequest -type PutBucketLoggingInput struct { - _ struct{} `type:"structure" payload:"BucketLoggingStatus"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // BucketLoggingStatus is a required field - BucketLoggingStatus *BucketLoggingStatus `locationName:"BucketLoggingStatus" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketLoggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLoggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketLoggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketLoggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.BucketLoggingStatus == nil { - invalidParams.Add(request.NewErrParamRequired("BucketLoggingStatus")) - } - if s.BucketLoggingStatus != nil { - if err := s.BucketLoggingStatus.Validate(); err != nil { - invalidParams.AddNested("BucketLoggingStatus", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketLoggingInput) SetBucket(v string) *PutBucketLoggingInput { - s.Bucket = &v - return s -} - -func (s *PutBucketLoggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetBucketLoggingStatus sets the BucketLoggingStatus field's value. -func (s *PutBucketLoggingInput) SetBucketLoggingStatus(v *BucketLoggingStatus) *PutBucketLoggingInput { - s.BucketLoggingStatus = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketLoggingOutput -type PutBucketLoggingOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketLoggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketLoggingOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationRequest -type PutBucketMetricsConfigurationInput struct { - _ struct{} `type:"structure" payload:"MetricsConfiguration"` - - // The name of the bucket for which the metrics configuration is set. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The ID used to identify the metrics configuration. - // - // Id is a required field - Id *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // Specifies the metrics configuration. - // - // MetricsConfiguration is a required field - MetricsConfiguration *MetricsConfiguration `locationName:"MetricsConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketMetricsConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketMetricsConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketMetricsConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketMetricsConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.MetricsConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("MetricsConfiguration")) - } - if s.MetricsConfiguration != nil { - if err := s.MetricsConfiguration.Validate(); err != nil { - invalidParams.AddNested("MetricsConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketMetricsConfigurationInput) SetBucket(v string) *PutBucketMetricsConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketMetricsConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetId sets the Id field's value. -func (s *PutBucketMetricsConfigurationInput) SetId(v string) *PutBucketMetricsConfigurationInput { - s.Id = &v - return s -} - -// SetMetricsConfiguration sets the MetricsConfiguration field's value. -func (s *PutBucketMetricsConfigurationInput) SetMetricsConfiguration(v *MetricsConfiguration) *PutBucketMetricsConfigurationInput { - s.MetricsConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketMetricsConfigurationOutput -type PutBucketMetricsConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketMetricsConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketMetricsConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationRequest -type PutBucketNotificationConfigurationInput struct { - _ struct{} `type:"structure" payload:"NotificationConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Container for specifying the notification configuration of the bucket. If - // this element is empty, notifications are turned off on the bucket. - // - // NotificationConfiguration is a required field - NotificationConfiguration *NotificationConfiguration `locationName:"NotificationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketNotificationConfigurationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketNotificationConfigurationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketNotificationConfigurationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationConfigurationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.NotificationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) - } - if s.NotificationConfiguration != nil { - if err := s.NotificationConfiguration.Validate(); err != nil { - invalidParams.AddNested("NotificationConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketNotificationConfigurationInput) SetBucket(v string) *PutBucketNotificationConfigurationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketNotificationConfigurationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetNotificationConfiguration sets the NotificationConfiguration field's value. -func (s *PutBucketNotificationConfigurationInput) SetNotificationConfiguration(v *NotificationConfiguration) *PutBucketNotificationConfigurationInput { - s.NotificationConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationConfigurationOutput -type PutBucketNotificationConfigurationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketNotificationConfigurationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketNotificationConfigurationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationRequest -type PutBucketNotificationInput struct { - _ struct{} `type:"structure" payload:"NotificationConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // NotificationConfiguration is a required field - NotificationConfiguration *NotificationConfigurationDeprecated `locationName:"NotificationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketNotificationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketNotificationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketNotificationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketNotificationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.NotificationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("NotificationConfiguration")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketNotificationInput) SetBucket(v string) *PutBucketNotificationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketNotificationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetNotificationConfiguration sets the NotificationConfiguration field's value. -func (s *PutBucketNotificationInput) SetNotificationConfiguration(v *NotificationConfigurationDeprecated) *PutBucketNotificationInput { - s.NotificationConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketNotificationOutput -type PutBucketNotificationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketNotificationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketNotificationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyRequest -type PutBucketPolicyInput struct { - _ struct{} `type:"structure" payload:"Policy"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Set this parameter to true to confirm that you want to remove your permissions - // to change this bucket policy in the future. - ConfirmRemoveSelfBucketAccess *bool `location:"header" locationName:"x-amz-confirm-remove-self-bucket-access" type:"boolean"` - - // The bucket policy as a JSON document. - // - // Policy is a required field - Policy *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s PutBucketPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketPolicyInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Policy == nil { - invalidParams.Add(request.NewErrParamRequired("Policy")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketPolicyInput) SetBucket(v string) *PutBucketPolicyInput { - s.Bucket = &v - return s -} - -func (s *PutBucketPolicyInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetConfirmRemoveSelfBucketAccess sets the ConfirmRemoveSelfBucketAccess field's value. -func (s *PutBucketPolicyInput) SetConfirmRemoveSelfBucketAccess(v bool) *PutBucketPolicyInput { - s.ConfirmRemoveSelfBucketAccess = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *PutBucketPolicyInput) SetPolicy(v string) *PutBucketPolicyInput { - s.Policy = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketPolicyOutput -type PutBucketPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketPolicyOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationRequest -type PutBucketReplicationInput struct { - _ struct{} `type:"structure" payload:"ReplicationConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Container for replication rules. You can add as many as 1,000 rules. Total - // replication configuration size can be up to 2 MB. - // - // ReplicationConfiguration is a required field - ReplicationConfiguration *ReplicationConfiguration `locationName:"ReplicationConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketReplicationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketReplicationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketReplicationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketReplicationInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.ReplicationConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("ReplicationConfiguration")) - } - if s.ReplicationConfiguration != nil { - if err := s.ReplicationConfiguration.Validate(); err != nil { - invalidParams.AddNested("ReplicationConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketReplicationInput) SetBucket(v string) *PutBucketReplicationInput { - s.Bucket = &v - return s -} - -func (s *PutBucketReplicationInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetReplicationConfiguration sets the ReplicationConfiguration field's value. -func (s *PutBucketReplicationInput) SetReplicationConfiguration(v *ReplicationConfiguration) *PutBucketReplicationInput { - s.ReplicationConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketReplicationOutput -type PutBucketReplicationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketReplicationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketReplicationOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentRequest -type PutBucketRequestPaymentInput struct { - _ struct{} `type:"structure" payload:"RequestPaymentConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // RequestPaymentConfiguration is a required field - RequestPaymentConfiguration *RequestPaymentConfiguration `locationName:"RequestPaymentConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketRequestPaymentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketRequestPaymentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketRequestPaymentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketRequestPaymentInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.RequestPaymentConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("RequestPaymentConfiguration")) - } - if s.RequestPaymentConfiguration != nil { - if err := s.RequestPaymentConfiguration.Validate(); err != nil { - invalidParams.AddNested("RequestPaymentConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketRequestPaymentInput) SetBucket(v string) *PutBucketRequestPaymentInput { - s.Bucket = &v - return s -} - -func (s *PutBucketRequestPaymentInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetRequestPaymentConfiguration sets the RequestPaymentConfiguration field's value. -func (s *PutBucketRequestPaymentInput) SetRequestPaymentConfiguration(v *RequestPaymentConfiguration) *PutBucketRequestPaymentInput { - s.RequestPaymentConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketRequestPaymentOutput -type PutBucketRequestPaymentOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketRequestPaymentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketRequestPaymentOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingRequest -type PutBucketTaggingInput struct { - _ struct{} `type:"structure" payload:"Tagging"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Tagging is a required field - Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Tagging == nil { - invalidParams.Add(request.NewErrParamRequired("Tagging")) - } - if s.Tagging != nil { - if err := s.Tagging.Validate(); err != nil { - invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketTaggingInput) SetBucket(v string) *PutBucketTaggingInput { - s.Bucket = &v - return s -} - -func (s *PutBucketTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetTagging sets the Tagging field's value. -func (s *PutBucketTaggingInput) SetTagging(v *Tagging) *PutBucketTaggingInput { - s.Tagging = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketTaggingOutput -type PutBucketTaggingOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketTaggingOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningRequest -type PutBucketVersioningInput struct { - _ struct{} `type:"structure" payload:"VersioningConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The concatenation of the authentication device's serial number, a space, - // and the value that is displayed on your authentication device. - MFA *string `location:"header" locationName:"x-amz-mfa" type:"string"` - - // VersioningConfiguration is a required field - VersioningConfiguration *VersioningConfiguration `locationName:"VersioningConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketVersioningInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketVersioningInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketVersioningInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketVersioningInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.VersioningConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("VersioningConfiguration")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketVersioningInput) SetBucket(v string) *PutBucketVersioningInput { - s.Bucket = &v - return s -} - -func (s *PutBucketVersioningInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetMFA sets the MFA field's value. -func (s *PutBucketVersioningInput) SetMFA(v string) *PutBucketVersioningInput { - s.MFA = &v - return s -} - -// SetVersioningConfiguration sets the VersioningConfiguration field's value. -func (s *PutBucketVersioningInput) SetVersioningConfiguration(v *VersioningConfiguration) *PutBucketVersioningInput { - s.VersioningConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketVersioningOutput -type PutBucketVersioningOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketVersioningOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketVersioningOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteRequest -type PutBucketWebsiteInput struct { - _ struct{} `type:"structure" payload:"WebsiteConfiguration"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // WebsiteConfiguration is a required field - WebsiteConfiguration *WebsiteConfiguration `locationName:"WebsiteConfiguration" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` -} - -// String returns the string representation -func (s PutBucketWebsiteInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketWebsiteInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutBucketWebsiteInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutBucketWebsiteInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.WebsiteConfiguration == nil { - invalidParams.Add(request.NewErrParamRequired("WebsiteConfiguration")) - } - if s.WebsiteConfiguration != nil { - if err := s.WebsiteConfiguration.Validate(); err != nil { - invalidParams.AddNested("WebsiteConfiguration", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutBucketWebsiteInput) SetBucket(v string) *PutBucketWebsiteInput { - s.Bucket = &v - return s -} - -func (s *PutBucketWebsiteInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetWebsiteConfiguration sets the WebsiteConfiguration field's value. -func (s *PutBucketWebsiteInput) SetWebsiteConfiguration(v *WebsiteConfiguration) *PutBucketWebsiteInput { - s.WebsiteConfiguration = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutBucketWebsiteOutput -type PutBucketWebsiteOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PutBucketWebsiteOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutBucketWebsiteOutput) GoString() string { - return s.String() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclRequest -type PutObjectAclInput struct { - _ struct{} `type:"structure" payload:"AccessControlPolicy"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - AccessControlPolicy *AccessControlPolicy `locationName:"AccessControlPolicy" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Allows grantee the read, write, read ACP, and write ACP permissions on the - // bucket. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to list the objects in the bucket. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the bucket ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to create, overwrite, and delete any object in the bucket. - GrantWrite *string `location:"header" locationName:"x-amz-grant-write" type:"string"` - - // Allows grantee to write the ACL for the applicable bucket. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // VersionId used to reference a specific version of the object. - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s PutObjectAclInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectAclInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectAclInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectAclInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.AccessControlPolicy != nil { - if err := s.AccessControlPolicy.Validate(); err != nil { - invalidParams.AddNested("AccessControlPolicy", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *PutObjectAclInput) SetACL(v string) *PutObjectAclInput { - s.ACL = &v - return s -} - -// SetAccessControlPolicy sets the AccessControlPolicy field's value. -func (s *PutObjectAclInput) SetAccessControlPolicy(v *AccessControlPolicy) *PutObjectAclInput { - s.AccessControlPolicy = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *PutObjectAclInput) SetBucket(v string) *PutObjectAclInput { - s.Bucket = &v - return s -} - -func (s *PutObjectAclInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutObjectAclInput) SetGrantFullControl(v string) *PutObjectAclInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *PutObjectAclInput) SetGrantRead(v string) *PutObjectAclInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutObjectAclInput) SetGrantReadACP(v string) *PutObjectAclInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWrite sets the GrantWrite field's value. -func (s *PutObjectAclInput) SetGrantWrite(v string) *PutObjectAclInput { - s.GrantWrite = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutObjectAclInput) SetGrantWriteACP(v string) *PutObjectAclInput { - s.GrantWriteACP = &v - return s -} - -// SetKey sets the Key field's value. -func (s *PutObjectAclInput) SetKey(v string) *PutObjectAclInput { - s.Key = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *PutObjectAclInput) SetRequestPayer(v string) *PutObjectAclInput { - s.RequestPayer = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *PutObjectAclInput) SetVersionId(v string) *PutObjectAclInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectAclOutput -type PutObjectAclOutput struct { - _ struct{} `type:"structure"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` -} - -// String returns the string representation -func (s PutObjectAclOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectAclOutput) GoString() string { - return s.String() -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *PutObjectAclOutput) SetRequestCharged(v string) *PutObjectAclOutput { - s.RequestCharged = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectRequest -type PutObjectInput struct { - _ struct{} `type:"structure" payload:"Body"` - - // The canned ACL to apply to the object. - ACL *string `location:"header" locationName:"x-amz-acl" type:"string" enum:"ObjectCannedACL"` - - // Object data. - Body io.ReadSeeker `type:"blob"` - - // Name of the bucket to which the PUT operation was initiated. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Specifies caching behavior along the request/reply chain. - CacheControl *string `location:"header" locationName:"Cache-Control" type:"string"` - - // Specifies presentational information for the object. - ContentDisposition *string `location:"header" locationName:"Content-Disposition" type:"string"` - - // Specifies what content encodings have been applied to the object and thus - // what decoding mechanisms must be applied to obtain the media-type referenced - // by the Content-Type header field. - ContentEncoding *string `location:"header" locationName:"Content-Encoding" type:"string"` - - // The language the content is in. - ContentLanguage *string `location:"header" locationName:"Content-Language" type:"string"` - - // Size of the body in bytes. This parameter is useful when the size of the - // body cannot be determined automatically. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - - // The base64-encoded 128-bit MD5 digest of the part data. - ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` - - // A standard MIME type describing the format of the object data. - ContentType *string `location:"header" locationName:"Content-Type" type:"string"` - - // The date and time at which the object is no longer cacheable. - Expires *time.Time `location:"header" locationName:"Expires" type:"timestamp" timestampFormat:"rfc822"` - - // Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object. - GrantFullControl *string `location:"header" locationName:"x-amz-grant-full-control" type:"string"` - - // Allows grantee to read the object data and its metadata. - GrantRead *string `location:"header" locationName:"x-amz-grant-read" type:"string"` - - // Allows grantee to read the object ACL. - GrantReadACP *string `location:"header" locationName:"x-amz-grant-read-acp" type:"string"` - - // Allows grantee to write the ACL for the applicable object. - GrantWriteACP *string `location:"header" locationName:"x-amz-grant-write-acp" type:"string"` - - // Object key for which the PUT operation was initiated. - // - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // A map of metadata to store with the object in S3. - Metadata map[string]*string `location:"headers" locationName:"x-amz-meta-" type:"map"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Specifies the AWS KMS key ID to use for object encryption. All GET and PUT - // requests for an object protected by AWS KMS will fail if not made via SSL - // or using SigV4. Documentation on configuring any of the officially supported - // AWS SDKs and CLI can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // The type of storage to use for the object. Defaults to 'STANDARD'. - StorageClass *string `location:"header" locationName:"x-amz-storage-class" type:"string" enum:"StorageClass"` - - // The tag-set for the object. The tag-set must be encoded as URL Query parameters - Tagging *string `location:"header" locationName:"x-amz-tagging" type:"string"` - - // If the bucket is configured as a website, redirects requests for this object - // to another object in the same bucket or to an external URL. Amazon S3 stores - // the value of this header in the object metadata. - WebsiteRedirectLocation *string `location:"header" locationName:"x-amz-website-redirect-location" type:"string"` -} - -// String returns the string representation -func (s PutObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetACL sets the ACL field's value. -func (s *PutObjectInput) SetACL(v string) *PutObjectInput { - s.ACL = &v - return s -} - -// SetBody sets the Body field's value. -func (s *PutObjectInput) SetBody(v io.ReadSeeker) *PutObjectInput { - s.Body = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *PutObjectInput) SetBucket(v string) *PutObjectInput { - s.Bucket = &v - return s -} - -func (s *PutObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCacheControl sets the CacheControl field's value. -func (s *PutObjectInput) SetCacheControl(v string) *PutObjectInput { - s.CacheControl = &v - return s -} - -// SetContentDisposition sets the ContentDisposition field's value. -func (s *PutObjectInput) SetContentDisposition(v string) *PutObjectInput { - s.ContentDisposition = &v - return s -} - -// SetContentEncoding sets the ContentEncoding field's value. -func (s *PutObjectInput) SetContentEncoding(v string) *PutObjectInput { - s.ContentEncoding = &v - return s -} - -// SetContentLanguage sets the ContentLanguage field's value. -func (s *PutObjectInput) SetContentLanguage(v string) *PutObjectInput { - s.ContentLanguage = &v - return s -} - -// SetContentLength sets the ContentLength field's value. -func (s *PutObjectInput) SetContentLength(v int64) *PutObjectInput { - s.ContentLength = &v - return s -} - -// SetContentMD5 sets the ContentMD5 field's value. -func (s *PutObjectInput) SetContentMD5(v string) *PutObjectInput { - s.ContentMD5 = &v - return s -} - -// SetContentType sets the ContentType field's value. -func (s *PutObjectInput) SetContentType(v string) *PutObjectInput { - s.ContentType = &v - return s -} - -// SetExpires sets the Expires field's value. -func (s *PutObjectInput) SetExpires(v time.Time) *PutObjectInput { - s.Expires = &v - return s -} - -// SetGrantFullControl sets the GrantFullControl field's value. -func (s *PutObjectInput) SetGrantFullControl(v string) *PutObjectInput { - s.GrantFullControl = &v - return s -} - -// SetGrantRead sets the GrantRead field's value. -func (s *PutObjectInput) SetGrantRead(v string) *PutObjectInput { - s.GrantRead = &v - return s -} - -// SetGrantReadACP sets the GrantReadACP field's value. -func (s *PutObjectInput) SetGrantReadACP(v string) *PutObjectInput { - s.GrantReadACP = &v - return s -} - -// SetGrantWriteACP sets the GrantWriteACP field's value. -func (s *PutObjectInput) SetGrantWriteACP(v string) *PutObjectInput { - s.GrantWriteACP = &v - return s -} - -// SetKey sets the Key field's value. -func (s *PutObjectInput) SetKey(v string) *PutObjectInput { - s.Key = &v - return s -} - -// SetMetadata sets the Metadata field's value. -func (s *PutObjectInput) SetMetadata(v map[string]*string) *PutObjectInput { - s.Metadata = v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *PutObjectInput) SetRequestPayer(v string) *PutObjectInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *PutObjectInput) SetSSECustomerAlgorithm(v string) *PutObjectInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *PutObjectInput) SetSSECustomerKey(v string) *PutObjectInput { - s.SSECustomerKey = &v - return s -} - -func (s *PutObjectInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *PutObjectInput) SetSSECustomerKeyMD5(v string) *PutObjectInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *PutObjectInput) SetSSEKMSKeyId(v string) *PutObjectInput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *PutObjectInput) SetServerSideEncryption(v string) *PutObjectInput { - s.ServerSideEncryption = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *PutObjectInput) SetStorageClass(v string) *PutObjectInput { - s.StorageClass = &v - return s -} - -// SetTagging sets the Tagging field's value. -func (s *PutObjectInput) SetTagging(v string) *PutObjectInput { - s.Tagging = &v - return s -} - -// SetWebsiteRedirectLocation sets the WebsiteRedirectLocation field's value. -func (s *PutObjectInput) SetWebsiteRedirectLocation(v string) *PutObjectInput { - s.WebsiteRedirectLocation = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectOutput -type PutObjectOutput struct { - _ struct{} `type:"structure"` - - // Entity tag for the uploaded object. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If the object expiration is configured, this will contain the expiration - // date (expiry-date) and rule ID (rule-id). The value of rule-id is URL encoded. - Expiration *string `location:"header" locationName:"x-amz-expiration" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` - - // Version of the object. - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s PutObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectOutput) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *PutObjectOutput) SetETag(v string) *PutObjectOutput { - s.ETag = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *PutObjectOutput) SetExpiration(v string) *PutObjectOutput { - s.Expiration = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *PutObjectOutput) SetRequestCharged(v string) *PutObjectOutput { - s.RequestCharged = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *PutObjectOutput) SetSSECustomerAlgorithm(v string) *PutObjectOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *PutObjectOutput) SetSSECustomerKeyMD5(v string) *PutObjectOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *PutObjectOutput) SetSSEKMSKeyId(v string) *PutObjectOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *PutObjectOutput) SetServerSideEncryption(v string) *PutObjectOutput { - s.ServerSideEncryption = &v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *PutObjectOutput) SetVersionId(v string) *PutObjectOutput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingRequest -type PutObjectTaggingInput struct { - _ struct{} `type:"structure" payload:"Tagging"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Tagging is a required field - Tagging *Tagging `locationName:"Tagging" type:"structure" required:"true" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s PutObjectTaggingInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectTaggingInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutObjectTaggingInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutObjectTaggingInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.Tagging == nil { - invalidParams.Add(request.NewErrParamRequired("Tagging")) - } - if s.Tagging != nil { - if err := s.Tagging.Validate(); err != nil { - invalidParams.AddNested("Tagging", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *PutObjectTaggingInput) SetBucket(v string) *PutObjectTaggingInput { - s.Bucket = &v - return s -} - -func (s *PutObjectTaggingInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *PutObjectTaggingInput) SetKey(v string) *PutObjectTaggingInput { - s.Key = &v - return s -} - -// SetTagging sets the Tagging field's value. -func (s *PutObjectTaggingInput) SetTagging(v *Tagging) *PutObjectTaggingInput { - s.Tagging = v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *PutObjectTaggingInput) SetVersionId(v string) *PutObjectTaggingInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/PutObjectTaggingOutput -type PutObjectTaggingOutput struct { - _ struct{} `type:"structure"` - - VersionId *string `location:"header" locationName:"x-amz-version-id" type:"string"` -} - -// String returns the string representation -func (s PutObjectTaggingOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutObjectTaggingOutput) GoString() string { - return s.String() -} - -// SetVersionId sets the VersionId field's value. -func (s *PutObjectTaggingOutput) SetVersionId(v string) *PutObjectTaggingOutput { - s.VersionId = &v - return s -} - -// Container for specifying an configuration when you want Amazon S3 to publish -// events to an Amazon Simple Queue Service (Amazon SQS) queue. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfiguration -type QueueConfiguration struct { - _ struct{} `type:"structure"` - - // Events is a required field - Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Filter *NotificationConfigurationFilter `type:"structure"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - // Amazon SQS queue ARN to which Amazon S3 will publish a message when it detects - // events of specified type. - // - // QueueArn is a required field - QueueArn *string `locationName:"Queue" type:"string" required:"true"` -} - -// String returns the string representation -func (s QueueConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s QueueConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *QueueConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "QueueConfiguration"} - if s.Events == nil { - invalidParams.Add(request.NewErrParamRequired("Events")) - } - if s.QueueArn == nil { - invalidParams.Add(request.NewErrParamRequired("QueueArn")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEvents sets the Events field's value. -func (s *QueueConfiguration) SetEvents(v []*string) *QueueConfiguration { - s.Events = v - return s -} - -// SetFilter sets the Filter field's value. -func (s *QueueConfiguration) SetFilter(v *NotificationConfigurationFilter) *QueueConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *QueueConfiguration) SetId(v string) *QueueConfiguration { - s.Id = &v - return s -} - -// SetQueueArn sets the QueueArn field's value. -func (s *QueueConfiguration) SetQueueArn(v string) *QueueConfiguration { - s.QueueArn = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/QueueConfigurationDeprecated -type QueueConfigurationDeprecated struct { - _ struct{} `type:"structure"` - - // Bucket event for which to send notifications. - Event *string `deprecated:"true" type:"string" enum:"Event"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - Queue *string `type:"string"` -} - -// String returns the string representation -func (s QueueConfigurationDeprecated) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s QueueConfigurationDeprecated) GoString() string { - return s.String() -} - -// SetEvent sets the Event field's value. -func (s *QueueConfigurationDeprecated) SetEvent(v string) *QueueConfigurationDeprecated { - s.Event = &v - return s -} - -// SetEvents sets the Events field's value. -func (s *QueueConfigurationDeprecated) SetEvents(v []*string) *QueueConfigurationDeprecated { - s.Events = v - return s -} - -// SetId sets the Id field's value. -func (s *QueueConfigurationDeprecated) SetId(v string) *QueueConfigurationDeprecated { - s.Id = &v - return s -} - -// SetQueue sets the Queue field's value. -func (s *QueueConfigurationDeprecated) SetQueue(v string) *QueueConfigurationDeprecated { - s.Queue = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Redirect -type Redirect struct { - _ struct{} `type:"structure"` - - // The host name to use in the redirect request. - HostName *string `type:"string"` - - // The HTTP redirect code to use on the response. Not required if one of the - // siblings is present. - HttpRedirectCode *string `type:"string"` - - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string" enum:"Protocol"` - - // The object key prefix to use in the redirect request. For example, to redirect - // requests for all pages with prefix docs/ (objects in the docs/ folder) to - // documents/, you can set a condition block with KeyPrefixEquals set to docs/ - // and in the Redirect set ReplaceKeyPrefixWith to /documents. Not required - // if one of the siblings is present. Can be present only if ReplaceKeyWith - // is not provided. - ReplaceKeyPrefixWith *string `type:"string"` - - // The specific object key to use in the redirect request. For example, redirect - // request to error.html. Not required if one of the sibling is present. Can - // be present only if ReplaceKeyPrefixWith is not provided. - ReplaceKeyWith *string `type:"string"` -} - -// String returns the string representation -func (s Redirect) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Redirect) GoString() string { - return s.String() -} - -// SetHostName sets the HostName field's value. -func (s *Redirect) SetHostName(v string) *Redirect { - s.HostName = &v - return s -} - -// SetHttpRedirectCode sets the HttpRedirectCode field's value. -func (s *Redirect) SetHttpRedirectCode(v string) *Redirect { - s.HttpRedirectCode = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *Redirect) SetProtocol(v string) *Redirect { - s.Protocol = &v - return s -} - -// SetReplaceKeyPrefixWith sets the ReplaceKeyPrefixWith field's value. -func (s *Redirect) SetReplaceKeyPrefixWith(v string) *Redirect { - s.ReplaceKeyPrefixWith = &v - return s -} - -// SetReplaceKeyWith sets the ReplaceKeyWith field's value. -func (s *Redirect) SetReplaceKeyWith(v string) *Redirect { - s.ReplaceKeyWith = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RedirectAllRequestsTo -type RedirectAllRequestsTo struct { - _ struct{} `type:"structure"` - - // Name of the host where requests will be redirected. - // - // HostName is a required field - HostName *string `type:"string" required:"true"` - - // Protocol to use (http, https) when redirecting requests. The default is the - // protocol that is used in the original request. - Protocol *string `type:"string" enum:"Protocol"` -} - -// String returns the string representation -func (s RedirectAllRequestsTo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RedirectAllRequestsTo) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RedirectAllRequestsTo) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RedirectAllRequestsTo"} - if s.HostName == nil { - invalidParams.Add(request.NewErrParamRequired("HostName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostName sets the HostName field's value. -func (s *RedirectAllRequestsTo) SetHostName(v string) *RedirectAllRequestsTo { - s.HostName = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *RedirectAllRequestsTo) SetProtocol(v string) *RedirectAllRequestsTo { - s.Protocol = &v - return s -} - -// Container for replication rules. You can add as many as 1,000 rules. Total -// replication configuration size can be up to 2 MB. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationConfiguration -type ReplicationConfiguration struct { - _ struct{} `type:"structure"` - - // Amazon Resource Name (ARN) of an IAM role for Amazon S3 to assume when replicating - // the objects. - // - // Role is a required field - Role *string `type:"string" required:"true"` - - // Container for information about a particular replication rule. Replication - // configuration must have at least one rule and can contain up to 1,000 rules. - // - // Rules is a required field - Rules []*ReplicationRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` -} - -// String returns the string representation -func (s ReplicationConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReplicationConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ReplicationConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReplicationConfiguration"} - if s.Role == nil { - invalidParams.Add(request.NewErrParamRequired("Role")) - } - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetRole sets the Role field's value. -func (s *ReplicationConfiguration) SetRole(v string) *ReplicationConfiguration { - s.Role = &v - return s -} - -// SetRules sets the Rules field's value. -func (s *ReplicationConfiguration) SetRules(v []*ReplicationRule) *ReplicationConfiguration { - s.Rules = v - return s -} - -// Container for information about a particular replication rule. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ReplicationRule -type ReplicationRule struct { - _ struct{} `type:"structure"` - - // Container for replication destination information. - // - // Destination is a required field - Destination *Destination `type:"structure" required:"true"` - - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` - - // Object keyname prefix identifying one or more objects to which the rule applies. - // Maximum prefix length can be up to 1,024 characters. Overlapping prefixes - // are not supported. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` - - // Container for filters that define which source objects should be replicated. - SourceSelectionCriteria *SourceSelectionCriteria `type:"structure"` - - // The rule is ignored if status is not Enabled. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ReplicationRuleStatus"` -} - -// String returns the string representation -func (s ReplicationRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReplicationRule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ReplicationRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReplicationRule"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) - } - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) - } - if s.Destination != nil { - if err := s.Destination.Validate(); err != nil { - invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) - } - } - if s.SourceSelectionCriteria != nil { - if err := s.SourceSelectionCriteria.Validate(); err != nil { - invalidParams.AddNested("SourceSelectionCriteria", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestination sets the Destination field's value. -func (s *ReplicationRule) SetDestination(v *Destination) *ReplicationRule { - s.Destination = v - return s -} - -// SetID sets the ID field's value. -func (s *ReplicationRule) SetID(v string) *ReplicationRule { - s.ID = &v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *ReplicationRule) SetPrefix(v string) *ReplicationRule { - s.Prefix = &v - return s -} - -// SetSourceSelectionCriteria sets the SourceSelectionCriteria field's value. -func (s *ReplicationRule) SetSourceSelectionCriteria(v *SourceSelectionCriteria) *ReplicationRule { - s.SourceSelectionCriteria = v - return s -} - -// SetStatus sets the Status field's value. -func (s *ReplicationRule) SetStatus(v string) *ReplicationRule { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RequestPaymentConfiguration -type RequestPaymentConfiguration struct { - _ struct{} `type:"structure"` - - // Specifies who pays for the download and request fees. - // - // Payer is a required field - Payer *string `type:"string" required:"true" enum:"Payer"` -} - -// String returns the string representation -func (s RequestPaymentConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RequestPaymentConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RequestPaymentConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RequestPaymentConfiguration"} - if s.Payer == nil { - invalidParams.Add(request.NewErrParamRequired("Payer")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPayer sets the Payer field's value. -func (s *RequestPaymentConfiguration) SetPayer(v string) *RequestPaymentConfiguration { - s.Payer = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectRequest -type RestoreObjectInput struct { - _ struct{} `type:"structure" payload:"RestoreRequest"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Container for restore job parameters. - RestoreRequest *RestoreRequest `locationName:"RestoreRequest" type:"structure" xmlURI:"http://s3.amazonaws.com/doc/2006-03-01/"` - - VersionId *string `location:"querystring" locationName:"versionId" type:"string"` -} - -// String returns the string representation -func (s RestoreObjectInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RestoreObjectInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RestoreObjectInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RestoreObjectInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.RestoreRequest != nil { - if err := s.RestoreRequest.Validate(); err != nil { - invalidParams.AddNested("RestoreRequest", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *RestoreObjectInput) SetBucket(v string) *RestoreObjectInput { - s.Bucket = &v - return s -} - -func (s *RestoreObjectInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetKey sets the Key field's value. -func (s *RestoreObjectInput) SetKey(v string) *RestoreObjectInput { - s.Key = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *RestoreObjectInput) SetRequestPayer(v string) *RestoreObjectInput { - s.RequestPayer = &v - return s -} - -// SetRestoreRequest sets the RestoreRequest field's value. -func (s *RestoreObjectInput) SetRestoreRequest(v *RestoreRequest) *RestoreObjectInput { - s.RestoreRequest = v - return s -} - -// SetVersionId sets the VersionId field's value. -func (s *RestoreObjectInput) SetVersionId(v string) *RestoreObjectInput { - s.VersionId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreObjectOutput -type RestoreObjectOutput struct { - _ struct{} `type:"structure"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // Indicates the path in the provided S3 output location where Select results - // will be restored to. - RestoreOutputPath *string `location:"header" locationName:"x-amz-restore-output-path" type:"string"` -} - -// String returns the string representation -func (s RestoreObjectOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RestoreObjectOutput) GoString() string { - return s.String() -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *RestoreObjectOutput) SetRequestCharged(v string) *RestoreObjectOutput { - s.RequestCharged = &v - return s -} - -// SetRestoreOutputPath sets the RestoreOutputPath field's value. -func (s *RestoreObjectOutput) SetRestoreOutputPath(v string) *RestoreObjectOutput { - s.RestoreOutputPath = &v - return s -} - -// Container for restore job parameters. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RestoreRequest -type RestoreRequest struct { - _ struct{} `type:"structure"` - - // Lifetime of the active copy in days. Do not use with restores that specify - // OutputLocation. - Days *int64 `type:"integer"` - - // The optional description for the job. - Description *string `type:"string"` - - // Glacier related parameters pertaining to this job. Do not use with restores - // that specify OutputLocation. - GlacierJobParameters *GlacierJobParameters `type:"structure"` - - // Describes the location where the restore job's output is stored. - OutputLocation *OutputLocation `type:"structure"` - - // Describes the parameters for Select job types. - SelectParameters *SelectParameters `type:"structure"` - - // Glacier retrieval tier at which the restore will be processed. - Tier *string `type:"string" enum:"Tier"` - - // Type of restore request. - Type *string `type:"string" enum:"RestoreRequestType"` -} - -// String returns the string representation -func (s RestoreRequest) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RestoreRequest) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RestoreRequest) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RestoreRequest"} - if s.GlacierJobParameters != nil { - if err := s.GlacierJobParameters.Validate(); err != nil { - invalidParams.AddNested("GlacierJobParameters", err.(request.ErrInvalidParams)) - } - } - if s.OutputLocation != nil { - if err := s.OutputLocation.Validate(); err != nil { - invalidParams.AddNested("OutputLocation", err.(request.ErrInvalidParams)) - } - } - if s.SelectParameters != nil { - if err := s.SelectParameters.Validate(); err != nil { - invalidParams.AddNested("SelectParameters", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDays sets the Days field's value. -func (s *RestoreRequest) SetDays(v int64) *RestoreRequest { - s.Days = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *RestoreRequest) SetDescription(v string) *RestoreRequest { - s.Description = &v - return s -} - -// SetGlacierJobParameters sets the GlacierJobParameters field's value. -func (s *RestoreRequest) SetGlacierJobParameters(v *GlacierJobParameters) *RestoreRequest { - s.GlacierJobParameters = v - return s -} - -// SetOutputLocation sets the OutputLocation field's value. -func (s *RestoreRequest) SetOutputLocation(v *OutputLocation) *RestoreRequest { - s.OutputLocation = v - return s -} - -// SetSelectParameters sets the SelectParameters field's value. -func (s *RestoreRequest) SetSelectParameters(v *SelectParameters) *RestoreRequest { - s.SelectParameters = v - return s -} - -// SetTier sets the Tier field's value. -func (s *RestoreRequest) SetTier(v string) *RestoreRequest { - s.Tier = &v - return s -} - -// SetType sets the Type field's value. -func (s *RestoreRequest) SetType(v string) *RestoreRequest { - s.Type = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/RoutingRule -type RoutingRule struct { - _ struct{} `type:"structure"` - - // A container for describing a condition that must be met for the specified - // redirect to apply. For example, 1. If request is for pages in the /docs folder, - // redirect to the /documents folder. 2. If request results in HTTP error 4xx, - // redirect request to another host where you might process the error. - Condition *Condition `type:"structure"` - - // Container for redirect information. You can redirect requests to another - // host, to another page, or with another protocol. In the event of an error, - // you can can specify a different error code to return. - // - // Redirect is a required field - Redirect *Redirect `type:"structure" required:"true"` -} - -// String returns the string representation -func (s RoutingRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RoutingRule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RoutingRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RoutingRule"} - if s.Redirect == nil { - invalidParams.Add(request.NewErrParamRequired("Redirect")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCondition sets the Condition field's value. -func (s *RoutingRule) SetCondition(v *Condition) *RoutingRule { - s.Condition = v - return s -} - -// SetRedirect sets the Redirect field's value. -func (s *RoutingRule) SetRedirect(v *Redirect) *RoutingRule { - s.Redirect = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Rule -type Rule struct { - _ struct{} `type:"structure"` - - // Specifies the days since the initiation of an Incomplete Multipart Upload - // that Lifecycle will wait before permanently removing all parts of the upload. - AbortIncompleteMultipartUpload *AbortIncompleteMultipartUpload `type:"structure"` - - Expiration *LifecycleExpiration `type:"structure"` - - // Unique identifier for the rule. The value cannot be longer than 255 characters. - ID *string `type:"string"` - - // Specifies when noncurrent object versions expire. Upon expiration, Amazon - // S3 permanently deletes the noncurrent object versions. You set this lifecycle - // configuration action on a bucket that has versioning enabled (or suspended) - // to request that Amazon S3 delete noncurrent object versions at a specific - // period in the object's lifetime. - NoncurrentVersionExpiration *NoncurrentVersionExpiration `type:"structure"` - - // Container for the transition rule that describes when noncurrent objects - // transition to the STANDARD_IA or GLACIER storage class. If your bucket is - // versioning-enabled (or versioning is suspended), you can set this action - // to request that Amazon S3 transition noncurrent object versions to the STANDARD_IA - // or GLACIER storage class at a specific period in the object's lifetime. - NoncurrentVersionTransition *NoncurrentVersionTransition `type:"structure"` - - // Prefix identifying one or more objects to which the rule applies. - // - // Prefix is a required field - Prefix *string `type:"string" required:"true"` - - // If 'Enabled', the rule is currently being applied. If 'Disabled', the rule - // is not currently being applied. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ExpirationStatus"` - - Transition *Transition `type:"structure"` -} - -// String returns the string representation -func (s Rule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Rule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Rule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Rule"} - if s.Prefix == nil { - invalidParams.Add(request.NewErrParamRequired("Prefix")) - } - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAbortIncompleteMultipartUpload sets the AbortIncompleteMultipartUpload field's value. -func (s *Rule) SetAbortIncompleteMultipartUpload(v *AbortIncompleteMultipartUpload) *Rule { - s.AbortIncompleteMultipartUpload = v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *Rule) SetExpiration(v *LifecycleExpiration) *Rule { - s.Expiration = v - return s -} - -// SetID sets the ID field's value. -func (s *Rule) SetID(v string) *Rule { - s.ID = &v - return s -} - -// SetNoncurrentVersionExpiration sets the NoncurrentVersionExpiration field's value. -func (s *Rule) SetNoncurrentVersionExpiration(v *NoncurrentVersionExpiration) *Rule { - s.NoncurrentVersionExpiration = v - return s -} - -// SetNoncurrentVersionTransition sets the NoncurrentVersionTransition field's value. -func (s *Rule) SetNoncurrentVersionTransition(v *NoncurrentVersionTransition) *Rule { - s.NoncurrentVersionTransition = v - return s -} - -// SetPrefix sets the Prefix field's value. -func (s *Rule) SetPrefix(v string) *Rule { - s.Prefix = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *Rule) SetStatus(v string) *Rule { - s.Status = &v - return s -} - -// SetTransition sets the Transition field's value. -func (s *Rule) SetTransition(v *Transition) *Rule { - s.Transition = v - return s -} - -// Specifies the use of SSE-KMS to encrypt delievered Inventory reports. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SSEKMS -type SSEKMS struct { - _ struct{} `locationName:"SSE-KMS" type:"structure"` - - // Specifies the ID of the AWS Key Management Service (KMS) master encryption - // key to use for encrypting Inventory reports. - // - // KeyId is a required field - KeyId *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s SSEKMS) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s SSEKMS) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *SSEKMS) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SSEKMS"} - if s.KeyId == nil { - invalidParams.Add(request.NewErrParamRequired("KeyId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyId sets the KeyId field's value. -func (s *SSEKMS) SetKeyId(v string) *SSEKMS { - s.KeyId = &v - return s -} - -// Specifies the use of SSE-S3 to encrypt delievered Inventory reports. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SSES3 -type SSES3 struct { - _ struct{} `locationName:"SSE-S3" type:"structure"` -} - -// String returns the string representation -func (s SSES3) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s SSES3) GoString() string { - return s.String() -} - -// Describes the parameters for Select job types. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SelectParameters -type SelectParameters struct { - _ struct{} `type:"structure"` - - // The expression that is used to query the object. - // - // Expression is a required field - Expression *string `type:"string" required:"true"` - - // The type of the provided expression (e.g., SQL). - // - // ExpressionType is a required field - ExpressionType *string `type:"string" required:"true" enum:"ExpressionType"` - - // Describes the serialization format of the object. - // - // InputSerialization is a required field - InputSerialization *InputSerialization `type:"structure" required:"true"` - - // Describes how the results of the Select job are serialized. - // - // OutputSerialization is a required field - OutputSerialization *OutputSerialization `type:"structure" required:"true"` -} - -// String returns the string representation -func (s SelectParameters) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s SelectParameters) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *SelectParameters) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SelectParameters"} - if s.Expression == nil { - invalidParams.Add(request.NewErrParamRequired("Expression")) - } - if s.ExpressionType == nil { - invalidParams.Add(request.NewErrParamRequired("ExpressionType")) - } - if s.InputSerialization == nil { - invalidParams.Add(request.NewErrParamRequired("InputSerialization")) - } - if s.OutputSerialization == nil { - invalidParams.Add(request.NewErrParamRequired("OutputSerialization")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetExpression sets the Expression field's value. -func (s *SelectParameters) SetExpression(v string) *SelectParameters { - s.Expression = &v - return s -} - -// SetExpressionType sets the ExpressionType field's value. -func (s *SelectParameters) SetExpressionType(v string) *SelectParameters { - s.ExpressionType = &v - return s -} - -// SetInputSerialization sets the InputSerialization field's value. -func (s *SelectParameters) SetInputSerialization(v *InputSerialization) *SelectParameters { - s.InputSerialization = v - return s -} - -// SetOutputSerialization sets the OutputSerialization field's value. -func (s *SelectParameters) SetOutputSerialization(v *OutputSerialization) *SelectParameters { - s.OutputSerialization = v - return s -} - -// Describes the default server-side encryption to apply to new objects in the -// bucket. If Put Object request does not specify any server-side encryption, -// this default encryption will be applied. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ServerSideEncryptionByDefault -type ServerSideEncryptionByDefault struct { - _ struct{} `type:"structure"` - - // KMS master key ID to use for the default encryption. This parameter is allowed - // if SSEAlgorithm is aws:kms. - KMSMasterKeyID *string `type:"string"` - - // Server-side encryption algorithm to use for the default encryption. - // - // SSEAlgorithm is a required field - SSEAlgorithm *string `type:"string" required:"true" enum:"ServerSideEncryption"` -} - -// String returns the string representation -func (s ServerSideEncryptionByDefault) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ServerSideEncryptionByDefault) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ServerSideEncryptionByDefault) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionByDefault"} - if s.SSEAlgorithm == nil { - invalidParams.Add(request.NewErrParamRequired("SSEAlgorithm")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKMSMasterKeyID sets the KMSMasterKeyID field's value. -func (s *ServerSideEncryptionByDefault) SetKMSMasterKeyID(v string) *ServerSideEncryptionByDefault { - s.KMSMasterKeyID = &v - return s -} - -// SetSSEAlgorithm sets the SSEAlgorithm field's value. -func (s *ServerSideEncryptionByDefault) SetSSEAlgorithm(v string) *ServerSideEncryptionByDefault { - s.SSEAlgorithm = &v - return s -} - -// Container for server-side encryption configuration rules. Currently S3 supports -// one rule only. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ServerSideEncryptionConfiguration -type ServerSideEncryptionConfiguration struct { - _ struct{} `type:"structure"` - - // Container for information about a particular server-side encryption configuration - // rule. - // - // Rules is a required field - Rules []*ServerSideEncryptionRule `locationName:"Rule" type:"list" flattened:"true" required:"true"` -} - -// String returns the string representation -func (s ServerSideEncryptionConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ServerSideEncryptionConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ServerSideEncryptionConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionConfiguration"} - if s.Rules == nil { - invalidParams.Add(request.NewErrParamRequired("Rules")) - } - if s.Rules != nil { - for i, v := range s.Rules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Rules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetRules sets the Rules field's value. -func (s *ServerSideEncryptionConfiguration) SetRules(v []*ServerSideEncryptionRule) *ServerSideEncryptionConfiguration { - s.Rules = v - return s -} - -// Container for information about a particular server-side encryption configuration -// rule. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/ServerSideEncryptionRule -type ServerSideEncryptionRule struct { - _ struct{} `type:"structure"` - - // Describes the default server-side encryption to apply to new objects in the - // bucket. If Put Object request does not specify any server-side encryption, - // this default encryption will be applied. - ApplyServerSideEncryptionByDefault *ServerSideEncryptionByDefault `type:"structure"` -} - -// String returns the string representation -func (s ServerSideEncryptionRule) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ServerSideEncryptionRule) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ServerSideEncryptionRule) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ServerSideEncryptionRule"} - if s.ApplyServerSideEncryptionByDefault != nil { - if err := s.ApplyServerSideEncryptionByDefault.Validate(); err != nil { - invalidParams.AddNested("ApplyServerSideEncryptionByDefault", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetApplyServerSideEncryptionByDefault sets the ApplyServerSideEncryptionByDefault field's value. -func (s *ServerSideEncryptionRule) SetApplyServerSideEncryptionByDefault(v *ServerSideEncryptionByDefault) *ServerSideEncryptionRule { - s.ApplyServerSideEncryptionByDefault = v - return s -} - -// Container for filters that define which source objects should be replicated. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SourceSelectionCriteria -type SourceSelectionCriteria struct { - _ struct{} `type:"structure"` - - // Container for filter information of selection of KMS Encrypted S3 objects. - SseKmsEncryptedObjects *SseKmsEncryptedObjects `type:"structure"` -} - -// String returns the string representation -func (s SourceSelectionCriteria) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s SourceSelectionCriteria) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *SourceSelectionCriteria) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SourceSelectionCriteria"} - if s.SseKmsEncryptedObjects != nil { - if err := s.SseKmsEncryptedObjects.Validate(); err != nil { - invalidParams.AddNested("SseKmsEncryptedObjects", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetSseKmsEncryptedObjects sets the SseKmsEncryptedObjects field's value. -func (s *SourceSelectionCriteria) SetSseKmsEncryptedObjects(v *SseKmsEncryptedObjects) *SourceSelectionCriteria { - s.SseKmsEncryptedObjects = v - return s -} - -// Container for filter information of selection of KMS Encrypted S3 objects. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/SseKmsEncryptedObjects -type SseKmsEncryptedObjects struct { - _ struct{} `type:"structure"` - - // The replication for KMS encrypted S3 objects is disabled if status is not - // Enabled. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"SseKmsEncryptedObjectsStatus"` -} - -// String returns the string representation -func (s SseKmsEncryptedObjects) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s SseKmsEncryptedObjects) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *SseKmsEncryptedObjects) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "SseKmsEncryptedObjects"} - if s.Status == nil { - invalidParams.Add(request.NewErrParamRequired("Status")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStatus sets the Status field's value. -func (s *SseKmsEncryptedObjects) SetStatus(v string) *SseKmsEncryptedObjects { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysis -type StorageClassAnalysis struct { - _ struct{} `type:"structure"` - - // A container used to describe how data related to the storage class analysis - // should be exported. - DataExport *StorageClassAnalysisDataExport `type:"structure"` -} - -// String returns the string representation -func (s StorageClassAnalysis) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StorageClassAnalysis) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StorageClassAnalysis) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StorageClassAnalysis"} - if s.DataExport != nil { - if err := s.DataExport.Validate(); err != nil { - invalidParams.AddNested("DataExport", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDataExport sets the DataExport field's value. -func (s *StorageClassAnalysis) SetDataExport(v *StorageClassAnalysisDataExport) *StorageClassAnalysis { - s.DataExport = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/StorageClassAnalysisDataExport -type StorageClassAnalysisDataExport struct { - _ struct{} `type:"structure"` - - // The place to store the data for an analysis. - // - // Destination is a required field - Destination *AnalyticsExportDestination `type:"structure" required:"true"` - - // The version of the output schema to use when exporting data. Must be V_1. - // - // OutputSchemaVersion is a required field - OutputSchemaVersion *string `type:"string" required:"true" enum:"StorageClassAnalysisSchemaVersion"` -} - -// String returns the string representation -func (s StorageClassAnalysisDataExport) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StorageClassAnalysisDataExport) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StorageClassAnalysisDataExport) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StorageClassAnalysisDataExport"} - if s.Destination == nil { - invalidParams.Add(request.NewErrParamRequired("Destination")) - } - if s.OutputSchemaVersion == nil { - invalidParams.Add(request.NewErrParamRequired("OutputSchemaVersion")) - } - if s.Destination != nil { - if err := s.Destination.Validate(); err != nil { - invalidParams.AddNested("Destination", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDestination sets the Destination field's value. -func (s *StorageClassAnalysisDataExport) SetDestination(v *AnalyticsExportDestination) *StorageClassAnalysisDataExport { - s.Destination = v - return s -} - -// SetOutputSchemaVersion sets the OutputSchemaVersion field's value. -func (s *StorageClassAnalysisDataExport) SetOutputSchemaVersion(v string) *StorageClassAnalysisDataExport { - s.OutputSchemaVersion = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tag -type Tag struct { - _ struct{} `type:"structure"` - - // Name of the tag. - // - // Key is a required field - Key *string `min:"1" type:"string" required:"true"` - - // Value of the tag. - // - // Value is a required field - Value *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s Tag) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Tag) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Tag) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Tag"} - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKey sets the Key field's value. -func (s *Tag) SetKey(v string) *Tag { - s.Key = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Tag) SetValue(v string) *Tag { - s.Value = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Tagging -type Tagging struct { - _ struct{} `type:"structure"` - - // TagSet is a required field - TagSet []*Tag `locationNameList:"Tag" type:"list" required:"true"` -} - -// String returns the string representation -func (s Tagging) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Tagging) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Tagging) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Tagging"} - if s.TagSet == nil { - invalidParams.Add(request.NewErrParamRequired("TagSet")) - } - if s.TagSet != nil { - for i, v := range s.TagSet { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "TagSet", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetTagSet sets the TagSet field's value. -func (s *Tagging) SetTagSet(v []*Tag) *Tagging { - s.TagSet = v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TargetGrant -type TargetGrant struct { - _ struct{} `type:"structure"` - - Grantee *Grantee `type:"structure" xmlPrefix:"xsi" xmlURI:"http://www.w3.org/2001/XMLSchema-instance"` - - // Logging permissions assigned to the Grantee for the bucket. - Permission *string `type:"string" enum:"BucketLogsPermission"` -} - -// String returns the string representation -func (s TargetGrant) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TargetGrant) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TargetGrant) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TargetGrant"} - if s.Grantee != nil { - if err := s.Grantee.Validate(); err != nil { - invalidParams.AddNested("Grantee", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetGrantee sets the Grantee field's value. -func (s *TargetGrant) SetGrantee(v *Grantee) *TargetGrant { - s.Grantee = v - return s -} - -// SetPermission sets the Permission field's value. -func (s *TargetGrant) SetPermission(v string) *TargetGrant { - s.Permission = &v - return s -} - -// Container for specifying the configuration when you want Amazon S3 to publish -// events to an Amazon Simple Notification Service (Amazon SNS) topic. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfiguration -type TopicConfiguration struct { - _ struct{} `type:"structure"` - - // Events is a required field - Events []*string `locationName:"Event" type:"list" flattened:"true" required:"true"` - - // Container for object key name filtering rules. For information about key - // name filtering, go to Configuring Event Notifications (http://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html) - Filter *NotificationConfigurationFilter `type:"structure"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - // Amazon SNS topic ARN to which Amazon S3 will publish a message when it detects - // events of specified type. - // - // TopicArn is a required field - TopicArn *string `locationName:"Topic" type:"string" required:"true"` -} - -// String returns the string representation -func (s TopicConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TopicConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TopicConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TopicConfiguration"} - if s.Events == nil { - invalidParams.Add(request.NewErrParamRequired("Events")) - } - if s.TopicArn == nil { - invalidParams.Add(request.NewErrParamRequired("TopicArn")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEvents sets the Events field's value. -func (s *TopicConfiguration) SetEvents(v []*string) *TopicConfiguration { - s.Events = v - return s -} - -// SetFilter sets the Filter field's value. -func (s *TopicConfiguration) SetFilter(v *NotificationConfigurationFilter) *TopicConfiguration { - s.Filter = v - return s -} - -// SetId sets the Id field's value. -func (s *TopicConfiguration) SetId(v string) *TopicConfiguration { - s.Id = &v - return s -} - -// SetTopicArn sets the TopicArn field's value. -func (s *TopicConfiguration) SetTopicArn(v string) *TopicConfiguration { - s.TopicArn = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/TopicConfigurationDeprecated -type TopicConfigurationDeprecated struct { - _ struct{} `type:"structure"` - - // Bucket event for which to send notifications. - Event *string `deprecated:"true" type:"string" enum:"Event"` - - Events []*string `locationName:"Event" type:"list" flattened:"true"` - - // Optional unique identifier for configurations in a notification configuration. - // If you don't provide one, Amazon S3 will assign an ID. - Id *string `type:"string"` - - // Amazon SNS topic to which Amazon S3 will publish a message to report the - // specified events for the bucket. - Topic *string `type:"string"` -} - -// String returns the string representation -func (s TopicConfigurationDeprecated) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TopicConfigurationDeprecated) GoString() string { - return s.String() -} - -// SetEvent sets the Event field's value. -func (s *TopicConfigurationDeprecated) SetEvent(v string) *TopicConfigurationDeprecated { - s.Event = &v - return s -} - -// SetEvents sets the Events field's value. -func (s *TopicConfigurationDeprecated) SetEvents(v []*string) *TopicConfigurationDeprecated { - s.Events = v - return s -} - -// SetId sets the Id field's value. -func (s *TopicConfigurationDeprecated) SetId(v string) *TopicConfigurationDeprecated { - s.Id = &v - return s -} - -// SetTopic sets the Topic field's value. -func (s *TopicConfigurationDeprecated) SetTopic(v string) *TopicConfigurationDeprecated { - s.Topic = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/Transition -type Transition struct { - _ struct{} `type:"structure"` - - // Indicates at what date the object is to be moved or deleted. Should be in - // GMT ISO 8601 Format. - Date *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // Indicates the lifetime, in days, of the objects that are subject to the rule. - // The value must be a non-zero positive integer. - Days *int64 `type:"integer"` - - // The class of storage used to store the object. - StorageClass *string `type:"string" enum:"TransitionStorageClass"` -} - -// String returns the string representation -func (s Transition) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Transition) GoString() string { - return s.String() -} - -// SetDate sets the Date field's value. -func (s *Transition) SetDate(v time.Time) *Transition { - s.Date = &v - return s -} - -// SetDays sets the Days field's value. -func (s *Transition) SetDays(v int64) *Transition { - s.Days = &v - return s -} - -// SetStorageClass sets the StorageClass field's value. -func (s *Transition) SetStorageClass(v string) *Transition { - s.StorageClass = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyRequest -type UploadPartCopyInput struct { - _ struct{} `type:"structure"` - - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // The name of the source bucket and key name of the source object, separated - // by a slash (/). Must be URL-encoded. - // - // CopySource is a required field - CopySource *string `location:"header" locationName:"x-amz-copy-source" type:"string" required:"true"` - - // Copies the object if its entity tag (ETag) matches the specified tag. - CopySourceIfMatch *string `location:"header" locationName:"x-amz-copy-source-if-match" type:"string"` - - // Copies the object if it has been modified since the specified time. - CopySourceIfModifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-modified-since" type:"timestamp" timestampFormat:"rfc822"` - - // Copies the object if its entity tag (ETag) is different than the specified - // ETag. - CopySourceIfNoneMatch *string `location:"header" locationName:"x-amz-copy-source-if-none-match" type:"string"` - - // Copies the object if it hasn't been modified since the specified time. - CopySourceIfUnmodifiedSince *time.Time `location:"header" locationName:"x-amz-copy-source-if-unmodified-since" type:"timestamp" timestampFormat:"rfc822"` - - // The range of bytes to copy from the source object. The range value must use - // the form bytes=first-last, where the first and last are the zero-based byte - // offsets to copy. For example, bytes=0-9 indicates that you want to copy the - // first ten bytes of the source. You can copy a range only if the source object - // is greater than 5 GB. - CopySourceRange *string `location:"header" locationName:"x-amz-copy-source-range" type:"string"` - - // Specifies the algorithm to use when decrypting the source object (e.g., AES256). - CopySourceSSECustomerAlgorithm *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use to decrypt - // the source object. The encryption key provided in this header must be one - // that was used when the source object was created. - CopySourceSSECustomerKey *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - CopySourceSSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-copy-source-server-side-encryption-customer-key-MD5" type:"string"` - - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Part number of part being copied. This is a positive integer between 1 and - // 10,000. - // - // PartNumber is a required field - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. This must be the same encryption key specified in the initiate multipart - // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Upload ID identifying the multipart upload whose part is being copied. - // - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` -} - -// String returns the string representation -func (s UploadPartCopyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UploadPartCopyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UploadPartCopyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UploadPartCopyInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.CopySource == nil { - invalidParams.Add(request.NewErrParamRequired("CopySource")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.PartNumber == nil { - invalidParams.Add(request.NewErrParamRequired("PartNumber")) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBucket sets the Bucket field's value. -func (s *UploadPartCopyInput) SetBucket(v string) *UploadPartCopyInput { - s.Bucket = &v - return s -} - -func (s *UploadPartCopyInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetCopySource sets the CopySource field's value. -func (s *UploadPartCopyInput) SetCopySource(v string) *UploadPartCopyInput { - s.CopySource = &v - return s -} - -// SetCopySourceIfMatch sets the CopySourceIfMatch field's value. -func (s *UploadPartCopyInput) SetCopySourceIfMatch(v string) *UploadPartCopyInput { - s.CopySourceIfMatch = &v - return s -} - -// SetCopySourceIfModifiedSince sets the CopySourceIfModifiedSince field's value. -func (s *UploadPartCopyInput) SetCopySourceIfModifiedSince(v time.Time) *UploadPartCopyInput { - s.CopySourceIfModifiedSince = &v - return s -} - -// SetCopySourceIfNoneMatch sets the CopySourceIfNoneMatch field's value. -func (s *UploadPartCopyInput) SetCopySourceIfNoneMatch(v string) *UploadPartCopyInput { - s.CopySourceIfNoneMatch = &v - return s -} - -// SetCopySourceIfUnmodifiedSince sets the CopySourceIfUnmodifiedSince field's value. -func (s *UploadPartCopyInput) SetCopySourceIfUnmodifiedSince(v time.Time) *UploadPartCopyInput { - s.CopySourceIfUnmodifiedSince = &v - return s -} - -// SetCopySourceRange sets the CopySourceRange field's value. -func (s *UploadPartCopyInput) SetCopySourceRange(v string) *UploadPartCopyInput { - s.CopySourceRange = &v - return s -} - -// SetCopySourceSSECustomerAlgorithm sets the CopySourceSSECustomerAlgorithm field's value. -func (s *UploadPartCopyInput) SetCopySourceSSECustomerAlgorithm(v string) *UploadPartCopyInput { - s.CopySourceSSECustomerAlgorithm = &v - return s -} - -// SetCopySourceSSECustomerKey sets the CopySourceSSECustomerKey field's value. -func (s *UploadPartCopyInput) SetCopySourceSSECustomerKey(v string) *UploadPartCopyInput { - s.CopySourceSSECustomerKey = &v - return s -} - -func (s *UploadPartCopyInput) getCopySourceSSECustomerKey() (v string) { - if s.CopySourceSSECustomerKey == nil { - return v - } - return *s.CopySourceSSECustomerKey -} - -// SetCopySourceSSECustomerKeyMD5 sets the CopySourceSSECustomerKeyMD5 field's value. -func (s *UploadPartCopyInput) SetCopySourceSSECustomerKeyMD5(v string) *UploadPartCopyInput { - s.CopySourceSSECustomerKeyMD5 = &v - return s -} - -// SetKey sets the Key field's value. -func (s *UploadPartCopyInput) SetKey(v string) *UploadPartCopyInput { - s.Key = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *UploadPartCopyInput) SetPartNumber(v int64) *UploadPartCopyInput { - s.PartNumber = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *UploadPartCopyInput) SetRequestPayer(v string) *UploadPartCopyInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *UploadPartCopyInput) SetSSECustomerAlgorithm(v string) *UploadPartCopyInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *UploadPartCopyInput) SetSSECustomerKey(v string) *UploadPartCopyInput { - s.SSECustomerKey = &v - return s -} - -func (s *UploadPartCopyInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *UploadPartCopyInput) SetSSECustomerKeyMD5(v string) *UploadPartCopyInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *UploadPartCopyInput) SetUploadId(v string) *UploadPartCopyInput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartCopyOutput -type UploadPartCopyOutput struct { - _ struct{} `type:"structure" payload:"CopyPartResult"` - - CopyPartResult *CopyPartResult `type:"structure"` - - // The version of the source object that was copied, if you have enabled versioning - // on the source bucket. - CopySourceVersionId *string `location:"header" locationName:"x-amz-copy-source-version-id" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` -} - -// String returns the string representation -func (s UploadPartCopyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UploadPartCopyOutput) GoString() string { - return s.String() -} - -// SetCopyPartResult sets the CopyPartResult field's value. -func (s *UploadPartCopyOutput) SetCopyPartResult(v *CopyPartResult) *UploadPartCopyOutput { - s.CopyPartResult = v - return s -} - -// SetCopySourceVersionId sets the CopySourceVersionId field's value. -func (s *UploadPartCopyOutput) SetCopySourceVersionId(v string) *UploadPartCopyOutput { - s.CopySourceVersionId = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *UploadPartCopyOutput) SetRequestCharged(v string) *UploadPartCopyOutput { - s.RequestCharged = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *UploadPartCopyOutput) SetSSECustomerAlgorithm(v string) *UploadPartCopyOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *UploadPartCopyOutput) SetSSECustomerKeyMD5(v string) *UploadPartCopyOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *UploadPartCopyOutput) SetSSEKMSKeyId(v string) *UploadPartCopyOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *UploadPartCopyOutput) SetServerSideEncryption(v string) *UploadPartCopyOutput { - s.ServerSideEncryption = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartRequest -type UploadPartInput struct { - _ struct{} `type:"structure" payload:"Body"` - - // Object data. - Body io.ReadSeeker `type:"blob"` - - // Name of the bucket to which the multipart upload was initiated. - // - // Bucket is a required field - Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` - - // Size of the body in bytes. This parameter is useful when the size of the - // body cannot be determined automatically. - ContentLength *int64 `location:"header" locationName:"Content-Length" type:"long"` - - // The base64-encoded 128-bit MD5 digest of the part data. - ContentMD5 *string `location:"header" locationName:"Content-MD5" type:"string"` - - // Object key for which the multipart upload was initiated. - // - // Key is a required field - Key *string `location:"uri" locationName:"Key" min:"1" type:"string" required:"true"` - - // Part number of part being uploaded. This is a positive integer between 1 - // and 10,000. - // - // PartNumber is a required field - PartNumber *int64 `location:"querystring" locationName:"partNumber" type:"integer" required:"true"` - - // Confirms that the requester knows that she or he will be charged for the - // request. Bucket owners need not specify this parameter in their requests. - // Documentation on downloading objects from requester pays buckets can be found - // at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html - RequestPayer *string `location:"header" locationName:"x-amz-request-payer" type:"string" enum:"RequestPayer"` - - // Specifies the algorithm to use to when encrypting the object (e.g., AES256). - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // Specifies the customer-provided encryption key for Amazon S3 to use in encrypting - // data. This value is used to store the object and then it is discarded; Amazon - // does not store the encryption key. The key must be appropriate for use with - // the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm - // header. This must be the same encryption key specified in the initiate multipart - // upload request. - SSECustomerKey *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key" type:"string"` - - // Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. - // Amazon S3 uses this header for a message integrity check to ensure the encryption - // key was transmitted without error. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // Upload ID identifying the multipart upload whose part is being uploaded. - // - // UploadId is a required field - UploadId *string `location:"querystring" locationName:"uploadId" type:"string" required:"true"` -} - -// String returns the string representation -func (s UploadPartInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UploadPartInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UploadPartInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UploadPartInput"} - if s.Bucket == nil { - invalidParams.Add(request.NewErrParamRequired("Bucket")) - } - if s.Key == nil { - invalidParams.Add(request.NewErrParamRequired("Key")) - } - if s.Key != nil && len(*s.Key) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Key", 1)) - } - if s.PartNumber == nil { - invalidParams.Add(request.NewErrParamRequired("PartNumber")) - } - if s.UploadId == nil { - invalidParams.Add(request.NewErrParamRequired("UploadId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetBody sets the Body field's value. -func (s *UploadPartInput) SetBody(v io.ReadSeeker) *UploadPartInput { - s.Body = v - return s -} - -// SetBucket sets the Bucket field's value. -func (s *UploadPartInput) SetBucket(v string) *UploadPartInput { - s.Bucket = &v - return s -} - -func (s *UploadPartInput) getBucket() (v string) { - if s.Bucket == nil { - return v - } - return *s.Bucket -} - -// SetContentLength sets the ContentLength field's value. -func (s *UploadPartInput) SetContentLength(v int64) *UploadPartInput { - s.ContentLength = &v - return s -} - -// SetContentMD5 sets the ContentMD5 field's value. -func (s *UploadPartInput) SetContentMD5(v string) *UploadPartInput { - s.ContentMD5 = &v - return s -} - -// SetKey sets the Key field's value. -func (s *UploadPartInput) SetKey(v string) *UploadPartInput { - s.Key = &v - return s -} - -// SetPartNumber sets the PartNumber field's value. -func (s *UploadPartInput) SetPartNumber(v int64) *UploadPartInput { - s.PartNumber = &v - return s -} - -// SetRequestPayer sets the RequestPayer field's value. -func (s *UploadPartInput) SetRequestPayer(v string) *UploadPartInput { - s.RequestPayer = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *UploadPartInput) SetSSECustomerAlgorithm(v string) *UploadPartInput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKey sets the SSECustomerKey field's value. -func (s *UploadPartInput) SetSSECustomerKey(v string) *UploadPartInput { - s.SSECustomerKey = &v - return s -} - -func (s *UploadPartInput) getSSECustomerKey() (v string) { - if s.SSECustomerKey == nil { - return v - } - return *s.SSECustomerKey -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *UploadPartInput) SetSSECustomerKeyMD5(v string) *UploadPartInput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetUploadId sets the UploadId field's value. -func (s *UploadPartInput) SetUploadId(v string) *UploadPartInput { - s.UploadId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/UploadPartOutput -type UploadPartOutput struct { - _ struct{} `type:"structure"` - - // Entity tag for the uploaded object. - ETag *string `location:"header" locationName:"ETag" type:"string"` - - // If present, indicates that the requester was successfully charged for the - // request. - RequestCharged *string `location:"header" locationName:"x-amz-request-charged" type:"string" enum:"RequestCharged"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header confirming the encryption algorithm - // used. - SSECustomerAlgorithm *string `location:"header" locationName:"x-amz-server-side-encryption-customer-algorithm" type:"string"` - - // If server-side encryption with a customer-provided encryption key was requested, - // the response will include this header to provide round trip message integrity - // verification of the customer-provided encryption key. - SSECustomerKeyMD5 *string `location:"header" locationName:"x-amz-server-side-encryption-customer-key-MD5" type:"string"` - - // If present, specifies the ID of the AWS Key Management Service (KMS) master - // encryption key that was used for the object. - SSEKMSKeyId *string `location:"header" locationName:"x-amz-server-side-encryption-aws-kms-key-id" type:"string"` - - // The Server-side encryption algorithm used when storing this object in S3 - // (e.g., AES256, aws:kms). - ServerSideEncryption *string `location:"header" locationName:"x-amz-server-side-encryption" type:"string" enum:"ServerSideEncryption"` -} - -// String returns the string representation -func (s UploadPartOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UploadPartOutput) GoString() string { - return s.String() -} - -// SetETag sets the ETag field's value. -func (s *UploadPartOutput) SetETag(v string) *UploadPartOutput { - s.ETag = &v - return s -} - -// SetRequestCharged sets the RequestCharged field's value. -func (s *UploadPartOutput) SetRequestCharged(v string) *UploadPartOutput { - s.RequestCharged = &v - return s -} - -// SetSSECustomerAlgorithm sets the SSECustomerAlgorithm field's value. -func (s *UploadPartOutput) SetSSECustomerAlgorithm(v string) *UploadPartOutput { - s.SSECustomerAlgorithm = &v - return s -} - -// SetSSECustomerKeyMD5 sets the SSECustomerKeyMD5 field's value. -func (s *UploadPartOutput) SetSSECustomerKeyMD5(v string) *UploadPartOutput { - s.SSECustomerKeyMD5 = &v - return s -} - -// SetSSEKMSKeyId sets the SSEKMSKeyId field's value. -func (s *UploadPartOutput) SetSSEKMSKeyId(v string) *UploadPartOutput { - s.SSEKMSKeyId = &v - return s -} - -// SetServerSideEncryption sets the ServerSideEncryption field's value. -func (s *UploadPartOutput) SetServerSideEncryption(v string) *UploadPartOutput { - s.ServerSideEncryption = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/VersioningConfiguration -type VersioningConfiguration struct { - _ struct{} `type:"structure"` - - // Specifies whether MFA delete is enabled in the bucket versioning configuration. - // This element is only returned if the bucket has been configured with MFA - // delete. If the bucket has never been so configured, this element is not returned. - MFADelete *string `locationName:"MfaDelete" type:"string" enum:"MFADelete"` - - // The versioning state of the bucket. - Status *string `type:"string" enum:"BucketVersioningStatus"` -} - -// String returns the string representation -func (s VersioningConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s VersioningConfiguration) GoString() string { - return s.String() -} - -// SetMFADelete sets the MFADelete field's value. -func (s *VersioningConfiguration) SetMFADelete(v string) *VersioningConfiguration { - s.MFADelete = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *VersioningConfiguration) SetStatus(v string) *VersioningConfiguration { - s.Status = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/WebsiteConfiguration -type WebsiteConfiguration struct { - _ struct{} `type:"structure"` - - ErrorDocument *ErrorDocument `type:"structure"` - - IndexDocument *IndexDocument `type:"structure"` - - RedirectAllRequestsTo *RedirectAllRequestsTo `type:"structure"` - - RoutingRules []*RoutingRule `locationNameList:"RoutingRule" type:"list"` -} - -// String returns the string representation -func (s WebsiteConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s WebsiteConfiguration) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *WebsiteConfiguration) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "WebsiteConfiguration"} - if s.ErrorDocument != nil { - if err := s.ErrorDocument.Validate(); err != nil { - invalidParams.AddNested("ErrorDocument", err.(request.ErrInvalidParams)) - } - } - if s.IndexDocument != nil { - if err := s.IndexDocument.Validate(); err != nil { - invalidParams.AddNested("IndexDocument", err.(request.ErrInvalidParams)) - } - } - if s.RedirectAllRequestsTo != nil { - if err := s.RedirectAllRequestsTo.Validate(); err != nil { - invalidParams.AddNested("RedirectAllRequestsTo", err.(request.ErrInvalidParams)) - } - } - if s.RoutingRules != nil { - for i, v := range s.RoutingRules { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "RoutingRules", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetErrorDocument sets the ErrorDocument field's value. -func (s *WebsiteConfiguration) SetErrorDocument(v *ErrorDocument) *WebsiteConfiguration { - s.ErrorDocument = v - return s -} - -// SetIndexDocument sets the IndexDocument field's value. -func (s *WebsiteConfiguration) SetIndexDocument(v *IndexDocument) *WebsiteConfiguration { - s.IndexDocument = v - return s -} - -// SetRedirectAllRequestsTo sets the RedirectAllRequestsTo field's value. -func (s *WebsiteConfiguration) SetRedirectAllRequestsTo(v *RedirectAllRequestsTo) *WebsiteConfiguration { - s.RedirectAllRequestsTo = v - return s -} - -// SetRoutingRules sets the RoutingRules field's value. -func (s *WebsiteConfiguration) SetRoutingRules(v []*RoutingRule) *WebsiteConfiguration { - s.RoutingRules = v - return s -} - -const ( - // AnalyticsS3ExportFileFormatCsv is a AnalyticsS3ExportFileFormat enum value - AnalyticsS3ExportFileFormatCsv = "CSV" -) - -const ( - // BucketAccelerateStatusEnabled is a BucketAccelerateStatus enum value - BucketAccelerateStatusEnabled = "Enabled" - - // BucketAccelerateStatusSuspended is a BucketAccelerateStatus enum value - BucketAccelerateStatusSuspended = "Suspended" -) - -const ( - // BucketCannedACLPrivate is a BucketCannedACL enum value - BucketCannedACLPrivate = "private" - - // BucketCannedACLPublicRead is a BucketCannedACL enum value - BucketCannedACLPublicRead = "public-read" - - // BucketCannedACLPublicReadWrite is a BucketCannedACL enum value - BucketCannedACLPublicReadWrite = "public-read-write" - - // BucketCannedACLAuthenticatedRead is a BucketCannedACL enum value - BucketCannedACLAuthenticatedRead = "authenticated-read" -) - -const ( - // BucketLocationConstraintEu is a BucketLocationConstraint enum value - BucketLocationConstraintEu = "EU" - - // BucketLocationConstraintEuWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintEuWest1 = "eu-west-1" - - // BucketLocationConstraintUsWest1 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest1 = "us-west-1" - - // BucketLocationConstraintUsWest2 is a BucketLocationConstraint enum value - BucketLocationConstraintUsWest2 = "us-west-2" - - // BucketLocationConstraintApSouth1 is a BucketLocationConstraint enum value - BucketLocationConstraintApSouth1 = "ap-south-1" - - // BucketLocationConstraintApSoutheast1 is a BucketLocationConstraint enum value - BucketLocationConstraintApSoutheast1 = "ap-southeast-1" - - // BucketLocationConstraintApSoutheast2 is a BucketLocationConstraint enum value - BucketLocationConstraintApSoutheast2 = "ap-southeast-2" - - // BucketLocationConstraintApNortheast1 is a BucketLocationConstraint enum value - BucketLocationConstraintApNortheast1 = "ap-northeast-1" - - // BucketLocationConstraintSaEast1 is a BucketLocationConstraint enum value - BucketLocationConstraintSaEast1 = "sa-east-1" - - // BucketLocationConstraintCnNorth1 is a BucketLocationConstraint enum value - BucketLocationConstraintCnNorth1 = "cn-north-1" - - // BucketLocationConstraintEuCentral1 is a BucketLocationConstraint enum value - BucketLocationConstraintEuCentral1 = "eu-central-1" -) - -const ( - // BucketLogsPermissionFullControl is a BucketLogsPermission enum value - BucketLogsPermissionFullControl = "FULL_CONTROL" - - // BucketLogsPermissionRead is a BucketLogsPermission enum value - BucketLogsPermissionRead = "READ" - - // BucketLogsPermissionWrite is a BucketLogsPermission enum value - BucketLogsPermissionWrite = "WRITE" -) - -const ( - // BucketVersioningStatusEnabled is a BucketVersioningStatus enum value - BucketVersioningStatusEnabled = "Enabled" - - // BucketVersioningStatusSuspended is a BucketVersioningStatus enum value - BucketVersioningStatusSuspended = "Suspended" -) - -// Requests Amazon S3 to encode the object keys in the response and specifies -// the encoding method to use. An object key may contain any Unicode character; -// however, XML 1.0 parser cannot parse some characters, such as characters -// with an ASCII value from 0 to 10. For characters that are not supported in -// XML 1.0, you can add this parameter to request that Amazon S3 encode the -// keys in the response. -const ( - // EncodingTypeUrl is a EncodingType enum value - EncodingTypeUrl = "url" -) - -// Bucket event for which to send notifications. -const ( - // EventS3ReducedRedundancyLostObject is a Event enum value - EventS3ReducedRedundancyLostObject = "s3:ReducedRedundancyLostObject" - - // EventS3ObjectCreated is a Event enum value - EventS3ObjectCreated = "s3:ObjectCreated:*" - - // EventS3ObjectCreatedPut is a Event enum value - EventS3ObjectCreatedPut = "s3:ObjectCreated:Put" - - // EventS3ObjectCreatedPost is a Event enum value - EventS3ObjectCreatedPost = "s3:ObjectCreated:Post" - - // EventS3ObjectCreatedCopy is a Event enum value - EventS3ObjectCreatedCopy = "s3:ObjectCreated:Copy" - - // EventS3ObjectCreatedCompleteMultipartUpload is a Event enum value - EventS3ObjectCreatedCompleteMultipartUpload = "s3:ObjectCreated:CompleteMultipartUpload" - - // EventS3ObjectRemoved is a Event enum value - EventS3ObjectRemoved = "s3:ObjectRemoved:*" - - // EventS3ObjectRemovedDelete is a Event enum value - EventS3ObjectRemovedDelete = "s3:ObjectRemoved:Delete" - - // EventS3ObjectRemovedDeleteMarkerCreated is a Event enum value - EventS3ObjectRemovedDeleteMarkerCreated = "s3:ObjectRemoved:DeleteMarkerCreated" -) - -const ( - // ExpirationStatusEnabled is a ExpirationStatus enum value - ExpirationStatusEnabled = "Enabled" - - // ExpirationStatusDisabled is a ExpirationStatus enum value - ExpirationStatusDisabled = "Disabled" -) - -const ( - // ExpressionTypeSql is a ExpressionType enum value - ExpressionTypeSql = "SQL" -) - -const ( - // FileHeaderInfoUse is a FileHeaderInfo enum value - FileHeaderInfoUse = "USE" - - // FileHeaderInfoIgnore is a FileHeaderInfo enum value - FileHeaderInfoIgnore = "IGNORE" - - // FileHeaderInfoNone is a FileHeaderInfo enum value - FileHeaderInfoNone = "NONE" -) - -const ( - // FilterRuleNamePrefix is a FilterRuleName enum value - FilterRuleNamePrefix = "prefix" - - // FilterRuleNameSuffix is a FilterRuleName enum value - FilterRuleNameSuffix = "suffix" -) - -const ( - // InventoryFormatCsv is a InventoryFormat enum value - InventoryFormatCsv = "CSV" - - // InventoryFormatOrc is a InventoryFormat enum value - InventoryFormatOrc = "ORC" -) - -const ( - // InventoryFrequencyDaily is a InventoryFrequency enum value - InventoryFrequencyDaily = "Daily" - - // InventoryFrequencyWeekly is a InventoryFrequency enum value - InventoryFrequencyWeekly = "Weekly" -) - -const ( - // InventoryIncludedObjectVersionsAll is a InventoryIncludedObjectVersions enum value - InventoryIncludedObjectVersionsAll = "All" - - // InventoryIncludedObjectVersionsCurrent is a InventoryIncludedObjectVersions enum value - InventoryIncludedObjectVersionsCurrent = "Current" -) - -const ( - // InventoryOptionalFieldSize is a InventoryOptionalField enum value - InventoryOptionalFieldSize = "Size" - - // InventoryOptionalFieldLastModifiedDate is a InventoryOptionalField enum value - InventoryOptionalFieldLastModifiedDate = "LastModifiedDate" - - // InventoryOptionalFieldStorageClass is a InventoryOptionalField enum value - InventoryOptionalFieldStorageClass = "StorageClass" - - // InventoryOptionalFieldEtag is a InventoryOptionalField enum value - InventoryOptionalFieldEtag = "ETag" - - // InventoryOptionalFieldIsMultipartUploaded is a InventoryOptionalField enum value - InventoryOptionalFieldIsMultipartUploaded = "IsMultipartUploaded" - - // InventoryOptionalFieldReplicationStatus is a InventoryOptionalField enum value - InventoryOptionalFieldReplicationStatus = "ReplicationStatus" - - // InventoryOptionalFieldEncryptionStatus is a InventoryOptionalField enum value - InventoryOptionalFieldEncryptionStatus = "EncryptionStatus" -) - -const ( - // MFADeleteEnabled is a MFADelete enum value - MFADeleteEnabled = "Enabled" - - // MFADeleteDisabled is a MFADelete enum value - MFADeleteDisabled = "Disabled" -) - -const ( - // MFADeleteStatusEnabled is a MFADeleteStatus enum value - MFADeleteStatusEnabled = "Enabled" - - // MFADeleteStatusDisabled is a MFADeleteStatus enum value - MFADeleteStatusDisabled = "Disabled" -) - -const ( - // MetadataDirectiveCopy is a MetadataDirective enum value - MetadataDirectiveCopy = "COPY" - - // MetadataDirectiveReplace is a MetadataDirective enum value - MetadataDirectiveReplace = "REPLACE" -) - -const ( - // ObjectCannedACLPrivate is a ObjectCannedACL enum value - ObjectCannedACLPrivate = "private" - - // ObjectCannedACLPublicRead is a ObjectCannedACL enum value - ObjectCannedACLPublicRead = "public-read" - - // ObjectCannedACLPublicReadWrite is a ObjectCannedACL enum value - ObjectCannedACLPublicReadWrite = "public-read-write" - - // ObjectCannedACLAuthenticatedRead is a ObjectCannedACL enum value - ObjectCannedACLAuthenticatedRead = "authenticated-read" - - // ObjectCannedACLAwsExecRead is a ObjectCannedACL enum value - ObjectCannedACLAwsExecRead = "aws-exec-read" - - // ObjectCannedACLBucketOwnerRead is a ObjectCannedACL enum value - ObjectCannedACLBucketOwnerRead = "bucket-owner-read" - - // ObjectCannedACLBucketOwnerFullControl is a ObjectCannedACL enum value - ObjectCannedACLBucketOwnerFullControl = "bucket-owner-full-control" -) - -const ( - // ObjectStorageClassStandard is a ObjectStorageClass enum value - ObjectStorageClassStandard = "STANDARD" - - // ObjectStorageClassReducedRedundancy is a ObjectStorageClass enum value - ObjectStorageClassReducedRedundancy = "REDUCED_REDUNDANCY" - - // ObjectStorageClassGlacier is a ObjectStorageClass enum value - ObjectStorageClassGlacier = "GLACIER" -) - -const ( - // ObjectVersionStorageClassStandard is a ObjectVersionStorageClass enum value - ObjectVersionStorageClassStandard = "STANDARD" -) - -const ( - // OwnerOverrideDestination is a OwnerOverride enum value - OwnerOverrideDestination = "Destination" -) - -const ( - // PayerRequester is a Payer enum value - PayerRequester = "Requester" - - // PayerBucketOwner is a Payer enum value - PayerBucketOwner = "BucketOwner" -) - -const ( - // PermissionFullControl is a Permission enum value - PermissionFullControl = "FULL_CONTROL" - - // PermissionWrite is a Permission enum value - PermissionWrite = "WRITE" - - // PermissionWriteAcp is a Permission enum value - PermissionWriteAcp = "WRITE_ACP" - - // PermissionRead is a Permission enum value - PermissionRead = "READ" - - // PermissionReadAcp is a Permission enum value - PermissionReadAcp = "READ_ACP" -) - -const ( - // ProtocolHttp is a Protocol enum value - ProtocolHttp = "http" - - // ProtocolHttps is a Protocol enum value - ProtocolHttps = "https" -) - -const ( - // QuoteFieldsAlways is a QuoteFields enum value - QuoteFieldsAlways = "ALWAYS" - - // QuoteFieldsAsneeded is a QuoteFields enum value - QuoteFieldsAsneeded = "ASNEEDED" -) - -const ( - // ReplicationRuleStatusEnabled is a ReplicationRuleStatus enum value - ReplicationRuleStatusEnabled = "Enabled" - - // ReplicationRuleStatusDisabled is a ReplicationRuleStatus enum value - ReplicationRuleStatusDisabled = "Disabled" -) - -const ( - // ReplicationStatusComplete is a ReplicationStatus enum value - ReplicationStatusComplete = "COMPLETE" - - // ReplicationStatusPending is a ReplicationStatus enum value - ReplicationStatusPending = "PENDING" - - // ReplicationStatusFailed is a ReplicationStatus enum value - ReplicationStatusFailed = "FAILED" - - // ReplicationStatusReplica is a ReplicationStatus enum value - ReplicationStatusReplica = "REPLICA" -) - -// If present, indicates that the requester was successfully charged for the -// request. -const ( - // RequestChargedRequester is a RequestCharged enum value - RequestChargedRequester = "requester" -) - -// Confirms that the requester knows that she or he will be charged for the -// request. Bucket owners need not specify this parameter in their requests. -// Documentation on downloading objects from requester pays buckets can be found -// at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html -const ( - // RequestPayerRequester is a RequestPayer enum value - RequestPayerRequester = "requester" -) - -const ( - // RestoreRequestTypeSelect is a RestoreRequestType enum value - RestoreRequestTypeSelect = "SELECT" -) - -const ( - // ServerSideEncryptionAes256 is a ServerSideEncryption enum value - ServerSideEncryptionAes256 = "AES256" - - // ServerSideEncryptionAwsKms is a ServerSideEncryption enum value - ServerSideEncryptionAwsKms = "aws:kms" -) - -const ( - // SseKmsEncryptedObjectsStatusEnabled is a SseKmsEncryptedObjectsStatus enum value - SseKmsEncryptedObjectsStatusEnabled = "Enabled" - - // SseKmsEncryptedObjectsStatusDisabled is a SseKmsEncryptedObjectsStatus enum value - SseKmsEncryptedObjectsStatusDisabled = "Disabled" -) - -const ( - // StorageClassStandard is a StorageClass enum value - StorageClassStandard = "STANDARD" - - // StorageClassReducedRedundancy is a StorageClass enum value - StorageClassReducedRedundancy = "REDUCED_REDUNDANCY" - - // StorageClassStandardIa is a StorageClass enum value - StorageClassStandardIa = "STANDARD_IA" -) - -const ( - // StorageClassAnalysisSchemaVersionV1 is a StorageClassAnalysisSchemaVersion enum value - StorageClassAnalysisSchemaVersionV1 = "V_1" -) - -const ( - // TaggingDirectiveCopy is a TaggingDirective enum value - TaggingDirectiveCopy = "COPY" - - // TaggingDirectiveReplace is a TaggingDirective enum value - TaggingDirectiveReplace = "REPLACE" -) - -const ( - // TierStandard is a Tier enum value - TierStandard = "Standard" - - // TierBulk is a Tier enum value - TierBulk = "Bulk" - - // TierExpedited is a Tier enum value - TierExpedited = "Expedited" -) - -const ( - // TransitionStorageClassGlacier is a TransitionStorageClass enum value - TransitionStorageClassGlacier = "GLACIER" - - // TransitionStorageClassStandardIa is a TransitionStorageClass enum value - TransitionStorageClassStandardIa = "STANDARD_IA" -) - -const ( - // TypeCanonicalUser is a Type enum value - TypeCanonicalUser = "CanonicalUser" - - // TypeAmazonCustomerByEmail is a Type enum value - TypeAmazonCustomerByEmail = "AmazonCustomerByEmail" - - // TypeGroup is a Type enum value - TypeGroup = "Group" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go b/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go deleted file mode 100644 index bc68a46acf..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/bucket_location.go +++ /dev/null @@ -1,106 +0,0 @@ -package s3 - -import ( - "io/ioutil" - "regexp" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`) - -// NormalizeBucketLocation is a utility function which will update the -// passed in value to always be a region ID. Generally this would be used -// with GetBucketLocation API operation. -// -// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". -// -// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html -// for more information on the values that can be returned. -func NormalizeBucketLocation(loc string) string { - switch loc { - case "": - loc = "us-east-1" - case "EU": - loc = "eu-west-1" - } - - return loc -} - -// NormalizeBucketLocationHandler is a request handler which will update the -// GetBucketLocation's result LocationConstraint value to always be a region ID. -// -// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". -// -// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html -// for more information on the values that can be returned. -// -// req, result := svc.GetBucketLocationRequest(&s3.GetBucketLocationInput{ -// Bucket: aws.String(bucket), -// }) -// req.Handlers.Unmarshal.PushBackNamed(NormalizeBucketLocationHandler) -// err := req.Send() -var NormalizeBucketLocationHandler = request.NamedHandler{ - Name: "awssdk.s3.NormalizeBucketLocation", - Fn: func(req *request.Request) { - if req.Error != nil { - return - } - - out := req.Data.(*GetBucketLocationOutput) - loc := NormalizeBucketLocation(aws.StringValue(out.LocationConstraint)) - out.LocationConstraint = aws.String(loc) - }, -} - -// WithNormalizeBucketLocation is a request option which will update the -// GetBucketLocation's result LocationConstraint value to always be a region ID. -// -// Replaces empty string with "us-east-1", and "EU" with "eu-west-1". -// -// See http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html -// for more information on the values that can be returned. -// -// result, err := svc.GetBucketLocationWithContext(ctx, -// &s3.GetBucketLocationInput{ -// Bucket: aws.String(bucket), -// }, -// s3.WithNormalizeBucketLocation, -// ) -func WithNormalizeBucketLocation(r *request.Request) { - r.Handlers.Unmarshal.PushBackNamed(NormalizeBucketLocationHandler) -} - -func buildGetBucketLocation(r *request.Request) { - if r.DataFilled() { - out := r.Data.(*GetBucketLocationOutput) - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed reading response body", err) - return - } - - match := reBucketLocation.FindSubmatch(b) - if len(match) > 1 { - loc := string(match[1]) - out.LocationConstraint = aws.String(loc) - } - } -} - -func populateLocationConstraint(r *request.Request) { - if r.ParamsFilled() && aws.StringValue(r.Config.Region) != "us-east-1" { - in := r.Params.(*CreateBucketInput) - if in.CreateBucketConfiguration == nil { - r.Params = awsutil.CopyOf(r.Params) - in = r.Params.(*CreateBucketInput) - in.CreateBucketConfiguration = &CreateBucketConfiguration{ - LocationConstraint: r.Config.Region, - } - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go b/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go deleted file mode 100644 index 9fc5df94d3..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/content_md5.go +++ /dev/null @@ -1,36 +0,0 @@ -package s3 - -import ( - "crypto/md5" - "encoding/base64" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// contentMD5 computes and sets the HTTP Content-MD5 header for requests that -// require it. -func contentMD5(r *request.Request) { - h := md5.New() - - // hash the body. seek back to the first position after reading to reset - // the body for transmission. copy errors may be assumed to be from the - // body. - _, err := io.Copy(h, r.Body) - if err != nil { - r.Error = awserr.New("ContentMD5", "failed to read body", err) - return - } - _, err = r.Body.Seek(0, 0) - if err != nil { - r.Error = awserr.New("ContentMD5", "failed to seek body", err) - return - } - - // encode the md5 checksum in base64 and set the request header. - sum := h.Sum(nil) - sum64 := make([]byte, base64.StdEncoding.EncodedLen(len(sum))) - base64.StdEncoding.Encode(sum64, sum) - r.HTTPRequest.Header.Set("Content-MD5", string(sum64)) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go deleted file mode 100644 index 899d5e8d10..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ /dev/null @@ -1,64 +0,0 @@ -package s3 - -import ( - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" -) - -func init() { - initClient = defaultInitClientFn - initRequest = defaultInitRequestFn -} - -func defaultInitClientFn(c *client.Client) { - // Support building custom endpoints based on config - c.Handlers.Build.PushFront(updateEndpointForS3Config) - - // Require SSL when using SSE keys - c.Handlers.Validate.PushBack(validateSSERequiresSSL) - c.Handlers.Build.PushBack(computeSSEKeys) - - // S3 uses custom error unmarshaling logic - c.Handlers.UnmarshalError.Clear() - c.Handlers.UnmarshalError.PushBack(unmarshalError) -} - -func defaultInitRequestFn(r *request.Request) { - // Add reuest handlers for specific platforms. - // e.g. 100-continue support for PUT requests using Go 1.6 - platformRequestHandlers(r) - - switch r.Operation.Name { - case opPutBucketCors, opPutBucketLifecycle, opPutBucketPolicy, - opPutBucketTagging, opDeleteObjects, opPutBucketLifecycleConfiguration, - opPutBucketReplication: - // These S3 operations require Content-MD5 to be set - r.Handlers.Build.PushBack(contentMD5) - case opGetBucketLocation: - // GetBucketLocation has custom parsing logic - r.Handlers.Unmarshal.PushFront(buildGetBucketLocation) - case opCreateBucket: - // Auto-populate LocationConstraint with current region - r.Handlers.Validate.PushFront(populateLocationConstraint) - case opCopyObject, opUploadPartCopy, opCompleteMultipartUpload: - r.Handlers.Unmarshal.PushFront(copyMultipartStatusOKUnmarhsalError) - } -} - -// bucketGetter is an accessor interface to grab the "Bucket" field from -// an S3 type. -type bucketGetter interface { - getBucket() string -} - -// sseCustomerKeyGetter is an accessor interface to grab the "SSECustomerKey" -// field from an S3 type. -type sseCustomerKeyGetter interface { - getSSECustomerKey() string -} - -// copySourceSSECustomerKeyGetter is an accessor interface to grab the -// "CopySourceSSECustomerKey" field from an S3 type. -type copySourceSSECustomerKeyGetter interface { - getCopySourceSSECustomerKey() string -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go deleted file mode 100644 index 0def02255a..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package s3 provides the client and types for making API -// requests to Amazon Simple Storage Service. -// -// See https://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01 for more information on this service. -// -// See s3 package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/ -// -// Using the Client -// -// To contact Amazon Simple Storage Service with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon Simple Storage Service client S3 for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/#New -package s3 diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go b/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go deleted file mode 100644 index 39b912c260..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/doc_custom.go +++ /dev/null @@ -1,109 +0,0 @@ -// Upload Managers -// -// The s3manager package's Uploader provides concurrent upload of content to S3 -// by taking advantage of S3's Multipart APIs. The Uploader also supports both -// io.Reader for streaming uploads, and will also take advantage of io.ReadSeeker -// for optimizations if the Body satisfies that type. Once the Uploader instance -// is created you can call Upload concurrently from multiple goroutines safely. -// -// // The session the S3 Uploader will use -// sess := session.Must(session.NewSession()) -// -// // Create an uploader with the session and default options -// uploader := s3manager.NewUploader(sess) -// -// f, err := os.Open(filename) -// if err != nil { -// return fmt.Errorf("failed to open file %q, %v", filename, err) -// } -// -// // Upload the file to S3. -// result, err := uploader.Upload(&s3manager.UploadInput{ -// Bucket: aws.String(myBucket), -// Key: aws.String(myString), -// Body: f, -// }) -// if err != nil { -// return fmt.Errorf("failed to upload file, %v", err) -// } -// fmt.Printf("file uploaded to, %s\n", aws.StringValue(result.Location)) -// -// See the s3manager package's Uploader type documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Uploader -// -// Download Manager -// -// The s3manager package's Downloader provides concurrently downloading of Objects -// from S3. The Downloader will write S3 Object content with an io.WriterAt. -// Once the Downloader instance is created you can call Download concurrently from -// multiple goroutines safely. -// -// // The session the S3 Downloader will use -// sess := session.Must(session.NewSession()) -// -// // Create a downloader with the session and default options -// downloader := s3manager.NewDownloader(sess) -// -// // Create a file to write the S3 Object contents to. -// f, err := os.Create(filename) -// if err != nil { -// return fmt.Errorf("failed to create file %q, %v", filename, err) -// } -// -// // Write the contents of S3 Object to the file -// n, err := downloader.Download(f, &s3.GetObjectInput{ -// Bucket: aws.String(myBucket), -// Key: aws.String(myString), -// }) -// if err != nil { -// return fmt.Errorf("failed to download file, %v", err) -// } -// fmt.Printf("file downloaded, %d bytes\n", n) -// -// See the s3manager package's Downloader type documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#Downloader -// -// Get Bucket Region -// -// GetBucketRegion will attempt to get the region for a bucket using a region -// hint to determine which AWS partition to perform the query on. Use this utility -// to determine the region a bucket is in. -// -// sess := session.Must(session.NewSession()) -// -// bucket := "my-bucket" -// region, err := s3manager.GetBucketRegion(ctx, sess, bucket, "us-west-2") -// if err != nil { -// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == "NotFound" { -// fmt.Fprintf(os.Stderr, "unable to find bucket %s's region not found\n", bucket) -// } -// return err -// } -// fmt.Printf("Bucket %s is in %s region\n", bucket, region) -// -// See the s3manager package's GetBucketRegion function documentation for more information -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#GetBucketRegion -// -// S3 Crypto Client -// -// The s3crypto package provides the tools to upload and download encrypted -// content from S3. The Encryption and Decryption clients can be used concurrently -// once the client is created. -// -// sess := session.Must(session.NewSession()) -// -// // Create the decryption client. -// svc := s3crypto.NewDecryptionClient(sess) -// -// // The object will be downloaded from S3 and decrypted locally. By metadata -// // about the object's encryption will instruct the decryption client how -// // decrypt the content of the object. By default KMS is used for keys. -// result, err := svc.GetObject(&s3.GetObjectInput { -// Bucket: aws.String(myBucket), -// Key: aws.String(myKey), -// }) -// -// See the s3crypto package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3crypto/ -// -package s3 diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go b/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go deleted file mode 100644 index 931cb17bb0..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/errors.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package s3 - -const ( - - // ErrCodeBucketAlreadyExists for service response error code - // "BucketAlreadyExists". - // - // The requested bucket name is not available. The bucket namespace is shared - // by all users of the system. Please select a different name and try again. - ErrCodeBucketAlreadyExists = "BucketAlreadyExists" - - // ErrCodeBucketAlreadyOwnedByYou for service response error code - // "BucketAlreadyOwnedByYou". - ErrCodeBucketAlreadyOwnedByYou = "BucketAlreadyOwnedByYou" - - // ErrCodeNoSuchBucket for service response error code - // "NoSuchBucket". - // - // The specified bucket does not exist. - ErrCodeNoSuchBucket = "NoSuchBucket" - - // ErrCodeNoSuchKey for service response error code - // "NoSuchKey". - // - // The specified key does not exist. - ErrCodeNoSuchKey = "NoSuchKey" - - // ErrCodeNoSuchUpload for service response error code - // "NoSuchUpload". - // - // The specified multipart upload does not exist. - ErrCodeNoSuchUpload = "NoSuchUpload" - - // ErrCodeObjectAlreadyInActiveTierError for service response error code - // "ObjectAlreadyInActiveTierError". - // - // This operation is not allowed against this storage tier - ErrCodeObjectAlreadyInActiveTierError = "ObjectAlreadyInActiveTierError" - - // ErrCodeObjectNotInActiveTierError for service response error code - // "ObjectNotInActiveTierError". - // - // The source object of the COPY operation is not in the active tier and is - // only stored in Amazon Glacier. - ErrCodeObjectNotInActiveTierError = "ObjectNotInActiveTierError" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go b/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go deleted file mode 100644 index a7fbc2de2f..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/host_style_bucket.go +++ /dev/null @@ -1,155 +0,0 @@ -package s3 - -import ( - "fmt" - "net/url" - "regexp" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// an operationBlacklist is a list of operation names that should a -// request handler should not be executed with. -type operationBlacklist []string - -// Continue will return true of the Request's operation name is not -// in the blacklist. False otherwise. -func (b operationBlacklist) Continue(r *request.Request) bool { - for i := 0; i < len(b); i++ { - if b[i] == r.Operation.Name { - return false - } - } - return true -} - -var accelerateOpBlacklist = operationBlacklist{ - opListBuckets, opCreateBucket, opDeleteBucket, -} - -// Request handler to automatically add the bucket name to the endpoint domain -// if possible. This style of bucket is valid for all bucket names which are -// DNS compatible and do not contain "." -func updateEndpointForS3Config(r *request.Request) { - forceHostStyle := aws.BoolValue(r.Config.S3ForcePathStyle) - accelerate := aws.BoolValue(r.Config.S3UseAccelerate) - - if accelerate && accelerateOpBlacklist.Continue(r) { - if forceHostStyle { - if r.Config.Logger != nil { - r.Config.Logger.Log("ERROR: aws.Config.S3UseAccelerate is not compatible with aws.Config.S3ForcePathStyle, ignoring S3ForcePathStyle.") - } - } - updateEndpointForAccelerate(r) - } else if !forceHostStyle && r.Operation.Name != opGetBucketLocation { - updateEndpointForHostStyle(r) - } -} - -func updateEndpointForHostStyle(r *request.Request) { - bucket, ok := bucketNameFromReqParams(r.Params) - if !ok { - // Ignore operation requests if the bucketname was not provided - // if this is an input validation error the validation handler - // will report it. - return - } - - if !hostCompatibleBucketName(r.HTTPRequest.URL, bucket) { - // bucket name must be valid to put into the host - return - } - - moveBucketToHost(r.HTTPRequest.URL, bucket) -} - -var ( - accelElem = []byte("s3-accelerate.dualstack.") -) - -func updateEndpointForAccelerate(r *request.Request) { - bucket, ok := bucketNameFromReqParams(r.Params) - if !ok { - // Ignore operation requests if the bucketname was not provided - // if this is an input validation error the validation handler - // will report it. - return - } - - if !hostCompatibleBucketName(r.HTTPRequest.URL, bucket) { - r.Error = awserr.New("InvalidParameterException", - fmt.Sprintf("bucket name %s is not compatible with S3 Accelerate", bucket), - nil) - return - } - - parts := strings.Split(r.HTTPRequest.URL.Host, ".") - if len(parts) < 3 { - r.Error = awserr.New("InvalidParameterExecption", - fmt.Sprintf("unable to update endpoint host for S3 accelerate, hostname invalid, %s", - r.HTTPRequest.URL.Host), nil) - return - } - - if parts[0] == "s3" || strings.HasPrefix(parts[0], "s3-") { - parts[0] = "s3-accelerate" - } - for i := 1; i+1 < len(parts); i++ { - if parts[i] == aws.StringValue(r.Config.Region) { - parts = append(parts[:i], parts[i+1:]...) - break - } - } - - r.HTTPRequest.URL.Host = strings.Join(parts, ".") - - moveBucketToHost(r.HTTPRequest.URL, bucket) -} - -// Attempts to retrieve the bucket name from the request input parameters. -// If no bucket is found, or the field is empty "", false will be returned. -func bucketNameFromReqParams(params interface{}) (string, bool) { - if iface, ok := params.(bucketGetter); ok { - b := iface.getBucket() - return b, len(b) > 0 - } - - return "", false -} - -// hostCompatibleBucketName returns true if the request should -// put the bucket in the host. This is false if S3ForcePathStyle is -// explicitly set or if the bucket is not DNS compatible. -func hostCompatibleBucketName(u *url.URL, bucket string) bool { - // Bucket might be DNS compatible but dots in the hostname will fail - // certificate validation, so do not use host-style. - if u.Scheme == "https" && strings.Contains(bucket, ".") { - return false - } - - // if the bucket is DNS compatible - return dnsCompatibleBucketName(bucket) -} - -var reDomain = regexp.MustCompile(`^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$`) -var reIPAddress = regexp.MustCompile(`^(\d+\.){3}\d+$`) - -// dnsCompatibleBucketName returns true if the bucket name is DNS compatible. -// Buckets created outside of the classic region MUST be DNS compatible. -func dnsCompatibleBucketName(bucket string) bool { - return reDomain.MatchString(bucket) && - !reIPAddress.MatchString(bucket) && - !strings.Contains(bucket, "..") -} - -// moveBucketToHost moves the bucket name from the URI path to URL host. -func moveBucketToHost(u *url.URL, bucket string) { - u.Host = bucket + "." + u.Host - u.Path = strings.Replace(u.Path, "/{Bucket}", "", -1) - if u.Path == "" { - u.Path = "/" - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers.go b/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers.go deleted file mode 100644 index 8e6f3307d4..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !go1.6 - -package s3 - -import "github.com/aws/aws-sdk-go/aws/request" - -func platformRequestHandlers(r *request.Request) { -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers_go1.6.go b/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers_go1.6.go deleted file mode 100644 index 14d05f7b75..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/platform_handlers_go1.6.go +++ /dev/null @@ -1,28 +0,0 @@ -// +build go1.6 - -package s3 - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -func platformRequestHandlers(r *request.Request) { - if r.Operation.HTTPMethod == "PUT" { - // 100-Continue should only be used on put requests. - r.Handlers.Sign.PushBack(add100Continue) - } -} - -func add100Continue(r *request.Request) { - if aws.BoolValue(r.Config.S3Disable100Continue) { - return - } - if r.HTTPRequest.ContentLength < 1024*1024*2 { - // Ignore requests smaller than 2MB. This helps prevent delaying - // requests unnecessarily. - return - } - - r.HTTPRequest.Header.Set("Expect", "100-Continue") -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go b/vendor/github.com/aws/aws-sdk-go/service/s3/service.go deleted file mode 100644 index 614e477d3b..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/service.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package s3 - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -// S3 provides the API operation methods for making requests to -// Amazon Simple Storage Service. See this package's package overview docs -// for details on the service. -// -// S3 methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type S3 struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "s3" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. -) - -// New creates a new instance of the S3 client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a S3 client from just a session. -// svc := s3.New(mySession) -// -// // Create a S3 client with additional configuration -// svc := s3.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *S3 { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *S3 { - svc := &S3{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2006-03-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(restxml.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a S3 operation and runs any -// custom request initialization. -func (c *S3) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go b/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go deleted file mode 100644 index 8010c4fa19..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/sse.go +++ /dev/null @@ -1,54 +0,0 @@ -package s3 - -import ( - "crypto/md5" - "encoding/base64" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -var errSSERequiresSSL = awserr.New("ConfigError", "cannot send SSE keys over HTTP.", nil) - -func validateSSERequiresSSL(r *request.Request) { - if r.HTTPRequest.URL.Scheme == "https" { - return - } - - if iface, ok := r.Params.(sseCustomerKeyGetter); ok { - if len(iface.getSSECustomerKey()) > 0 { - r.Error = errSSERequiresSSL - return - } - } - - if iface, ok := r.Params.(copySourceSSECustomerKeyGetter); ok { - if len(iface.getCopySourceSSECustomerKey()) > 0 { - r.Error = errSSERequiresSSL - return - } - } -} - -func computeSSEKeys(r *request.Request) { - headers := []string{ - "x-amz-server-side-encryption-customer-key", - "x-amz-copy-source-server-side-encryption-customer-key", - } - - for _, h := range headers { - md5h := h + "-md5" - if key := r.HTTPRequest.Header.Get(h); key != "" { - // Base64-encode the value - b64v := base64.StdEncoding.EncodeToString([]byte(key)) - r.HTTPRequest.Header.Set(h, b64v) - - // Add MD5 if it wasn't computed - if r.HTTPRequest.Header.Get(md5h) == "" { - sum := md5.Sum([]byte(key)) - b64sum := base64.StdEncoding.EncodeToString(sum[:]) - r.HTTPRequest.Header.Set(md5h, b64sum) - } - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go deleted file mode 100644 index 5a78fd3370..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/statusok_error.go +++ /dev/null @@ -1,35 +0,0 @@ -package s3 - -import ( - "bytes" - "io/ioutil" - "net/http" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -func copyMultipartStatusOKUnmarhsalError(r *request.Request) { - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "unable to read response body", err) - return - } - body := bytes.NewReader(b) - r.HTTPResponse.Body = ioutil.NopCloser(body) - defer body.Seek(0, 0) - - if body.Len() == 0 { - // If there is no body don't attempt to parse the body. - return - } - - unmarshalError(r) - if err, ok := r.Error.(awserr.Error); ok && err != nil { - if err.Code() == "SerializationError" { - r.Error = nil - return - } - r.HTTPResponse.StatusCode = http.StatusServiceUnavailable - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go deleted file mode 100644 index bcca8627af..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ /dev/null @@ -1,103 +0,0 @@ -package s3 - -import ( - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"Error"` - Code string `xml:"Code"` - Message string `xml:"Message"` -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - defer io.Copy(ioutil.Discard, r.HTTPResponse.Body) - - hostID := r.HTTPResponse.Header.Get("X-Amz-Id-2") - - // Bucket exists in a different region, and request needs - // to be made to the correct region. - if r.HTTPResponse.StatusCode == http.StatusMovedPermanently { - r.Error = requestFailure{ - RequestFailure: awserr.NewRequestFailure( - awserr.New("BucketRegionError", - fmt.Sprintf("incorrect region, the bucket is not in '%s' region", - aws.StringValue(r.Config.Region)), - nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ), - hostID: hostID, - } - return - } - - var errCode, errMsg string - - // Attempt to parse error from body if it is known - resp := &xmlErrorResponse{} - err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) - if err != nil && err != io.EOF { - errCode = "SerializationError" - errMsg = "failed to decode S3 XML error response" - } else { - errCode = resp.Code - errMsg = resp.Message - err = nil - } - - // Fallback to status code converted to message if still no error code - if len(errCode) == 0 { - statusText := http.StatusText(r.HTTPResponse.StatusCode) - errCode = strings.Replace(statusText, " ", "", -1) - errMsg = statusText - } - - r.Error = requestFailure{ - RequestFailure: awserr.NewRequestFailure( - awserr.New(errCode, errMsg, err), - r.HTTPResponse.StatusCode, - r.RequestID, - ), - hostID: hostID, - } -} - -// A RequestFailure provides access to the S3 Request ID and Host ID values -// returned from API operation errors. Getting the error as a string will -// return the formated error with the same information as awserr.RequestFailure, -// while also adding the HostID value from the response. -type RequestFailure interface { - awserr.RequestFailure - - // Host ID is the S3 Host ID needed for debug, and contacting support - HostID() string -} - -type requestFailure struct { - awserr.RequestFailure - - hostID string -} - -func (r requestFailure) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s, host id: %s", - r.StatusCode(), r.RequestID(), r.hostID) - return awserr.SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} -func (r requestFailure) String() string { - return r.Error() -} -func (r requestFailure) HostID() string { - return r.hostID -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go deleted file mode 100644 index 2596c694b5..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/s3/waiters.go +++ /dev/null @@ -1,214 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package s3 - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// WaitUntilBucketExists uses the Amazon S3 API operation -// HeadBucket to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *S3) WaitUntilBucketExists(input *HeadBucketInput) error { - return c.WaitUntilBucketExistsWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilBucketExistsWithContext is an extended version of WaitUntilBucketExists. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) WaitUntilBucketExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilBucketExists", - MaxAttempts: 20, - Delay: request.ConstantWaiterDelay(5 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 301, - }, - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 403, - }, - { - State: request.RetryWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 404, - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *HeadBucketInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.HeadBucketRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} - -// WaitUntilBucketNotExists uses the Amazon S3 API operation -// HeadBucket to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *S3) WaitUntilBucketNotExists(input *HeadBucketInput) error { - return c.WaitUntilBucketNotExistsWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilBucketNotExistsWithContext is an extended version of WaitUntilBucketNotExists. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) WaitUntilBucketNotExistsWithContext(ctx aws.Context, input *HeadBucketInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilBucketNotExists", - MaxAttempts: 20, - Delay: request.ConstantWaiterDelay(5 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 404, - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *HeadBucketInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.HeadBucketRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} - -// WaitUntilObjectExists uses the Amazon S3 API operation -// HeadObject to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *S3) WaitUntilObjectExists(input *HeadObjectInput) error { - return c.WaitUntilObjectExistsWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilObjectExistsWithContext is an extended version of WaitUntilObjectExists. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) WaitUntilObjectExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilObjectExists", - MaxAttempts: 20, - Delay: request.ConstantWaiterDelay(5 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 200, - }, - { - State: request.RetryWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 404, - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *HeadObjectInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.HeadObjectRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} - -// WaitUntilObjectNotExists uses the Amazon S3 API operation -// HeadObject to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *S3) WaitUntilObjectNotExists(input *HeadObjectInput) error { - return c.WaitUntilObjectNotExistsWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilObjectNotExistsWithContext is an extended version of WaitUntilObjectNotExists. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *S3) WaitUntilObjectNotExistsWithContext(ctx aws.Context, input *HeadObjectInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilObjectNotExists", - MaxAttempts: 20, - Delay: request.ConstantWaiterDelay(5 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.StatusWaiterMatch, - Expected: 404, - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *HeadObjectInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.HeadObjectRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go deleted file mode 100644 index e5c105fed8..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ /dev/null @@ -1,2365 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssumeRole = "AssumeRole" - -// AssumeRoleRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRole operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See AssumeRole for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRole method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the AssumeRoleRequest method. -// req, resp := client.AssumeRoleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) { - op := &request.Operation{ - Name: opAssumeRole, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleInput{} - } - - output = &AssumeRoleOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRole API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) that you can use to access -// AWS resources that you might not normally have access to. Typically, you -// use AssumeRole for cross-account access or federation. For a comparison of -// AssumeRole with the other APIs that produce temporary credentials, see Requesting -// Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// Important: You cannot call AssumeRole by using AWS root account credentials; -// access is denied. You must use credentials for an IAM user or an IAM role -// to call AssumeRole. -// -// For cross-account access, imagine that you own multiple accounts and need -// to access resources in each account. You could create long-term credentials -// in each account to access those resources. However, managing all those credentials -// and remembering which one can access which account can be time consuming. -// Instead, you can create one set of long-term credentials in one account and -// then use temporary security credentials to access all the other accounts -// by assuming roles in those accounts. For more information about roles, see -// IAM Roles (Delegation and Federation) (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html) -// in the IAM User Guide. -// -// For federation, you can, for example, grant single sign-on access to the -// AWS Management Console. If you already have an identity and authentication -// system in your corporate network, you don't have to recreate user identities -// in AWS in order to grant those user identities access to AWS. Instead, after -// a user has been authenticated, you call AssumeRole (and specify the role -// with the appropriate permissions) to get temporary security credentials for -// that user. With those temporary security credentials, you construct a sign-in -// URL that users can use to access the console. For more information, see Common -// Scenarios for Temporary Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction) -// in the IAM User Guide. -// -// The temporary security credentials are valid for the duration that you specified -// when calling AssumeRole, which can be from 900 seconds (15 minutes) to a -// maximum of 3600 seconds (1 hour). The default is 1 hour. -// -// The temporary security credentials created by AssumeRole can be used to make -// API calls to any AWS service with the following exception: you cannot call -// the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// To assume a role, your AWS account must be trusted by the role. The trust -// relationship is defined in the role's trust policy when the role is created. -// That trust policy states which accounts are allowed to delegate access to -// this account's role. -// -// The user who wants to access the role must also have permissions delegated -// from the role's administrator. If the user is in a different account than -// the role, then the user's administrator must attach a policy that allows -// the user to call AssumeRole on the ARN of the role in the other account. -// If the user is in the same account as the role, then you can either attach -// a policy to the user (identical to the previous different account user), -// or you can add the user as a principal directly in the role's trust policy -// -// Using MFA with AssumeRole -// -// You can optionally include multi-factor authentication (MFA) information -// when you call AssumeRole. This is useful for cross-account scenarios in which -// you want to make sure that the user who is assuming the role has been authenticated -// using an AWS MFA device. In that scenario, the trust policy of the role being -// assumed includes a condition that tests for MFA authentication; if the caller -// does not include valid MFA information, the request to assume the role is -// denied. The condition in a trust policy that tests for MFA authentication -// might look like the following example. -// -// "Condition": {"Bool": {"aws:MultiFactorAuthPresent": true}} -// -// For more information, see Configuring MFA-Protected API Access (http://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html) -// in the IAM User Guide guide. -// -// To use MFA with AssumeRole, you pass values for the SerialNumber and TokenCode -// parameters. The SerialNumber value identifies the user's hardware or virtual -// MFA device. The TokenCode is the time-based one-time password (TOTP) that -// the MFA devices produces. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRole for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - return out, req.Send() -} - -// AssumeRoleWithContext is the same as AssumeRole with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRole for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithSAML = "AssumeRoleWithSAML" - -// AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithSAML operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See AssumeRoleWithSAML for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRoleWithSAML method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the AssumeRoleWithSAMLRequest method. -// req, resp := client.AssumeRoleWithSAMLRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithSAML, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithSAMLInput{} - } - - output = &AssumeRoleWithSAMLOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithSAML API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// via a SAML authentication response. This operation provides a mechanism for -// tying an enterprise identity store or directory to role-based AWS access -// without user-specific credentials or configuration. For a comparison of AssumeRoleWithSAML -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this operation consist of -// an access key ID, a secret access key, and a security token. Applications -// can use these temporary security credentials to sign calls to AWS services. -// -// The temporary security credentials are valid for the duration that you specified -// when calling AssumeRole, or until the time specified in the SAML authentication -// response's SessionNotOnOrAfter value, whichever is shorter. The duration -// can be from 900 seconds (15 minutes) to a maximum of 3600 seconds (1 hour). -// The default is 1 hour. -// -// The temporary security credentials created by AssumeRoleWithSAML can be used -// to make API calls to any AWS service with the following exception: you cannot -// call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by the intersection of both the access policy -// of the role that is being assumed, and the policy that you pass. This means -// that both policies must grant the permission for the action to be allowed. -// This gives you a way to further restrict the permissions for the resulting -// temporary security credentials. You cannot use the passed policy to grant -// permissions that are in excess of those allowed by the access policy of the -// role that is being assumed. For more information, see Permissions for AssumeRole, -// AssumeRoleWithSAML, and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// Before your application can call AssumeRoleWithSAML, you must configure your -// SAML identity provider (IdP) to issue the claims required by AWS. Additionally, -// you must use AWS Identity and Access Management (IAM) to create a SAML provider -// entity in your AWS account that represents your identity provider, and create -// an IAM role that specifies this SAML provider in its trust policy. -// -// Calling AssumeRoleWithSAML does not require the use of AWS security credentials. -// The identity of the caller is validated by using keys in the metadata document -// that is uploaded for the SAML provider entity for your identity provider. -// -// Calling AssumeRoleWithSAML can result in an entry in your AWS CloudTrail -// logs. The entry includes the value in the NameID element of the SAML assertion. -// We recommend that you use a NameIDType that is not associated with any personally -// identifiable information (PII). For example, you could instead use the Persistent -// Identifier (urn:oasis:names:tc:SAML:2.0:nameid-format:persistent). -// -// For more information, see the following resources: -// -// * About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// -// * Creating SAML Identity Providers (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// -// * Configuring a Relying Party and Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) -// in the IAM User Guide. -// -// * Creating a Role for SAML 2.0 Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithSAML for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - return out, req.Send() -} - -// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithSAML for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" - -// AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithWebIdentity operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See AssumeRoleWithWebIdentity for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the AssumeRoleWithWebIdentity method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the AssumeRoleWithWebIdentityRequest method. -// req, resp := client.AssumeRoleWithWebIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithWebIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithWebIdentityInput{} - } - - output = &AssumeRoleWithWebIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithWebIdentity API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// in a mobile or web application with a web identity provider, such as Amazon -// Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible -// identity provider. -// -// For mobile applications, we recommend that you use Amazon Cognito. You can -// use Amazon Cognito with the AWS SDK for iOS (http://aws.amazon.com/sdkforios/) -// and the AWS SDK for Android (http://aws.amazon.com/sdkforandroid/) to uniquely -// identify a user and supply the user with a consistent identity throughout -// the lifetime of an application. -// -// To learn more about Amazon Cognito, see Amazon Cognito Overview (http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840) -// in the AWS SDK for Android Developer Guide guide and Amazon Cognito Overview -// (http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664) -// in the AWS SDK for iOS Developer Guide. -// -// Calling AssumeRoleWithWebIdentity does not require the use of AWS security -// credentials. Therefore, you can distribute an application (for example, on -// mobile devices) that requests temporary security credentials without including -// long-term AWS credentials in the application, and without deploying server-based -// proxy services that use long-term AWS credentials. Instead, the identity -// of the caller is validated by using a token from the web identity provider. -// For a comparison of AssumeRoleWithWebIdentity with the other APIs that produce -// temporary credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The temporary security credentials returned by this API consist of an access -// key ID, a secret access key, and a security token. Applications can use these -// temporary security credentials to sign calls to AWS service APIs. -// -// The credentials are valid for the duration that you specified when calling -// AssumeRoleWithWebIdentity, which can be from 900 seconds (15 minutes) to -// a maximum of 3600 seconds (1 hour). The default is 1 hour. -// -// The temporary security credentials created by AssumeRoleWithWebIdentity can -// be used to make API calls to any AWS service with the following exception: -// you cannot call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// Before your application can call AssumeRoleWithWebIdentity, you must have -// an identity token from a supported identity provider and create a role that -// the application can assume. The role that your application assumes must trust -// the identity provider that is associated with the identity token. In other -// words, the identity provider must be specified in the role's trust policy. -// -// Calling AssumeRoleWithWebIdentity can result in an entry in your AWS CloudTrail -// logs. The entry includes the Subject (http://openid.net/specs/openid-connect-core-1_0.html#Claims) -// of the provided Web Identity Token. We recommend that you avoid using any -// personally identifiable information (PII) in this field. For example, you -// could instead use a GUID or a pairwise identifier, as suggested in the OIDC -// specification (http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes). -// -// For more information about how to use web identity federation and the AssumeRoleWithWebIdentity -// API, see the following resources: -// -// * Using Web Identity Federation APIs for Mobile Apps (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// -// * Web Identity Federation Playground (https://web-identity-federation-playground.s3.amazonaws.com/index.html). -// This interactive website lets you walk through the process of authenticating -// via Login with Amazon, Facebook, or Google, getting temporary security -// credentials, and then using those credentials to make a request to AWS. -// -// -// * AWS SDK for iOS (http://aws.amazon.com/sdkforios/) and AWS SDK for Android -// (http://aws.amazon.com/sdkforandroid/). These toolkits contain sample -// apps that show how to invoke the identity providers, and then how to use -// the information from these providers to get and use temporary security -// credentials. -// -// * Web Identity Federation with Mobile Applications (http://aws.amazon.com/articles/4617974389850313). -// This article discusses web identity federation and shows an example of -// how to use web identity federation to get access to content in Amazon -// S3. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithWebIdentity for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeIDPCommunicationErrorException "IDPCommunicationError" -// The request could not be fulfilled because the non-AWS identity provider -// (IDP) that was asked to verify the incoming identity token could not be reached. -// This is often a transient error caused by network conditions. Retry the request -// a limited number of times so that you don't exceed the request rate. If the -// error persists, the non-AWS identity provider might be down or not responding. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - return out, req.Send() -} - -// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithWebIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" - -// DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the -// client's request for the DecodeAuthorizationMessage operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See DecodeAuthorizationMessage for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the DecodeAuthorizationMessage method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the DecodeAuthorizationMessageRequest method. -// req, resp := client.DecodeAuthorizationMessageRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) { - op := &request.Operation{ - Name: opDecodeAuthorizationMessage, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DecodeAuthorizationMessageInput{} - } - - output = &DecodeAuthorizationMessageOutput{} - req = c.newRequest(op, input, output) - return -} - -// DecodeAuthorizationMessage API operation for AWS Security Token Service. -// -// Decodes additional information about the authorization status of a request -// from an encoded message returned in response to an AWS request. -// -// For example, if a user is not authorized to perform an action that he or -// she has requested, the request returns a Client.UnauthorizedOperation response -// (an HTTP 403 response). Some AWS actions additionally return an encoded message -// that can provide details about this authorization failure. -// -// Only certain AWS actions return an encoded authorization message. The documentation -// for an individual action indicates whether that action returns an encoded -// message in addition to returning an HTTP code. -// -// The message is encoded because the details of the authorization status can -// constitute privileged information that the user who requested the action -// should not see. To decode an authorization status message, a user must be -// granted permissions via an IAM policy to request the DecodeAuthorizationMessage -// (sts:DecodeAuthorizationMessage) action. -// -// The decoded message includes the following type of information: -// -// * Whether the request was denied due to an explicit deny or due to the -// absence of an explicit allow. For more information, see Determining Whether -// a Request is Allowed or Denied (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow) -// in the IAM User Guide. -// -// * The principal who made the request. -// -// * The requested action. -// -// * The requested resource. -// -// * The values of condition keys in the context of the user's request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation DecodeAuthorizationMessage for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidAuthorizationMessageException "InvalidAuthorizationMessageException" -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - return out, req.Send() -} - -// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of -// the ability to pass a context and additional request options. -// -// See DecodeAuthorizationMessage for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCallerIdentity = "GetCallerIdentity" - -// GetCallerIdentityRequest generates a "aws/request.Request" representing the -// client's request for the GetCallerIdentity operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See GetCallerIdentity for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetCallerIdentity method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the GetCallerIdentityRequest method. -// req, resp := client.GetCallerIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) { - op := &request.Operation{ - Name: opGetCallerIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetCallerIdentityInput{} - } - - output = &GetCallerIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCallerIdentity API operation for AWS Security Token Service. -// -// Returns details about the IAM identity whose credentials are used to call -// the API. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetCallerIdentity for usage and error information. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - return out, req.Send() -} - -// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See GetCallerIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetFederationToken = "GetFederationToken" - -// GetFederationTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetFederationToken operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See GetFederationToken for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetFederationToken method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the GetFederationTokenRequest method. -// req, resp := client.GetFederationTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) { - op := &request.Operation{ - Name: opGetFederationToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetFederationTokenInput{} - } - - output = &GetFederationTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetFederationToken API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a federated user. -// A typical use is in a proxy application that gets temporary security credentials -// on behalf of distributed applications inside a corporate network. Because -// you must call the GetFederationToken action using the long-term security -// credentials of an IAM user, this call is appropriate in contexts where those -// credentials can be safely stored, usually in a server-based application. -// For a comparison of GetFederationToken with the other APIs that produce temporary -// credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// If you are creating a mobile-based or browser-based app that can authenticate -// users using a web identity provider like Login with Amazon, Facebook, Google, -// or an OpenID Connect-compatible identity provider, we recommend that you -// use Amazon Cognito (http://aws.amazon.com/cognito/) or AssumeRoleWithWebIdentity. -// For more information, see Federation Through a Web-based Identity Provider -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// The GetFederationToken action must be called by using the long-term AWS security -// credentials of an IAM user. You can also call GetFederationToken using the -// security credentials of an AWS root account, but we do not recommended it. -// Instead, we recommend that you create an IAM user for the purpose of the -// proxy application and then attach a policy to the IAM user that limits federated -// users to only the actions and resources that they need access to. For more -// information, see IAM Best Practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) -// in the IAM User Guide. -// -// The temporary security credentials that are obtained by using the long-term -// credentials of an IAM user are valid for the specified duration, from 900 -// seconds (15 minutes) up to a maximium of 129600 seconds (36 hours). The default -// is 43200 seconds (12 hours). Temporary credentials that are obtained by using -// AWS root account credentials have a maximum duration of 3600 seconds (1 hour). -// -// The temporary security credentials created by GetFederationToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot use these credentials to call any IAM APIs. -// -// * You cannot call any STS APIs except GetCallerIdentity. -// -// Permissions -// -// The permissions for the temporary security credentials returned by GetFederationToken -// are determined by a combination of the following: -// -// * The policy or policies that are attached to the IAM user whose credentials -// are used to call GetFederationToken. -// -// * The policy that is passed as a parameter in the call. -// -// The passed policy is attached to the temporary security credentials that -// result from the GetFederationToken API call--that is, to the federated user. -// When the federated user makes an AWS request, AWS evaluates the policy attached -// to the federated user in combination with the policy or policies attached -// to the IAM user whose credentials were used to call GetFederationToken. AWS -// allows the federated user's request only when both the federated user and -// the IAM user are explicitly allowed to perform the requested action. The -// passed policy cannot grant more permissions than those that are defined in -// the IAM user policy. -// -// A typical use case is that the permissions of the IAM user whose credentials -// are used to call GetFederationToken are designed to allow access to all the -// actions and resources that any federated user will need. Then, for individual -// users, you pass a policy to the operation that scopes down the permissions -// to a level that's appropriate to that individual user, using a policy that -// allows only a subset of permissions that are granted to the IAM user. -// -// If you do not pass a policy, the resulting temporary security credentials -// have no effective permissions. The only exception is when the temporary security -// credentials are used to access a resource that has a resource-based policy -// that specifically allows the federated user to access the resource. -// -// For more information about how permissions work, see Permissions for GetFederationToken -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). -// For information about using GetFederationToken to create temporary security -// credentials, see GetFederationToken—Federation Through a Custom Identity -// Broker (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetFederationToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - return out, req.Send() -} - -// GetFederationTokenWithContext is the same as GetFederationToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetFederationToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetSessionToken = "GetSessionToken" - -// GetSessionTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetSessionToken operation. The "output" return -// value can be used to capture response data after the request's "Send" method -// is called. -// -// See GetSessionToken for usage and error information. -// -// Creating a request object using this method should be used when you want to inject -// custom logic into the request's lifecycle using a custom handler, or if you want to -// access properties on the request object before or after sending the request. If -// you just want the service response, call the GetSessionToken method directly -// instead. -// -// Note: You must call the "Send" method on the returned request object in order -// to execute the request. -// -// // Example sending a request using the GetSessionTokenRequest method. -// req, resp := client.GetSessionTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) { - op := &request.Operation{ - Name: opGetSessionToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetSessionTokenInput{} - } - - output = &GetSessionTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetSessionToken API operation for AWS Security Token Service. -// -// Returns a set of temporary credentials for an AWS account or IAM user. The -// credentials consist of an access key ID, a secret access key, and a security -// token. Typically, you use GetSessionToken if you want to use MFA to protect -// programmatic calls to specific AWS APIs like Amazon EC2 StopInstances. MFA-enabled -// IAM users would need to call GetSessionToken and submit an MFA code that -// is associated with their MFA device. Using the temporary security credentials -// that are returned from the call, IAM users can then make programmatic calls -// to APIs that require MFA authentication. If you do not supply a correct MFA -// code, then the API returns an access denied error. For a comparison of GetSessionToken -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The GetSessionToken action must be called by using the long-term AWS security -// credentials of the AWS account or an IAM user. Credentials that are created -// by IAM users are valid for the duration that you specify, from 900 seconds -// (15 minutes) up to a maximum of 129600 seconds (36 hours), with a default -// of 43200 seconds (12 hours); credentials that are created by using account -// credentials can range from 900 seconds (15 minutes) up to a maximum of 3600 -// seconds (1 hour), with a default of 1 hour. -// -// The temporary security credentials created by GetSessionToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot call any IAM APIs unless MFA authentication information is -// included in the request. -// -// * You cannot call any STS API exceptAssumeRole or GetCallerIdentity. -// -// We recommend that you do not call GetSessionToken with root account credentials. -// Instead, follow our best practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users) -// by creating one or more IAM users, giving them the necessary permissions, -// and using IAM users for everyday interaction with AWS. -// -// The permissions associated with the temporary security credentials returned -// by GetSessionToken are based on the permissions associated with account or -// IAM user whose credentials are used to call the action. If GetSessionToken -// is called using root account credentials, the temporary credentials have -// root account permissions. Similarly, if GetSessionToken is called using the -// credentials of an IAM user, the temporary credentials have the same permissions -// as the IAM user. -// -// For more information about using GetSessionToken to create temporary credentials, -// go to Temporary Credentials for Users in Untrusted Environments (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetSessionToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - return out, req.Send() -} - -// GetSessionTokenWithContext is the same as GetSessionToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetSessionToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleRequest -type AssumeRoleInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. - // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Creating a URL that Enables - // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // A unique identifier that is used by third parties when assuming roles in - // their customers' accounts. For each role that the third party can assume, - // they should instruct their customers to ensure the role's trust policy checks - // for the external ID that the third party generated. Each time the third party - // assumes the role, they should pass the customer's external ID. The external - // ID is useful in order to help third parties bind a role to the customer who - // created it. For more information about the external ID, see How to Use an - // External ID When Granting Access to Your AWS Resources to a Third Party (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. - // - // The regex used to validated this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - ExternalId *string `min:"2" type:"string"` - - // An IAM policy in JSON format. - // - // This parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both (the intersection of) the access policy of the role that - // is being assumed, and the policy that you pass. This gives you a way to further - // restrict the permissions for the resulting temporary security credentials. - // You cannot use the passed policy to grant permissions that are in excess - // of those allowed by the access policy of the role that is being assumed. - // For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, - // and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the role to assume. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. - // - // Use the role session name to uniquely identify a session when the same role - // is assumed by different principals or for different reasons. In cross-account - // scenarios, the role session name is visible to, and can be logged by the - // account that owns the role. The role session name is also used in the ARN - // of the assumed role principal. This means that subsequent cross-account API - // requests using the temporary security credentials will expose the role session - // name to the external account in their CloudTrail logs. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The identification number of the MFA device that is associated with the user - // who is making the AssumeRole call. Specify this value if the trust policy - // of the role being assumed includes a condition that requires MFA authentication. - // The value is either the serial number for a hardware device (such as GAHT12345678) - // or an Amazon Resource Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - SerialNumber *string `min:"9" type:"string"` - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.ExternalId != nil && len(*s.ExternalId) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ExternalId", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleInput) SetDurationSeconds(v int64) *AssumeRoleInput { - s.DurationSeconds = &v - return s -} - -// SetExternalId sets the ExternalId field's value. -func (s *AssumeRoleInput) SetExternalId(v string) *AssumeRoleInput { - s.ExternalId = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleInput) SetPolicy(v string) *AssumeRoleInput { - s.Policy = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleInput) SetRoleArn(v string) *AssumeRoleInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleInput) SetRoleSessionName(v string) *AssumeRoleInput { - s.RoleSessionName = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *AssumeRoleInput) SetSerialNumber(v string) *AssumeRoleInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *AssumeRoleInput) SetTokenCode(v string) *AssumeRoleInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful AssumeRole request, including temporary -// AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleResponse -type AssumeRoleOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s AssumeRoleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleOutput { - s.AssumedRoleUser = v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleOutput) SetCredentials(v *Credentials) *AssumeRoleOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleOutput) SetPackedPolicySize(v int64) *AssumeRoleOutput { - s.PackedPolicySize = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAMLRequest -type AssumeRoleWithSAMLInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. An expiration can also be specified in the SAML authentication - // response's SessionNotOnOrAfter value. The actual expiration time is whichever - // value is shorter. - // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Enabling SAML 2.0 Federated - // Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-saml.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes - // the IdP. - // - // PrincipalArn is a required field - PrincipalArn *string `min:"20" type:"string" required:"true"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // The base-64 encoded SAML authentication response provided by the IdP. - // - // For more information, see Configuring a Relying Party and Adding Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the Using IAM guide. - // - // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithSAMLInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithSAMLInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.PrincipalArn == nil { - invalidParams.Add(request.NewErrParamRequired("PrincipalArn")) - } - if s.PrincipalArn != nil && len(*s.PrincipalArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PrincipalArn", 20)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.SAMLAssertion == nil { - invalidParams.Add(request.NewErrParamRequired("SAMLAssertion")) - } - if s.SAMLAssertion != nil && len(*s.SAMLAssertion) < 4 { - invalidParams.Add(request.NewErrParamMinLen("SAMLAssertion", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithSAMLInput) SetDurationSeconds(v int64) *AssumeRoleWithSAMLInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithSAMLInput) SetPolicy(v string) *AssumeRoleWithSAMLInput { - s.Policy = &v - return s -} - -// SetPrincipalArn sets the PrincipalArn field's value. -func (s *AssumeRoleWithSAMLInput) SetPrincipalArn(v string) *AssumeRoleWithSAMLInput { - s.PrincipalArn = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithSAMLInput) SetRoleArn(v string) *AssumeRoleWithSAMLInput { - s.RoleArn = &v - return s -} - -// SetSAMLAssertion sets the SAMLAssertion field's value. -func (s *AssumeRoleWithSAMLInput) SetSAMLAssertion(v string) *AssumeRoleWithSAMLInput { - s.SAMLAssertion = &v - return s -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAMLResponse -type AssumeRoleWithSAMLOutput struct { - _ struct{} `type:"structure"` - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The value of the Recipient attribute of the SubjectConfirmationData element - // of the SAML assertion. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // The value of the Issuer element of the SAML assertion. - Issuer *string `type:"string"` - - // A hash value based on the concatenation of the Issuer response value, the - // AWS account ID, and the friendly name (the last part of the ARN) of the SAML - // provider in IAM. The combination of NameQualifier and Subject can be used - // to uniquely identify a federated user. - // - // The following pseudocode shows how the hash value is calculated: - // - // BASE64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" - // ) ) - NameQualifier *string `type:"string"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string `type:"string"` - - // The format of the name ID, as defined by the Format attribute in the NameID - // element of the SAML assertion. Typical examples of the format are transient - // or persistent. - // - // If the format includes the prefix urn:oasis:names:tc:SAML:2.0:nameid-format, - // that prefix is removed. For example, urn:oasis:names:tc:SAML:2.0:nameid-format:transient - // is returned as transient. If the format includes any other prefix, the format - // is returned with no modifications. - SubjectType *string `type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithSAMLOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithSAMLOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithSAMLOutput) SetAudience(v string) *AssumeRoleWithSAMLOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithSAMLOutput) SetCredentials(v *Credentials) *AssumeRoleWithSAMLOutput { - s.Credentials = v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *AssumeRoleWithSAMLOutput) SetIssuer(v string) *AssumeRoleWithSAMLOutput { - s.Issuer = &v - return s -} - -// SetNameQualifier sets the NameQualifier field's value. -func (s *AssumeRoleWithSAMLOutput) SetNameQualifier(v string) *AssumeRoleWithSAMLOutput { - s.NameQualifier = &v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithSAMLOutput) SetPackedPolicySize(v int64) *AssumeRoleWithSAMLOutput { - s.PackedPolicySize = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubject(v string) *AssumeRoleWithSAMLOutput { - s.Subject = &v - return s -} - -// SetSubjectType sets the SubjectType field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubjectType(v string) *AssumeRoleWithSAMLOutput { - s.SubjectType = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentityRequest -type AssumeRoleWithWebIdentityInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, of the role session. The value can range from 900 - // seconds (15 minutes) to 3600 seconds (1 hour). By default, the value is set - // to 3600 seconds. - // - // This is separate from the duration of a console session that you might request - // using the returned credentials. The request to the federation endpoint for - // a console sign-in token takes a SessionDuration parameter that specifies - // the maximum length of the console session, separately from the DurationSeconds - // parameter on this API. For more information, see Creating a URL that Enables - // Federated Users to Access the AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // see Permissions for AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - Policy *string `min:"1" type:"string"` - - // The fully qualified host component of the domain name of the identity provider. - // - // Specify this value only for OAuth 2.0 access tokens. Currently www.amazon.com - // and graph.facebook.com are the only supported identity providers for OAuth - // 2.0 access tokens. Do not include URL schemes and port numbers. - // - // Do not specify this value for OpenID Connect ID tokens. - ProviderId *string `min:"4" type:"string"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // An identifier for the assumed role session. Typically, you pass the name - // or identifier that is associated with the user who is using your application. - // That way, the temporary security credentials that your application will use - // are associated with that user. This session name is included as part of the - // ARN and assumed role ID in the AssumedRoleUser response element. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // The OAuth 2.0 access token or OpenID Connect ID token that is provided by - // the identity provider. Your application must get this token by authenticating - // the user who is using your application with a web identity provider before - // the application makes an AssumeRoleWithWebIdentity call. - // - // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithWebIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithWebIdentityInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.ProviderId != nil && len(*s.ProviderId) < 4 { - invalidParams.Add(request.NewErrParamMinLen("ProviderId", 4)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.WebIdentityToken == nil { - invalidParams.Add(request.NewErrParamRequired("WebIdentityToken")) - } - if s.WebIdentityToken != nil && len(*s.WebIdentityToken) < 4 { - invalidParams.Add(request.NewErrParamMinLen("WebIdentityToken", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithWebIdentityInput) SetDurationSeconds(v int64) *AssumeRoleWithWebIdentityInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithWebIdentityInput) SetPolicy(v string) *AssumeRoleWithWebIdentityInput { - s.Policy = &v - return s -} - -// SetProviderId sets the ProviderId field's value. -func (s *AssumeRoleWithWebIdentityInput) SetProviderId(v string) *AssumeRoleWithWebIdentityInput { - s.ProviderId = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleArn(v string) *AssumeRoleWithWebIdentityInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleSessionName(v string) *AssumeRoleWithWebIdentityInput { - s.RoleSessionName = &v - return s -} - -// SetWebIdentityToken sets the WebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityInput) SetWebIdentityToken(v string) *AssumeRoleWithWebIdentityInput { - s.WebIdentityToken = &v - return s -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentityResponse -type AssumeRoleWithWebIdentityOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) and the assumed role ID, which are identifiers - // that you can use to refer to the resulting temporary security credentials. - // For example, you can reference these credentials as a principal in a resource-based - // policy by using the ARN or assumed role ID. The ARN and ID include the RoleSessionName - // that you specified when you called AssumeRole. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The intended audience (also known as client ID) of the web identity token. - // This is traditionally the client identifier issued to the application that - // requested the web identity token. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The issuing authority of the web identity token presented. For OpenID Connect - // ID Tokens this contains the value of the iss field. For OAuth 2.0 access - // tokens, this contains the value of the ProviderId parameter that was passed - // in the AssumeRoleWithWebIdentity request. - Provider *string `type:"string"` - - // The unique user identifier that is returned by the identity provider. This - // identifier is associated with the WebIdentityToken that was submitted with - // the AssumeRoleWithWebIdentity call. The identifier is typically unique to - // the user and the application that acquired the WebIdentityToken (pairwise - // identifier). For OpenID Connect ID tokens, this field contains the value - // returned by the identity provider as the token's sub (Subject) claim. - SubjectFromWebIdentityToken *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithWebIdentityOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAudience(v string) *AssumeRoleWithWebIdentityOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetCredentials(v *Credentials) *AssumeRoleWithWebIdentityOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetPackedPolicySize(v int64) *AssumeRoleWithWebIdentityOutput { - s.PackedPolicySize = &v - return s -} - -// SetProvider sets the Provider field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetProvider(v string) *AssumeRoleWithWebIdentityOutput { - s.Provider = &v - return s -} - -// SetSubjectFromWebIdentityToken sets the SubjectFromWebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetSubjectFromWebIdentityToken(v string) *AssumeRoleWithWebIdentityOutput { - s.SubjectFromWebIdentityToken = &v - return s -} - -// The identifiers for the temporary security credentials that the operation -// returns. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumedRoleUser -type AssumedRoleUser struct { - _ struct{} `type:"structure"` - - // The ARN of the temporary security credentials that are returned from the - // AssumeRole action. For more information about ARNs and how to use them in - // policies, see IAM Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // A unique identifier that contains the role ID and the role session name of - // the role that is being assumed. The role ID is generated by AWS when the - // role is created. - // - // AssumedRoleId is a required field - AssumedRoleId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumedRoleUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumedRoleUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *AssumedRoleUser) SetArn(v string) *AssumedRoleUser { - s.Arn = &v - return s -} - -// SetAssumedRoleId sets the AssumedRoleId field's value. -func (s *AssumedRoleUser) SetAssumedRoleId(v string) *AssumedRoleUser { - s.AssumedRoleId = &v - return s -} - -// AWS credentials for API authentication. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/Credentials -type Credentials struct { - _ struct{} `type:"structure"` - - // The access key ID that identifies the temporary security credentials. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` - - // The date on which the current credentials expire. - // - // Expiration is a required field - Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` - - // The secret access key that can be used to sign requests. - // - // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` - - // The token that users must pass to the service API to use the temporary credentials. - // - // SessionToken is a required field - SessionToken *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s Credentials) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Credentials) GoString() string { - return s.String() -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *Credentials) SetAccessKeyId(v string) *Credentials { - s.AccessKeyId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *Credentials) SetExpiration(v time.Time) *Credentials { - s.Expiration = &v - return s -} - -// SetSecretAccessKey sets the SecretAccessKey field's value. -func (s *Credentials) SetSecretAccessKey(v string) *Credentials { - s.SecretAccessKey = &v - return s -} - -// SetSessionToken sets the SessionToken field's value. -func (s *Credentials) SetSessionToken(v string) *Credentials { - s.SessionToken = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessageRequest -type DecodeAuthorizationMessageInput struct { - _ struct{} `type:"structure"` - - // The encoded message that was returned with the response. - // - // EncodedMessage is a required field - EncodedMessage *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DecodeAuthorizationMessageInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DecodeAuthorizationMessageInput"} - if s.EncodedMessage == nil { - invalidParams.Add(request.NewErrParamRequired("EncodedMessage")) - } - if s.EncodedMessage != nil && len(*s.EncodedMessage) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncodedMessage", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEncodedMessage sets the EncodedMessage field's value. -func (s *DecodeAuthorizationMessageInput) SetEncodedMessage(v string) *DecodeAuthorizationMessageInput { - s.EncodedMessage = &v - return s -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an AWS -// request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessageResponse -type DecodeAuthorizationMessageOutput struct { - _ struct{} `type:"structure"` - - // An XML document that contains the decoded message. - DecodedMessage *string `type:"string"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageOutput) GoString() string { - return s.String() -} - -// SetDecodedMessage sets the DecodedMessage field's value. -func (s *DecodeAuthorizationMessageOutput) SetDecodedMessage(v string) *DecodeAuthorizationMessageOutput { - s.DecodedMessage = &v - return s -} - -// Identifiers for the federated user that is associated with the credentials. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/FederatedUser -type FederatedUser struct { - _ struct{} `type:"structure"` - - // The ARN that specifies the federated user that is associated with the credentials. - // For more information about ARNs and how to use them in policies, see IAM - // Identifiers (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // FederatedUserId is a required field - FederatedUserId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s FederatedUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s FederatedUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *FederatedUser) SetArn(v string) *FederatedUser { - s.Arn = &v - return s -} - -// SetFederatedUserId sets the FederatedUserId field's value. -func (s *FederatedUser) SetFederatedUserId(v string) *FederatedUser { - s.FederatedUserId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentityRequest -type GetCallerIdentityInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetCallerIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityInput) GoString() string { - return s.String() -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentityResponse -type GetCallerIdentityOutput struct { - _ struct{} `type:"structure"` - - // The AWS account ID number of the account that owns or contains the calling - // entity. - Account *string `type:"string"` - - // The AWS ARN associated with the calling entity. - Arn *string `min:"20" type:"string"` - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity making the call. The values returned are those listed in the - // aws:userid column in the Principal table (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html#principaltable) - // found on the Policy Variables reference page in the IAM User Guide. - UserId *string `type:"string"` -} - -// String returns the string representation -func (s GetCallerIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityOutput) GoString() string { - return s.String() -} - -// SetAccount sets the Account field's value. -func (s *GetCallerIdentityOutput) SetAccount(v string) *GetCallerIdentityOutput { - s.Account = &v - return s -} - -// SetArn sets the Arn field's value. -func (s *GetCallerIdentityOutput) SetArn(v string) *GetCallerIdentityOutput { - s.Arn = &v - return s -} - -// SetUserId sets the UserId field's value. -func (s *GetCallerIdentityOutput) SetUserId(v string) *GetCallerIdentityOutput { - s.UserId = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationTokenRequest -type GetFederationTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129600 seconds - // (36 hours), with 43200 seconds (12 hours) as the default. Sessions obtained - // using AWS account (root) credentials are restricted to a maximum of 3600 - // seconds (one hour). If the specified duration is longer than one hour, the - // session obtained by using AWS account (root) credentials defaults to one - // hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The name of the federated user. The name is used as an identifier for the - // temporary security credentials (such as Bob). For example, you can reference - // the federated user name in a resource-based policy, such as in an Amazon - // S3 bucket policy. - // - // The regex used to validate this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@- - // - // Name is a required field - Name *string `min:"2" type:"string" required:"true"` - - // An IAM policy in JSON format that is passed with the GetFederationToken call - // and evaluated along with the policy or policies that are attached to the - // IAM user whose credentials are used to call GetFederationToken. The passed - // policy is used to scope down the permissions that are available to the IAM - // user, by allowing only a subset of the permissions that are granted to the - // IAM user. The passed policy cannot grant more permissions than those granted - // to the IAM user. The final permissions for the federated user are the most - // restrictive set based on the intersection of the passed policy and the IAM - // user policy. - // - // If you do not pass a policy, the resulting temporary security credentials - // have no effective permissions. The only exception is when the temporary security - // credentials are used to access a resource that has a resource-based policy - // that specifically allows the federated user to access the resource. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // The policy plain text must be 2048 bytes or shorter. However, an internal - // conversion compresses it into a packed binary format with a separate limit. - // The PackedPolicySize response element indicates by percentage how close to - // the upper size limit the policy is, with 100% equaling the maximum allowed - // size. - // - // For more information about how permissions work, see Permissions for GetFederationToken - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). - Policy *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GetFederationTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetFederationTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFederationTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetFederationTokenInput) SetDurationSeconds(v int64) *GetFederationTokenInput { - s.DurationSeconds = &v - return s -} - -// SetName sets the Name field's value. -func (s *GetFederationTokenInput) SetName(v string) *GetFederationTokenInput { - s.Name = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *GetFederationTokenInput) SetPolicy(v string) *GetFederationTokenInput { - s.Policy = &v - return s -} - -// Contains the response to a successful GetFederationToken request, including -// temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationTokenResponse -type GetFederationTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // Identifiers for the federated user associated with the credentials (such - // as arn:aws:sts::123456789012:federated-user/Bob or 123456789012:Bob). You - // can use the federated user's ARN in your resource-based policies, such as - // an Amazon S3 bucket policy. - FederatedUser *FederatedUser `type:"structure"` - - // A percentage value indicating the size of the policy in packed form. The - // service rejects policies for which the packed size is greater than 100 percent - // of the allowed value. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s GetFederationTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetFederationTokenOutput) SetCredentials(v *Credentials) *GetFederationTokenOutput { - s.Credentials = v - return s -} - -// SetFederatedUser sets the FederatedUser field's value. -func (s *GetFederationTokenOutput) SetFederatedUser(v *FederatedUser) *GetFederationTokenOutput { - s.FederatedUser = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *GetFederationTokenOutput) SetPackedPolicySize(v int64) *GetFederationTokenOutput { - s.PackedPolicySize = &v - return s -} - -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionTokenRequest -type GetSessionTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129600 - // seconds (36 hours), with 43200 seconds (12 hours) as the default. Sessions - // for AWS account owners are restricted to a maximum of 3600 seconds (one hour). - // If the duration is longer than one hour, the session for AWS account owners - // defaults to one hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // The identification number of the MFA device that is associated with the IAM - // user who is making the GetSessionToken call. Specify this value if the IAM - // user has a policy that requires MFA authentication. The value is either the - // serial number for a hardware device (such as GAHT12345678) or an Amazon Resource - // Name (ARN) for a virtual device (such as arn:aws:iam::123456789012:mfa/user). - // You can find the device for an IAM user by going to the AWS Management Console - // and viewing the user's security credentials. - // - // The regex used to validated this parameter is a string of characters consisting - // of upper- and lower-case alphanumeric characters with no spaces. You can - // also include underscores or any of the following characters: =,.@:/- - SerialNumber *string `min:"9" type:"string"` - - // The value provided by the MFA device, if MFA is required. If any policy requires - // the IAM user to submit an MFA code, specify this value. If MFA authentication - // is required, and the user does not provide a code when requesting a set of - // temporary security credentials, the user will receive an "access denied" - // response when requesting resources that require MFA authentication. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s GetSessionTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetSessionTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetSessionTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetSessionTokenInput) SetDurationSeconds(v int64) *GetSessionTokenInput { - s.DurationSeconds = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *GetSessionTokenInput) SetSerialNumber(v string) *GetSessionTokenInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *GetSessionTokenInput) SetTokenCode(v string) *GetSessionTokenInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful GetSessionToken request, including -// temporary AWS credentials that can be used to make AWS requests. -// Please also see https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionTokenResponse -type GetSessionTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` -} - -// String returns the string representation -func (s GetSessionTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetSessionTokenOutput) SetCredentials(v *Credentials) *GetSessionTokenOutput { - s.Credentials = v - return s -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go deleted file mode 100644 index 4010cc7fa1..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go +++ /dev/null @@ -1,12 +0,0 @@ -package sts - -import "github.com/aws/aws-sdk-go/aws/request" - -func init() { - initRequest = func(r *request.Request) { - switch r.Operation.Name { - case opAssumeRoleWithSAML, opAssumeRoleWithWebIdentity: - r.Handlers.Sign.Clear() // these operations are unsigned - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go deleted file mode 100644 index d2af518cfa..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ /dev/null @@ -1,124 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package sts provides the client and types for making API -// requests to AWS Security Token Service. -// -// The AWS Security Token Service (STS) is a web service that enables you to -// request temporary, limited-privilege credentials for AWS Identity and Access -// Management (IAM) users or for users that you authenticate (federated users). -// This guide provides descriptions of the STS API. For more detailed information -// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). -// -// As an alternative to using the API, you can use one of the AWS SDKs, which -// consist of libraries and sample code for various programming languages and -// platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient -// way to create programmatic access to STS. For example, the SDKs take care -// of cryptographically signing requests, managing errors, and retrying requests -// automatically. For information about the AWS SDKs, including how to download -// and install them, see the Tools for Amazon Web Services page (http://aws.amazon.com/tools/). -// -// For information about setting up signatures and authorization through the -// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about the Query API, -// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in Using IAM. For information about using security tokens with other AWS -// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) -// in the IAM User Guide. -// -// If you're new to AWS and need additional technical information about a specific -// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/ -// (http://aws.amazon.com/documentation/). -// -// Endpoints -// -// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com -// that maps to the US East (N. Virginia) region. Additional regions are available -// and are activated by default. For more information, see Activating and Deactivating -// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) -// in the AWS General Reference. -// -// Recording API requests -// -// STS supports AWS CloudTrail, which is a service that records AWS calls for -// your AWS account and delivers log files to an Amazon S3 bucket. By using -// information collected by CloudTrail, you can determine what requests were -// successfully made to STS, who made the request, when it was made, and so -// on. To learn more about CloudTrail, including how to turn it on and find -// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). -// -// See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. -// -// See sts package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/ -// -// Using the Client -// -// To use the client for AWS Security Token Service you will first need -// to create a new instance of it. -// -// When creating a client for an AWS service you'll first need to have a Session -// already created. The Session provides configuration that can be shared -// between multiple service clients. Additional configuration can be applied to -// the Session and service's client when they are constructed. The aws package's -// Config type contains several fields such as Region for the AWS Region the -// client should make API requests too. The optional Config value can be provided -// as the variadic argument for Sessions and client creation. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// // Create a session to share configuration, and load external configuration. -// sess := session.Must(session.NewSession()) -// -// // Create the service's client with the session. -// svc := sts.New(sess) -// -// See the SDK's documentation for more information on how to use service clients. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws package's Config type for more information on configuration options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS Security Token Service client STS for more -// information on creating the service's client. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. -// -// The API method will document which error codes the service can be returned -// by the operation if the service models the API operation's errors. These -// errors will also be available as const strings prefixed with "ErrCode". -// -// result, err := svc.AssumeRole(params) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == { -// // Specific error code handling -// } -// return err -// } -// -// fmt.Println("AssumeRole result:") -// fmt.Println(result) -// -// Using the Client with Context -// -// The service's client also provides methods to make API requests with a Context -// value. This allows you to control the timeout, and cancellation of pending -// requests. These methods also take request Option as variadic parameter to apply -// additional configuration to the API request. -// -// ctx := context.Background() -// -// result, err := svc.AssumeRoleWithContext(ctx, params) -// -// See the request package documentation for more information on using Context pattern -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/request/ -package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go deleted file mode 100644 index e24884ef37..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -const ( - - // ErrCodeExpiredTokenException for service response error code - // "ExpiredTokenException". - // - // The web identity token that was passed is expired or is not valid. Get a - // new identity token from the identity provider and then retry the request. - ErrCodeExpiredTokenException = "ExpiredTokenException" - - // ErrCodeIDPCommunicationErrorException for service response error code - // "IDPCommunicationError". - // - // The request could not be fulfilled because the non-AWS identity provider - // (IDP) that was asked to verify the incoming identity token could not be reached. - // This is often a transient error caused by network conditions. Retry the request - // a limited number of times so that you don't exceed the request rate. If the - // error persists, the non-AWS identity provider might be down or not responding. - ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" - - // ErrCodeIDPRejectedClaimException for service response error code - // "IDPRejectedClaim". - // - // The identity provider (IdP) reported that authentication failed. This might - // be because the claim is invalid. - // - // If this error is returned for the AssumeRoleWithWebIdentity operation, it - // can also mean that the claim has expired or has been explicitly revoked. - ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" - - // ErrCodeInvalidAuthorizationMessageException for service response error code - // "InvalidAuthorizationMessageException". - // - // The error returned if the message passed to DecodeAuthorizationMessage was - // invalid. This can happen if the token contains invalid characters, such as - // linebreaks. - ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" - - // ErrCodeInvalidIdentityTokenException for service response error code - // "InvalidIdentityToken". - // - // The web identity token that was passed could not be validated by AWS. Get - // a new identity token from the identity provider and then retry the request. - ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" - - // ErrCodeMalformedPolicyDocumentException for service response error code - // "MalformedPolicyDocument". - // - // The request was rejected because the policy document was malformed. The error - // message describes the specific error. - ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" - - // ErrCodePackedPolicyTooLargeException for service response error code - // "PackedPolicyTooLarge". - // - // The request was rejected because the policy document was too large. The error - // message describes how big the policy document is, in packed form, as a percentage - // of what the API allows. - ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" - - // ErrCodeRegionDisabledException for service response error code - // "RegionDisabledException". - // - // STS is not activated in the requested region for the account that is being - // asked to generate credentials. The account administrator must use the IAM - // console to activate STS in that region. For more information, see Activating - // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) - // in the IAM User Guide. - ErrCodeRegionDisabledException = "RegionDisabledException" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go deleted file mode 100644 index 1ee5839e04..0000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/query" -) - -// STS provides the API operation methods for making requests to -// AWS Security Token Service. See this package's package overview docs -// for details on the service. -// -// STS methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type STS struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "sts" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. -) - -// New creates a new instance of the STS client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a STS client from just a session. -// svc := sts.New(mySession) -// -// // Create a STS client with additional configuration -// svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *STS { - svc := &STS{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2011-06-15", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a STS operation and runs any -// custom request initialization. -func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/awslabs/goformation/CONTRIBUTING.md b/vendor/github.com/awslabs/goformation/CONTRIBUTING.md deleted file mode 100644 index f5c85f6d96..0000000000 --- a/vendor/github.com/awslabs/goformation/CONTRIBUTING.md +++ /dev/null @@ -1,29 +0,0 @@ -# Contributing to GoFormation - -Contributions to GoFormation should be made via GitHub [pull -requests](https://github.com/awslabs/goformation/pulls) and discussed using -GitHub [issues](https://github.com/awslabs/goformation/issues). - -### Before you start - -If you would like to make a significant change, it's a good idea to first open -an issue to discuss it. - -### Making the request - -1. Create a fork of the GoFormation repository [(quick link)](https://github.com/awslabs/goformation#fork-destination-box) -2. Commit your changes to your fork -3. Create a new pull request [(quick link)](https://github.com/awslabs/goformation/compare) - -### Testing - -Any contributions should pass all tests, including those not run by our -current CI system. - -You may run all tests by running `go test` (requires `go` to be installed). - -## Licensing - -GoFormation is released under an [Apache 2.0](http://aws.amazon.com/apache-2-0/) license. Any code you submit will be released under that license. - -For significant changes, we may ask you to sign a [Contributor License Agreement (http://en.wikipedia.org/wiki/Contributor_License_Agreement). diff --git a/vendor/github.com/awslabs/goformation/LICENSE b/vendor/github.com/awslabs/goformation/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/vendor/github.com/awslabs/goformation/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/awslabs/goformation/NOTICE b/vendor/github.com/awslabs/goformation/NOTICE deleted file mode 100644 index 595536ae35..0000000000 --- a/vendor/github.com/awslabs/goformation/NOTICE +++ /dev/null @@ -1,2 +0,0 @@ -GoFormation -Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/vendor/github.com/awslabs/goformation/README.md b/vendor/github.com/awslabs/goformation/README.md deleted file mode 100644 index b69daad2fd..0000000000 --- a/vendor/github.com/awslabs/goformation/README.md +++ /dev/null @@ -1,225 +0,0 @@ -# AWS GoFormation - -[![Build Status](https://travis-ci.org/awslabs/goformation.svg?branch=0.1.0)](https://travis-ci.org/awslabs/goformation) [![GoDoc Reference](https://godoc.org/gopkg.in/awslabs/goformation.v1?status.svg)](http://godoc.org/github.com/awslabs/goformation) ![Apache-2.0](https://img.shields.io/badge/Licence-Apache%202.0-blue.svg) - -`GoFormation` is a Go library for working with AWS CloudFormation / AWS Serverless Application Model (SAM) templates. -- [AWS GoFormation](#aws-goformation) - - [Main features](#main-features) - - [Installation](#installation) - - [Usage](#usage) - - [Marshalling CloudFormation/SAM described with Go structs, into YAML/JSON](#marshalling-cloudformationsam-described-with-go-structs-into-yamljson) - - [Unmarshalling CloudFormation YAML/JSON into Go structs](#unmarshalling-cloudformation-yamljson-into-go-structs) - - [Updating CloudFormation / SAM Resources in GoFormation](#updating-cloudformation-sam-resources-in-goformation) - - [Advanced](#advanced) - - [AWS CloudFormation Intrinsic Functions](#aws-cloudformation-intrinsic-functions) - - [Resolving References (Ref)](#resolving-references-ref) - - [Contributing](#contributing) - -## Main features - - * Describe AWS CloudFormation and AWS SAM templates as Go objects (structs), and then turn it into JSON/YAML. - * Parse JSON/YAML AWS CloudFormation and AWS SAM templates and turn them into Go structs. - * Strongly typed Go structs generated for every AWS CloudFormation and AWS SAM resource. - * Automatically generated, from the published AWS CloudFormation Resource Specification. - -## Installation - -As with other Go libraries, GoFormation can be installed with `go get`. - -``` -$ go get github.com/awslabs/goformation -``` - -## Usage - -### Marshalling CloudFormation/SAM described with Go structs, into YAML/JSON - -Below is an example of building a CloudFormation template programmatically, then outputting the resulting JSON - -```go -package main - -import ( - "fmt" - - "github.com/awslabs/goformation/cloudformation" -) - -func main() { - - // Create a new CloudFormation template - template := cloudformation.NewTemplate() - - // An an example SNS Topic - template.Resources["MySNSTopic"] = &cloudformation.AWSSNSTopic{ - DisplayName: "test-sns-topic-display-name", - TopicName: "test-sns-topic-name", - Subscription: []cloudformation.AWSSNSTopic_Subscription{ - cloudformation.AWSSNSTopic_Subscription{ - Endpoint: "test-sns-topic-subscription-endpoint", - Protocol: "test-sns-topic-subscription-protocol", - }, - }, - } - - // ...and a Route 53 Hosted Zone too - template.Resources["MyRoute53HostedZone"] = &cloudformation.AWSRoute53HostedZone{ - Name: "example.com", - } - - // Let's see the JSON - j, err := template.JSON() - if err != nil { - fmt.Printf("Failed to generate JSON: %s\n", err) - } else { - fmt.Printf("%s\n", string(j)) - } - - y, err := template.YAML() - if err != nil { - fmt.Printf("Failed to generate YAML: %s\n", err) - } else { - fmt.Printf("%s\n", string(y)) - } - -} -``` - -Would output the following JSON template: - -```javascript -{ - "AWSTemplateFormatVersion": "2010-09-09", - "Resources": { - "MyRoute53HostedZone": { - "Type": "AWS::Route53::HostedZone", - "Properties": { - "Name": "example.com" - } - }, - "MySNSTopic": { - "Type": "AWS::SNS::Topic", - "Properties": { - "DisplayName": "test-sns-topic-display-name", - "Subscription": [ - { - "Endpoint": "test-sns-topic-subscription-endpoint", - "Protocol": "test-sns-topic-subscription-protocol" - } - ], - "TopicName": "test-sns-topic-name" - } - } - } -} -``` - -...and the following YAML template: - -```yaml -AWSTemplateFormatVersion: 2010-09-09 -Resources: - MyRoute53HostedZone: - Type: AWS::Route53::HostedZone - Properties: - Name: example.com - MySNSTopic: - Type: AWS::SNS::Topic - Properties: - DisplayName: test-sns-topic-display-name - Subscription: - - Endpoint: test-sns-topic-subscription-endpoint - Protocol: test-sns-topic-subscription-protocol - TopicName: test-sns-topic-name -``` - - -### Unmarshalling CloudFormation YAML/JSON into Go structs - -GoFormation also works the other way - parsing JSON/YAML CloudFormation/SAM templates into Go structs. - -```go -package main - -import ( - "fmt" - "github.com/awslabs/goformation" - "github.com/awslabs/goformation/cloudformation" -) - -func main() { - - // Open a template from file (can be JSON or YAML) - template, err := goformation.Open("template.yaml") - - // ...or provide one as a byte array ([]byte) - template, err := goformation.ParseYAML(data) - - // You can then inspect all of the values - for name, resource := range template.Resources { - - // E.g. Found a resource with name MyLambdaFunction and type AWS::Lambda::Function - log.Printf("Found a resource with name %s and type %s", name, resource.Type) - - } - - // You can extract all resources of a certain type - // Each AWS CloudFormation / SAM resource is a strongly typed struct - functions := template.GetAllAWSLambdaFunctionResources() - for name, function := range functions { - - // E.g. Found a AWS::Lambda::Function with name MyLambdaFunction and nodejs6.10 handler - log.Printf("Found a %s with name %s and %s handler", name, function.Type(), function.Handler) - - } - -} -``` - -## Updating CloudFormation / SAM Resources in GoFormation - -AWS GoFormation contains automatically generated Go structs for every CloudFormation/SAM resource, located in the [cloudformation/](cloudformation/) directory. These can be generated, from the latest [AWS CloudFormation Resource Specification](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html) published for `us-east-1` by just running `go generate`: - -``` -$ go generate - -Generated 587 AWS CloudFormation resources from specification v1.4.2 -Generated 17 AWS SAM resources from specification v2016-10-31 -Generated JSON Schema: schema/cloudformation.schema.json -``` - -The GoFormation build pipeline automatically checks for any updated AWS CloudFormation resources on a daily basis, and creates a pull request against this repository if any are found. - -## Advanced - -### AWS CloudFormation Intrinsic Functions - -The following [AWS CloudFormation Intrinsic Functions](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html) are supported in GoFormation: - -- [x] [Fn::Base64](intrinsics/fnbase64.go) -- [x] [Fn::FindInMap](intrinsics/fnfindinmap.go) -- [x] [Fn::Join](intrinsics/fnjoin.go) -- [x] [Fn::Select](intrinsics/fnselect.go) -- [x] [Fn::Split](intrinsics/fnsplit.go) -- [x] [Fn::Sub](intrinsics/fnsub.go) -- [x] [Ref](intrinsics/ref.go) -- [x] [Fn::And](intrinsics/fnand.go) -- [x] [Fn::Equals](intrinsics/fnequals.go) -- [x] [Fn::If](intrinsics/fnif.go) -- [x] [Fn::Not](intrinsics/fnnot.go) -- [x] [Fn::Or](intrinsics/fnor.go) -- [ ] Fn::GetAtt -- [x] [Fn::GetAZs](intrinsics/fngetazs.go) -- [ ] Fn::ImportValue - -Any unsupported intrinsic functions will return `nil`. - -#### Resolving References (Ref) - -The intrinsic 'Ref' function as implemented will resolve all of the [pseudo parameters](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html) such as `AWS::AccountId` with their default value as listed on [the bottom of this page](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html). - -If a reference is not a pseudo parameter, GoFormation will try to resolve it within the AWS CloudFormation template. **Currently, this implementation only searches for `Parameters` with a name that matches the ref, and returns the `Default` if it has one.** - -## Contributing - -Contributions and feedback are welcome! Proposals and pull requests will be considered and responded to. For more information, see the [CONTRIBUTING](CONTRIBUTING.md) file. diff --git a/vendor/github.com/awslabs/goformation/cloudformation/README.md b/vendor/github.com/awslabs/goformation/cloudformation/README.md deleted file mode 100644 index a1e31aab26..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/README.md +++ /dev/null @@ -1,5 +0,0 @@ -### Important - -All resource files in this directory are auto-generated by running 'go generate' in the repository root directory. - -Do not manually edit any of generated resource files \ No newline at end of file diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-account.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-account.go deleted file mode 100644 index 1603a5da74..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-account.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayAccount AWS CloudFormation Resource (AWS::ApiGateway::Account) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-account.html -type AWSApiGatewayAccount struct { - - // CloudWatchRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-account.html#cfn-apigateway-account-cloudwatchrolearn - CloudWatchRoleArn string `json:"CloudWatchRoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayAccount) AWSCloudFormationType() string { - return "AWS::ApiGateway::Account" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayAccount) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayAccount - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayAccount) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayAccount - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayAccount(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayAccountResources retrieves all AWSApiGatewayAccount items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayAccountResources() map[string]AWSApiGatewayAccount { - results := map[string]AWSApiGatewayAccount{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayAccount: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Account" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayAccount - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayAccountWithName retrieves all AWSApiGatewayAccount items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayAccountWithName(name string) (AWSApiGatewayAccount, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayAccount: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Account" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayAccount - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayAccount{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey.go deleted file mode 100644 index f4dc531547..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayApiKey AWS CloudFormation Resource (AWS::ApiGateway::ApiKey) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html -type AWSApiGatewayApiKey struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apigateway-apikey-description - Description string `json:"Description,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apigateway-apikey-enabled - Enabled bool `json:"Enabled,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apigateway-apikey-name - Name string `json:"Name,omitempty"` - - // StageKeys AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-apikey.html#cfn-apigateway-apigateway-apikey-stagekeys - StageKeys []AWSApiGatewayApiKey_StageKey `json:"StageKeys,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayApiKey) AWSCloudFormationType() string { - return "AWS::ApiGateway::ApiKey" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayApiKey) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayApiKey - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayApiKey) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayApiKey - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayApiKey(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayApiKeyResources retrieves all AWSApiGatewayApiKey items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayApiKeyResources() map[string]AWSApiGatewayApiKey { - results := map[string]AWSApiGatewayApiKey{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayApiKey: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::ApiKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayApiKey - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayApiKeyWithName retrieves all AWSApiGatewayApiKey items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayApiKeyWithName(name string) (AWSApiGatewayApiKey, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayApiKey: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::ApiKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayApiKey - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayApiKey{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey_stagekey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey_stagekey.go deleted file mode 100644 index c275afa146..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-apikey_stagekey.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSApiGatewayApiKey_StageKey AWS CloudFormation Resource (AWS::ApiGateway::ApiKey.StageKey) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-apikey-stagekey.html -type AWSApiGatewayApiKey_StageKey struct { - - // RestApiId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-apikey-stagekey.html#cfn-apigateway-apikey-stagekey-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // StageName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-apikey-stagekey.html#cfn-apigateway-apikey-stagekey-stagename - StageName string `json:"StageName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayApiKey_StageKey) AWSCloudFormationType() string { - return "AWS::ApiGateway::ApiKey.StageKey" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-authorizer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-authorizer.go deleted file mode 100644 index 1cb95efb88..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-authorizer.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayAuthorizer AWS CloudFormation Resource (AWS::ApiGateway::Authorizer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html -type AWSApiGatewayAuthorizer struct { - - // AuthType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-authtype - AuthType string `json:"AuthType,omitempty"` - - // AuthorizerCredentials AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-authorizercredentials - AuthorizerCredentials string `json:"AuthorizerCredentials,omitempty"` - - // AuthorizerResultTtlInSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-authorizerresultttlinseconds - AuthorizerResultTtlInSeconds int `json:"AuthorizerResultTtlInSeconds,omitempty"` - - // AuthorizerUri AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-authorizeruri - AuthorizerUri string `json:"AuthorizerUri,omitempty"` - - // IdentitySource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-identitysource - IdentitySource string `json:"IdentitySource,omitempty"` - - // IdentityValidationExpression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-identityvalidationexpression - IdentityValidationExpression string `json:"IdentityValidationExpression,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-name - Name string `json:"Name,omitempty"` - - // ProviderARNs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-providerarns - ProviderARNs []string `json:"ProviderARNs,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-authorizer.html#cfn-apigateway-authorizer-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayAuthorizer) AWSCloudFormationType() string { - return "AWS::ApiGateway::Authorizer" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayAuthorizer) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayAuthorizer - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayAuthorizer) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayAuthorizer - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayAuthorizer(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayAuthorizerResources retrieves all AWSApiGatewayAuthorizer items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayAuthorizerResources() map[string]AWSApiGatewayAuthorizer { - results := map[string]AWSApiGatewayAuthorizer{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayAuthorizer: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Authorizer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayAuthorizer - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayAuthorizerWithName retrieves all AWSApiGatewayAuthorizer items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayAuthorizerWithName(name string) (AWSApiGatewayAuthorizer, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayAuthorizer: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Authorizer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayAuthorizer - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayAuthorizer{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-basepathmapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-basepathmapping.go deleted file mode 100644 index 31b96f3057..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-basepathmapping.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayBasePathMapping AWS CloudFormation Resource (AWS::ApiGateway::BasePathMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html -type AWSApiGatewayBasePathMapping struct { - - // BasePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html#cfn-apigateway-basepathmapping-basepath - BasePath string `json:"BasePath,omitempty"` - - // DomainName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html#cfn-apigateway-basepathmapping-domainname - DomainName string `json:"DomainName,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html#cfn-apigateway-basepathmapping-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // Stage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-basepathmapping.html#cfn-apigateway-basepathmapping-stage - Stage string `json:"Stage,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayBasePathMapping) AWSCloudFormationType() string { - return "AWS::ApiGateway::BasePathMapping" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayBasePathMapping) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayBasePathMapping - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayBasePathMapping) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayBasePathMapping - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayBasePathMapping(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayBasePathMappingResources retrieves all AWSApiGatewayBasePathMapping items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayBasePathMappingResources() map[string]AWSApiGatewayBasePathMapping { - results := map[string]AWSApiGatewayBasePathMapping{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayBasePathMapping: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::BasePathMapping" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayBasePathMapping - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayBasePathMappingWithName retrieves all AWSApiGatewayBasePathMapping items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayBasePathMappingWithName(name string) (AWSApiGatewayBasePathMapping, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayBasePathMapping: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::BasePathMapping" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayBasePathMapping - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayBasePathMapping{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-clientcertificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-clientcertificate.go deleted file mode 100644 index 50602f10e7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-clientcertificate.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayClientCertificate AWS CloudFormation Resource (AWS::ApiGateway::ClientCertificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-clientcertificate.html -type AWSApiGatewayClientCertificate struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-clientcertificate.html#cfn-apigateway-clientcertificate-description - Description string `json:"Description,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayClientCertificate) AWSCloudFormationType() string { - return "AWS::ApiGateway::ClientCertificate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayClientCertificate) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayClientCertificate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayClientCertificate) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayClientCertificate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayClientCertificate(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayClientCertificateResources retrieves all AWSApiGatewayClientCertificate items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayClientCertificateResources() map[string]AWSApiGatewayClientCertificate { - results := map[string]AWSApiGatewayClientCertificate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayClientCertificate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::ClientCertificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayClientCertificate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayClientCertificateWithName retrieves all AWSApiGatewayClientCertificate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayClientCertificateWithName(name string) (AWSApiGatewayClientCertificate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayClientCertificate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::ClientCertificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayClientCertificate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayClientCertificate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment.go deleted file mode 100644 index 2f148c4893..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayDeployment AWS CloudFormation Resource (AWS::ApiGateway::Deployment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html -type AWSApiGatewayDeployment struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html#cfn-apigateway-deployment-description - Description string `json:"Description,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html#cfn-apigateway-deployment-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // StageDescription AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html#cfn-apigateway-deployment-stagedescription - StageDescription *AWSApiGatewayDeployment_StageDescription `json:"StageDescription,omitempty"` - - // StageName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-deployment.html#cfn-apigateway-deployment-stagename - StageName string `json:"StageName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDeployment) AWSCloudFormationType() string { - return "AWS::ApiGateway::Deployment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayDeployment) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayDeployment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayDeployment) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayDeployment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayDeployment(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayDeploymentResources retrieves all AWSApiGatewayDeployment items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayDeploymentResources() map[string]AWSApiGatewayDeployment { - results := map[string]AWSApiGatewayDeployment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayDeployment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Deployment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDeployment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayDeploymentWithName retrieves all AWSApiGatewayDeployment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayDeploymentWithName(name string) (AWSApiGatewayDeployment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayDeployment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Deployment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDeployment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayDeployment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_methodsetting.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_methodsetting.go deleted file mode 100644 index e9849b1cf2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_methodsetting.go +++ /dev/null @@ -1,61 +0,0 @@ -package cloudformation - -// AWSApiGatewayDeployment_MethodSetting AWS CloudFormation Resource (AWS::ApiGateway::Deployment.MethodSetting) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html -type AWSApiGatewayDeployment_MethodSetting struct { - - // CacheDataEncrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-cachedataencrypted - CacheDataEncrypted bool `json:"CacheDataEncrypted,omitempty"` - - // CacheTtlInSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-cachettlinseconds - CacheTtlInSeconds int `json:"CacheTtlInSeconds,omitempty"` - - // CachingEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-cachingenabled - CachingEnabled bool `json:"CachingEnabled,omitempty"` - - // DataTraceEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-datatraceenabled - DataTraceEnabled bool `json:"DataTraceEnabled,omitempty"` - - // HttpMethod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-httpmethod - HttpMethod string `json:"HttpMethod,omitempty"` - - // LoggingLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-logginglevel - LoggingLevel string `json:"LoggingLevel,omitempty"` - - // MetricsEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-metricsenabled - MetricsEnabled bool `json:"MetricsEnabled,omitempty"` - - // ResourcePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-resourcepath - ResourcePath string `json:"ResourcePath,omitempty"` - - // ThrottlingBurstLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-throttlingburstlimit - ThrottlingBurstLimit int `json:"ThrottlingBurstLimit,omitempty"` - - // ThrottlingRateLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription-methodsetting.html#cfn-apigateway-deployment-stagedescription-methodsetting-throttlingratelimit - ThrottlingRateLimit float64 `json:"ThrottlingRateLimit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDeployment_MethodSetting) AWSCloudFormationType() string { - return "AWS::ApiGateway::Deployment.MethodSetting" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_stagedescription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_stagedescription.go deleted file mode 100644 index 684e030784..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-deployment_stagedescription.go +++ /dev/null @@ -1,86 +0,0 @@ -package cloudformation - -// AWSApiGatewayDeployment_StageDescription AWS CloudFormation Resource (AWS::ApiGateway::Deployment.StageDescription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html -type AWSApiGatewayDeployment_StageDescription struct { - - // CacheClusterEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-cacheclusterenabled - CacheClusterEnabled bool `json:"CacheClusterEnabled,omitempty"` - - // CacheClusterSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-cacheclustersize - CacheClusterSize string `json:"CacheClusterSize,omitempty"` - - // CacheDataEncrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-cachedataencrypted - CacheDataEncrypted bool `json:"CacheDataEncrypted,omitempty"` - - // CacheTtlInSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-cachettlinseconds - CacheTtlInSeconds int `json:"CacheTtlInSeconds,omitempty"` - - // CachingEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-cachingenabled - CachingEnabled bool `json:"CachingEnabled,omitempty"` - - // ClientCertificateId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-clientcertificateid - ClientCertificateId string `json:"ClientCertificateId,omitempty"` - - // DataTraceEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-datatraceenabled - DataTraceEnabled bool `json:"DataTraceEnabled,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-description - Description string `json:"Description,omitempty"` - - // DocumentationVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-documentationversion - DocumentationVersion string `json:"DocumentationVersion,omitempty"` - - // LoggingLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-logginglevel - LoggingLevel string `json:"LoggingLevel,omitempty"` - - // MethodSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-methodsettings - MethodSettings []AWSApiGatewayDeployment_MethodSetting `json:"MethodSettings,omitempty"` - - // MetricsEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-metricsenabled - MetricsEnabled bool `json:"MetricsEnabled,omitempty"` - - // ThrottlingBurstLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-throttlingburstlimit - ThrottlingBurstLimit int `json:"ThrottlingBurstLimit,omitempty"` - - // ThrottlingRateLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-throttlingratelimit - ThrottlingRateLimit float64 `json:"ThrottlingRateLimit,omitempty"` - - // Variables AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-deployment-stagedescription.html#cfn-apigateway-deployment-stagedescription-variables - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDeployment_StageDescription) AWSCloudFormationType() string { - return "AWS::ApiGateway::Deployment.StageDescription" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart.go deleted file mode 100644 index e55daa97bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayDocumentationPart AWS CloudFormation Resource (AWS::ApiGateway::DocumentationPart) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationpart.html -type AWSApiGatewayDocumentationPart struct { - - // Location AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationpart.html#cfn-apigateway-documentationpart-location - Location *AWSApiGatewayDocumentationPart_Location `json:"Location,omitempty"` - - // Properties AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationpart.html#cfn-apigateway-documentationpart-properties - Properties string `json:"Properties,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationpart.html#cfn-apigateway-documentationpart-restapiid - RestApiId string `json:"RestApiId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDocumentationPart) AWSCloudFormationType() string { - return "AWS::ApiGateway::DocumentationPart" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayDocumentationPart) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayDocumentationPart - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayDocumentationPart) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayDocumentationPart - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayDocumentationPart(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayDocumentationPartResources retrieves all AWSApiGatewayDocumentationPart items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayDocumentationPartResources() map[string]AWSApiGatewayDocumentationPart { - results := map[string]AWSApiGatewayDocumentationPart{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayDocumentationPart: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DocumentationPart" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDocumentationPart - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayDocumentationPartWithName retrieves all AWSApiGatewayDocumentationPart items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayDocumentationPartWithName(name string) (AWSApiGatewayDocumentationPart, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayDocumentationPart: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DocumentationPart" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDocumentationPart - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayDocumentationPart{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart_location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart_location.go deleted file mode 100644 index 4189f180ca..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationpart_location.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSApiGatewayDocumentationPart_Location AWS CloudFormation Resource (AWS::ApiGateway::DocumentationPart.Location) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html -type AWSApiGatewayDocumentationPart_Location struct { - - // Method AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html#cfn-apigateway-documentationpart-location-method - Method string `json:"Method,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html#cfn-apigateway-documentationpart-location-name - Name string `json:"Name,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html#cfn-apigateway-documentationpart-location-path - Path string `json:"Path,omitempty"` - - // StatusCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html#cfn-apigateway-documentationpart-location-statuscode - StatusCode string `json:"StatusCode,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-documentationpart-location.html#cfn-apigateway-documentationpart-location-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDocumentationPart_Location) AWSCloudFormationType() string { - return "AWS::ApiGateway::DocumentationPart.Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationversion.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationversion.go deleted file mode 100644 index 137c0cfb02..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-documentationversion.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayDocumentationVersion AWS CloudFormation Resource (AWS::ApiGateway::DocumentationVersion) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationversion.html -type AWSApiGatewayDocumentationVersion struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationversion.html#cfn-apigateway-documentationversion-description - Description string `json:"Description,omitempty"` - - // DocumentationVersion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationversion.html#cfn-apigateway-documentationversion-documentationversion - DocumentationVersion string `json:"DocumentationVersion,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-documentationversion.html#cfn-apigateway-documentationversion-restapiid - RestApiId string `json:"RestApiId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDocumentationVersion) AWSCloudFormationType() string { - return "AWS::ApiGateway::DocumentationVersion" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayDocumentationVersion) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayDocumentationVersion - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayDocumentationVersion) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayDocumentationVersion - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayDocumentationVersion(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayDocumentationVersionResources retrieves all AWSApiGatewayDocumentationVersion items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayDocumentationVersionResources() map[string]AWSApiGatewayDocumentationVersion { - results := map[string]AWSApiGatewayDocumentationVersion{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayDocumentationVersion: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DocumentationVersion" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDocumentationVersion - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayDocumentationVersionWithName retrieves all AWSApiGatewayDocumentationVersion items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayDocumentationVersionWithName(name string) (AWSApiGatewayDocumentationVersion, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayDocumentationVersion: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DocumentationVersion" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDocumentationVersion - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayDocumentationVersion{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-domainname.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-domainname.go deleted file mode 100644 index 2dd1458269..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-domainname.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayDomainName AWS CloudFormation Resource (AWS::ApiGateway::DomainName) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-domainname.html -type AWSApiGatewayDomainName struct { - - // CertificateArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-domainname.html#cfn-apigateway-domainname-certificatearn - CertificateArn string `json:"CertificateArn,omitempty"` - - // DomainName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-domainname.html#cfn-apigateway-domainname-domainname - DomainName string `json:"DomainName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayDomainName) AWSCloudFormationType() string { - return "AWS::ApiGateway::DomainName" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayDomainName) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayDomainName - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayDomainName) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayDomainName - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayDomainName(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayDomainNameResources retrieves all AWSApiGatewayDomainName items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayDomainNameResources() map[string]AWSApiGatewayDomainName { - results := map[string]AWSApiGatewayDomainName{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayDomainName: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DomainName" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDomainName - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayDomainNameWithName retrieves all AWSApiGatewayDomainName items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayDomainNameWithName(name string) (AWSApiGatewayDomainName, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayDomainName: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::DomainName" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayDomainName - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayDomainName{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-gatewayresponse.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-gatewayresponse.go deleted file mode 100644 index ed4e03851e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-gatewayresponse.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayGatewayResponse AWS CloudFormation Resource (AWS::ApiGateway::GatewayResponse) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html -type AWSApiGatewayGatewayResponse struct { - - // ResponseParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html#cfn-apigateway-gatewayresponse-responseparameters - ResponseParameters map[string]string `json:"ResponseParameters,omitempty"` - - // ResponseTemplates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html#cfn-apigateway-gatewayresponse-responsetemplates - ResponseTemplates map[string]string `json:"ResponseTemplates,omitempty"` - - // ResponseType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html#cfn-apigateway-gatewayresponse-responsetype - ResponseType string `json:"ResponseType,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html#cfn-apigateway-gatewayresponse-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // StatusCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-gatewayresponse.html#cfn-apigateway-gatewayresponse-statuscode - StatusCode string `json:"StatusCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayGatewayResponse) AWSCloudFormationType() string { - return "AWS::ApiGateway::GatewayResponse" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayGatewayResponse) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayGatewayResponse - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayGatewayResponse) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayGatewayResponse - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayGatewayResponse(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayGatewayResponseResources retrieves all AWSApiGatewayGatewayResponse items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayGatewayResponseResources() map[string]AWSApiGatewayGatewayResponse { - results := map[string]AWSApiGatewayGatewayResponse{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayGatewayResponse: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::GatewayResponse" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayGatewayResponse - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayGatewayResponseWithName retrieves all AWSApiGatewayGatewayResponse items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayGatewayResponseWithName(name string) (AWSApiGatewayGatewayResponse, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayGatewayResponse: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::GatewayResponse" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayGatewayResponse - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayGatewayResponse{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method.go deleted file mode 100644 index 76a2b5f541..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method.go +++ /dev/null @@ -1,165 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayMethod AWS CloudFormation Resource (AWS::ApiGateway::Method) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html -type AWSApiGatewayMethod struct { - - // ApiKeyRequired AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-apikeyrequired - ApiKeyRequired bool `json:"ApiKeyRequired,omitempty"` - - // AuthorizationType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-authorizationtype - AuthorizationType string `json:"AuthorizationType,omitempty"` - - // AuthorizerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-authorizerid - AuthorizerId string `json:"AuthorizerId,omitempty"` - - // HttpMethod AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-httpmethod - HttpMethod string `json:"HttpMethod,omitempty"` - - // Integration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-integration - Integration *AWSApiGatewayMethod_Integration `json:"Integration,omitempty"` - - // MethodResponses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-methodresponses - MethodResponses []AWSApiGatewayMethod_MethodResponse `json:"MethodResponses,omitempty"` - - // OperationName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-operationname - OperationName string `json:"OperationName,omitempty"` - - // RequestModels AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-requestmodels - RequestModels map[string]string `json:"RequestModels,omitempty"` - - // RequestParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-requestparameters - RequestParameters map[string]bool `json:"RequestParameters,omitempty"` - - // RequestValidatorId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-requestvalidatorid - RequestValidatorId string `json:"RequestValidatorId,omitempty"` - - // ResourceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-resourceid - ResourceId string `json:"ResourceId,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-method.html#cfn-apigateway-method-restapiid - RestApiId string `json:"RestApiId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayMethod) AWSCloudFormationType() string { - return "AWS::ApiGateway::Method" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayMethod) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayMethod - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayMethod) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayMethod - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayMethod(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayMethodResources retrieves all AWSApiGatewayMethod items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayMethodResources() map[string]AWSApiGatewayMethod { - results := map[string]AWSApiGatewayMethod{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayMethod: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Method" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayMethod - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayMethodWithName retrieves all AWSApiGatewayMethod items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayMethodWithName(name string) (AWSApiGatewayMethod, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayMethod: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Method" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayMethod - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayMethod{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integration.go deleted file mode 100644 index 5f20fa79e2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integration.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudformation - -// AWSApiGatewayMethod_Integration AWS CloudFormation Resource (AWS::ApiGateway::Method.Integration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html -type AWSApiGatewayMethod_Integration struct { - - // CacheKeyParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-cachekeyparameters - CacheKeyParameters []string `json:"CacheKeyParameters,omitempty"` - - // CacheNamespace AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-cachenamespace - CacheNamespace string `json:"CacheNamespace,omitempty"` - - // ContentHandling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-contenthandling - ContentHandling string `json:"ContentHandling,omitempty"` - - // Credentials AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-credentials - Credentials string `json:"Credentials,omitempty"` - - // IntegrationHttpMethod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-integrationhttpmethod - IntegrationHttpMethod string `json:"IntegrationHttpMethod,omitempty"` - - // IntegrationResponses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-integrationresponses - IntegrationResponses []AWSApiGatewayMethod_IntegrationResponse `json:"IntegrationResponses,omitempty"` - - // PassthroughBehavior AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-passthroughbehavior - PassthroughBehavior string `json:"PassthroughBehavior,omitempty"` - - // RequestParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-requestparameters - RequestParameters map[string]string `json:"RequestParameters,omitempty"` - - // RequestTemplates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-requesttemplates - RequestTemplates map[string]string `json:"RequestTemplates,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-type - Type string `json:"Type,omitempty"` - - // Uri AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration.html#cfn-apigateway-method-integration-uri - Uri string `json:"Uri,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayMethod_Integration) AWSCloudFormationType() string { - return "AWS::ApiGateway::Method.Integration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integrationresponse.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integrationresponse.go deleted file mode 100644 index 5534d689f2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_integrationresponse.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSApiGatewayMethod_IntegrationResponse AWS CloudFormation Resource (AWS::ApiGateway::Method.IntegrationResponse) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html -type AWSApiGatewayMethod_IntegrationResponse struct { - - // ContentHandling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html#cfn-apigateway-method-integrationresponse-contenthandling - ContentHandling string `json:"ContentHandling,omitempty"` - - // ResponseParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html#cfn-apigateway-method-integration-integrationresponse-responseparameters - ResponseParameters map[string]string `json:"ResponseParameters,omitempty"` - - // ResponseTemplates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html#cfn-apigateway-method-integration-integrationresponse-responsetemplates - ResponseTemplates map[string]string `json:"ResponseTemplates,omitempty"` - - // SelectionPattern AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html#cfn-apigateway-method-integration-integrationresponse-selectionpattern - SelectionPattern string `json:"SelectionPattern,omitempty"` - - // StatusCode AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-integration-integrationresponse.html#cfn-apigateway-method-integration-integrationresponse-statuscode - StatusCode string `json:"StatusCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayMethod_IntegrationResponse) AWSCloudFormationType() string { - return "AWS::ApiGateway::Method.IntegrationResponse" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_methodresponse.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_methodresponse.go deleted file mode 100644 index 256763cac7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-method_methodresponse.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSApiGatewayMethod_MethodResponse AWS CloudFormation Resource (AWS::ApiGateway::Method.MethodResponse) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html -type AWSApiGatewayMethod_MethodResponse struct { - - // ResponseModels AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-responsemodels - ResponseModels map[string]string `json:"ResponseModels,omitempty"` - - // ResponseParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-responseparameters - ResponseParameters map[string]bool `json:"ResponseParameters,omitempty"` - - // StatusCode AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-method-methodresponse.html#cfn-apigateway-method-methodresponse-statuscode - StatusCode string `json:"StatusCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayMethod_MethodResponse) AWSCloudFormationType() string { - return "AWS::ApiGateway::Method.MethodResponse" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-model.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-model.go deleted file mode 100644 index 2dc019653c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-model.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayModel AWS CloudFormation Resource (AWS::ApiGateway::Model) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html -type AWSApiGatewayModel struct { - - // ContentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html#cfn-apigateway-model-contenttype - ContentType string `json:"ContentType,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html#cfn-apigateway-model-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html#cfn-apigateway-model-name - Name string `json:"Name,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html#cfn-apigateway-model-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // Schema AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-model.html#cfn-apigateway-model-schema - Schema interface{} `json:"Schema,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayModel) AWSCloudFormationType() string { - return "AWS::ApiGateway::Model" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayModel) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayModel - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayModel) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayModel - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayModel(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayModelResources retrieves all AWSApiGatewayModel items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayModelResources() map[string]AWSApiGatewayModel { - results := map[string]AWSApiGatewayModel{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayModel: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Model" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayModel - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayModelWithName retrieves all AWSApiGatewayModel items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayModelWithName(name string) (AWSApiGatewayModel, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayModel: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Model" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayModel - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayModel{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-requestvalidator.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-requestvalidator.go deleted file mode 100644 index 4e68bc16b9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-requestvalidator.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayRequestValidator AWS CloudFormation Resource (AWS::ApiGateway::RequestValidator) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html -type AWSApiGatewayRequestValidator struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html#cfn-apigateway-requestvalidator-name - Name string `json:"Name,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html#cfn-apigateway-requestvalidator-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // ValidateRequestBody AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html#cfn-apigateway-requestvalidator-validaterequestbody - ValidateRequestBody bool `json:"ValidateRequestBody,omitempty"` - - // ValidateRequestParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-requestvalidator.html#cfn-apigateway-requestvalidator-validaterequestparameters - ValidateRequestParameters bool `json:"ValidateRequestParameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayRequestValidator) AWSCloudFormationType() string { - return "AWS::ApiGateway::RequestValidator" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayRequestValidator) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayRequestValidator - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayRequestValidator) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayRequestValidator - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayRequestValidator(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayRequestValidatorResources retrieves all AWSApiGatewayRequestValidator items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayRequestValidatorResources() map[string]AWSApiGatewayRequestValidator { - results := map[string]AWSApiGatewayRequestValidator{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayRequestValidator: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::RequestValidator" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayRequestValidator - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayRequestValidatorWithName retrieves all AWSApiGatewayRequestValidator items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayRequestValidatorWithName(name string) (AWSApiGatewayRequestValidator, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayRequestValidator: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::RequestValidator" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayRequestValidator - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayRequestValidator{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-resource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-resource.go deleted file mode 100644 index cf0eca5122..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-resource.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayResource AWS CloudFormation Resource (AWS::ApiGateway::Resource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html -type AWSApiGatewayResource struct { - - // ParentId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html#cfn-apigateway-resource-parentid - ParentId string `json:"ParentId,omitempty"` - - // PathPart AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html#cfn-apigateway-resource-pathpart - PathPart string `json:"PathPart,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html#cfn-apigateway-resource-restapiid - RestApiId string `json:"RestApiId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayResource) AWSCloudFormationType() string { - return "AWS::ApiGateway::Resource" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayResource) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayResource - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayResource) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayResource - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayResource(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayResourceResources retrieves all AWSApiGatewayResource items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayResourceResources() map[string]AWSApiGatewayResource { - results := map[string]AWSApiGatewayResource{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayResource: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Resource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayResource - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayResourceWithName retrieves all AWSApiGatewayResource items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayResourceWithName(name string) (AWSApiGatewayResource, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayResource: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Resource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayResource - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayResource{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi.go deleted file mode 100644 index 20c8d59727..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayRestApi AWS CloudFormation Resource (AWS::ApiGateway::RestApi) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html -type AWSApiGatewayRestApi struct { - - // BinaryMediaTypes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-binarymediatypes - BinaryMediaTypes []string `json:"BinaryMediaTypes,omitempty"` - - // Body AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-body - Body interface{} `json:"Body,omitempty"` - - // BodyS3Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-bodys3location - BodyS3Location *AWSApiGatewayRestApi_S3Location `json:"BodyS3Location,omitempty"` - - // CloneFrom AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-clonefrom - CloneFrom string `json:"CloneFrom,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-description - Description string `json:"Description,omitempty"` - - // FailOnWarnings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-failonwarnings - FailOnWarnings bool `json:"FailOnWarnings,omitempty"` - - // Mode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-mode - Mode string `json:"Mode,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-name - Name string `json:"Name,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-restapi.html#cfn-apigateway-restapi-parameters - Parameters map[string]string `json:"Parameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayRestApi) AWSCloudFormationType() string { - return "AWS::ApiGateway::RestApi" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayRestApi) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayRestApi - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayRestApi) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayRestApi - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayRestApi(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayRestApiResources retrieves all AWSApiGatewayRestApi items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayRestApiResources() map[string]AWSApiGatewayRestApi { - results := map[string]AWSApiGatewayRestApi{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayRestApi: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::RestApi" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayRestApi - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayRestApiWithName retrieves all AWSApiGatewayRestApi items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayRestApiWithName(name string) (AWSApiGatewayRestApi, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayRestApi: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::RestApi" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayRestApi - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayRestApi{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi_s3location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi_s3location.go deleted file mode 100644 index 56f36a0c09..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-restapi_s3location.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSApiGatewayRestApi_S3Location AWS CloudFormation Resource (AWS::ApiGateway::RestApi.S3Location) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-restapi-bodys3location.html -type AWSApiGatewayRestApi_S3Location struct { - - // Bucket AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-restapi-bodys3location.html#cfn-apigateway-restapi-s3location-bucket - Bucket string `json:"Bucket,omitempty"` - - // ETag AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-restapi-bodys3location.html#cfn-apigateway-restapi-s3location-etag - ETag string `json:"ETag,omitempty"` - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-restapi-bodys3location.html#cfn-apigateway-restapi-s3location-key - Key string `json:"Key,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-restapi-bodys3location.html#cfn-apigateway-restapi-s3location-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayRestApi_S3Location) AWSCloudFormationType() string { - return "AWS::ApiGateway::RestApi.S3Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage.go deleted file mode 100644 index 798b61c2b2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayStage AWS CloudFormation Resource (AWS::ApiGateway::Stage) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html -type AWSApiGatewayStage struct { - - // CacheClusterEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclusterenabled - CacheClusterEnabled bool `json:"CacheClusterEnabled,omitempty"` - - // CacheClusterSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-cacheclustersize - CacheClusterSize string `json:"CacheClusterSize,omitempty"` - - // ClientCertificateId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-clientcertificateid - ClientCertificateId string `json:"ClientCertificateId,omitempty"` - - // DeploymentId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-deploymentid - DeploymentId string `json:"DeploymentId,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-description - Description string `json:"Description,omitempty"` - - // DocumentationVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-documentationversion - DocumentationVersion string `json:"DocumentationVersion,omitempty"` - - // MethodSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-methodsettings - MethodSettings []AWSApiGatewayStage_MethodSetting `json:"MethodSettings,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-restapiid - RestApiId string `json:"RestApiId,omitempty"` - - // StageName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-stagename - StageName string `json:"StageName,omitempty"` - - // Variables AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-stage.html#cfn-apigateway-stage-variables - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayStage) AWSCloudFormationType() string { - return "AWS::ApiGateway::Stage" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayStage) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayStage - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayStage) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayStage - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayStage(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayStageResources retrieves all AWSApiGatewayStage items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayStageResources() map[string]AWSApiGatewayStage { - results := map[string]AWSApiGatewayStage{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayStage: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Stage" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayStage - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayStageWithName retrieves all AWSApiGatewayStage items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayStageWithName(name string) (AWSApiGatewayStage, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayStage: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::Stage" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayStage - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayStage{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage_methodsetting.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage_methodsetting.go deleted file mode 100644 index 8f850edcb3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-stage_methodsetting.go +++ /dev/null @@ -1,61 +0,0 @@ -package cloudformation - -// AWSApiGatewayStage_MethodSetting AWS CloudFormation Resource (AWS::ApiGateway::Stage.MethodSetting) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html -type AWSApiGatewayStage_MethodSetting struct { - - // CacheDataEncrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachedataencrypted - CacheDataEncrypted bool `json:"CacheDataEncrypted,omitempty"` - - // CacheTtlInSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachettlinseconds - CacheTtlInSeconds int `json:"CacheTtlInSeconds,omitempty"` - - // CachingEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-cachingenabled - CachingEnabled bool `json:"CachingEnabled,omitempty"` - - // DataTraceEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-datatraceenabled - DataTraceEnabled bool `json:"DataTraceEnabled,omitempty"` - - // HttpMethod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-httpmethod - HttpMethod string `json:"HttpMethod,omitempty"` - - // LoggingLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-logginglevel - LoggingLevel string `json:"LoggingLevel,omitempty"` - - // MetricsEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-metricsenabled - MetricsEnabled bool `json:"MetricsEnabled,omitempty"` - - // ResourcePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-resourcepath - ResourcePath string `json:"ResourcePath,omitempty"` - - // ThrottlingBurstLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-throttlingburstlimit - ThrottlingBurstLimit int `json:"ThrottlingBurstLimit,omitempty"` - - // ThrottlingRateLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apitgateway-stage-methodsetting.html#cfn-apigateway-stage-methodsetting-throttlingratelimit - ThrottlingRateLimit float64 `json:"ThrottlingRateLimit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayStage_MethodSetting) AWSCloudFormationType() string { - return "AWS::ApiGateway::Stage.MethodSetting" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan.go deleted file mode 100644 index e70db3463d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayUsagePlan AWS CloudFormation Resource (AWS::ApiGateway::UsagePlan) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html -type AWSApiGatewayUsagePlan struct { - - // ApiStages AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html#cfn-apigateway-usageplan-apistages - ApiStages []AWSApiGatewayUsagePlan_ApiStage `json:"ApiStages,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html#cfn-apigateway-usageplan-description - Description string `json:"Description,omitempty"` - - // Quota AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html#cfn-apigateway-usageplan-quota - Quota *AWSApiGatewayUsagePlan_QuotaSettings `json:"Quota,omitempty"` - - // Throttle AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html#cfn-apigateway-usageplan-throttle - Throttle *AWSApiGatewayUsagePlan_ThrottleSettings `json:"Throttle,omitempty"` - - // UsagePlanName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplan.html#cfn-apigateway-usageplan-usageplanname - UsagePlanName string `json:"UsagePlanName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayUsagePlan) AWSCloudFormationType() string { - return "AWS::ApiGateway::UsagePlan" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayUsagePlan) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayUsagePlan - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayUsagePlan) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayUsagePlan - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayUsagePlan(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayUsagePlanResources retrieves all AWSApiGatewayUsagePlan items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayUsagePlanResources() map[string]AWSApiGatewayUsagePlan { - results := map[string]AWSApiGatewayUsagePlan{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayUsagePlan: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::UsagePlan" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayUsagePlan - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayUsagePlanWithName retrieves all AWSApiGatewayUsagePlan items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayUsagePlanWithName(name string) (AWSApiGatewayUsagePlan, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayUsagePlan: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::UsagePlan" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayUsagePlan - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayUsagePlan{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_apistage.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_apistage.go deleted file mode 100644 index 19a3dc7674..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_apistage.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSApiGatewayUsagePlan_ApiStage AWS CloudFormation Resource (AWS::ApiGateway::UsagePlan.ApiStage) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html -type AWSApiGatewayUsagePlan_ApiStage struct { - - // ApiId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html#cfn-apigateway-usageplan-apistage-apiid - ApiId string `json:"ApiId,omitempty"` - - // Stage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-apistage.html#cfn-apigateway-usageplan-apistage-stage - Stage string `json:"Stage,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayUsagePlan_ApiStage) AWSCloudFormationType() string { - return "AWS::ApiGateway::UsagePlan.ApiStage" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_quotasettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_quotasettings.go deleted file mode 100644 index 4d3af3cf57..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_quotasettings.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSApiGatewayUsagePlan_QuotaSettings AWS CloudFormation Resource (AWS::ApiGateway::UsagePlan.QuotaSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-quotasettings.html -type AWSApiGatewayUsagePlan_QuotaSettings struct { - - // Limit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-quotasettings.html#cfn-apigateway-usageplan-quotasettings-limit - Limit int `json:"Limit,omitempty"` - - // Offset AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-quotasettings.html#cfn-apigateway-usageplan-quotasettings-offset - Offset int `json:"Offset,omitempty"` - - // Period AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-quotasettings.html#cfn-apigateway-usageplan-quotasettings-period - Period string `json:"Period,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayUsagePlan_QuotaSettings) AWSCloudFormationType() string { - return "AWS::ApiGateway::UsagePlan.QuotaSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_throttlesettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_throttlesettings.go deleted file mode 100644 index 7aa059a16a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplan_throttlesettings.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSApiGatewayUsagePlan_ThrottleSettings AWS CloudFormation Resource (AWS::ApiGateway::UsagePlan.ThrottleSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-throttlesettings.html -type AWSApiGatewayUsagePlan_ThrottleSettings struct { - - // BurstLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-throttlesettings.html#cfn-apigateway-usageplan-throttlesettings-burstlimit - BurstLimit int `json:"BurstLimit,omitempty"` - - // RateLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-apigateway-usageplan-throttlesettings.html#cfn-apigateway-usageplan-throttlesettings-ratelimit - RateLimit float64 `json:"RateLimit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayUsagePlan_ThrottleSettings) AWSCloudFormationType() string { - return "AWS::ApiGateway::UsagePlan.ThrottleSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplankey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplankey.go deleted file mode 100644 index b4946f5ed7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-apigateway-usageplankey.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApiGatewayUsagePlanKey AWS CloudFormation Resource (AWS::ApiGateway::UsagePlanKey) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplankey.html -type AWSApiGatewayUsagePlanKey struct { - - // KeyId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplankey.html#cfn-apigateway-usageplankey-keyid - KeyId string `json:"KeyId,omitempty"` - - // KeyType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplankey.html#cfn-apigateway-usageplankey-keytype - KeyType string `json:"KeyType,omitempty"` - - // UsagePlanId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-usageplankey.html#cfn-apigateway-usageplankey-usageplanid - UsagePlanId string `json:"UsagePlanId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApiGatewayUsagePlanKey) AWSCloudFormationType() string { - return "AWS::ApiGateway::UsagePlanKey" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApiGatewayUsagePlanKey) MarshalJSON() ([]byte, error) { - type Properties AWSApiGatewayUsagePlanKey - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApiGatewayUsagePlanKey) UnmarshalJSON(b []byte) error { - type Properties AWSApiGatewayUsagePlanKey - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApiGatewayUsagePlanKey(*res.Properties) - } - - return nil -} - -// GetAllAWSApiGatewayUsagePlanKeyResources retrieves all AWSApiGatewayUsagePlanKey items from an AWS CloudFormation template -func (t *Template) GetAllAWSApiGatewayUsagePlanKeyResources() map[string]AWSApiGatewayUsagePlanKey { - results := map[string]AWSApiGatewayUsagePlanKey{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApiGatewayUsagePlanKey: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::UsagePlanKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayUsagePlanKey - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApiGatewayUsagePlanKeyWithName retrieves all AWSApiGatewayUsagePlanKey items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApiGatewayUsagePlanKeyWithName(name string) (AWSApiGatewayUsagePlanKey, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApiGatewayUsagePlanKey: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApiGateway::UsagePlanKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApiGatewayUsagePlanKey - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApiGatewayUsagePlanKey{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalabletarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalabletarget.go deleted file mode 100644 index bb7d9fe0f0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalabletarget.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApplicationAutoScalingScalableTarget AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalableTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html -type AWSApplicationAutoScalingScalableTarget struct { - - // MaxCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-maxcapacity - MaxCapacity int `json:"MaxCapacity,omitempty"` - - // MinCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-mincapacity - MinCapacity int `json:"MinCapacity,omitempty"` - - // ResourceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-resourceid - ResourceId string `json:"ResourceId,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-rolearn - RoleARN string `json:"RoleARN,omitempty"` - - // ScalableDimension AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-scalabledimension - ScalableDimension string `json:"ScalableDimension,omitempty"` - - // ServiceNamespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalabletarget.html#cfn-applicationautoscaling-scalabletarget-servicenamespace - ServiceNamespace string `json:"ServiceNamespace,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalableTarget) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalableTarget" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApplicationAutoScalingScalableTarget) MarshalJSON() ([]byte, error) { - type Properties AWSApplicationAutoScalingScalableTarget - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApplicationAutoScalingScalableTarget) UnmarshalJSON(b []byte) error { - type Properties AWSApplicationAutoScalingScalableTarget - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApplicationAutoScalingScalableTarget(*res.Properties) - } - - return nil -} - -// GetAllAWSApplicationAutoScalingScalableTargetResources retrieves all AWSApplicationAutoScalingScalableTarget items from an AWS CloudFormation template -func (t *Template) GetAllAWSApplicationAutoScalingScalableTargetResources() map[string]AWSApplicationAutoScalingScalableTarget { - results := map[string]AWSApplicationAutoScalingScalableTarget{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApplicationAutoScalingScalableTarget: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApplicationAutoScaling::ScalableTarget" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApplicationAutoScalingScalableTarget - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApplicationAutoScalingScalableTargetWithName retrieves all AWSApplicationAutoScalingScalableTarget items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApplicationAutoScalingScalableTargetWithName(name string) (AWSApplicationAutoScalingScalableTarget, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApplicationAutoScalingScalableTarget: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApplicationAutoScaling::ScalableTarget" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApplicationAutoScalingScalableTarget - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApplicationAutoScalingScalableTarget{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy.go deleted file mode 100644 index 16040e9741..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy.go +++ /dev/null @@ -1,145 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSApplicationAutoScalingScalingPolicy AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html -type AWSApplicationAutoScalingScalingPolicy struct { - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-policyname - PolicyName string `json:"PolicyName,omitempty"` - - // PolicyType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-policytype - PolicyType string `json:"PolicyType,omitempty"` - - // ResourceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-resourceid - ResourceId string `json:"ResourceId,omitempty"` - - // ScalableDimension AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-scalabledimension - ScalableDimension string `json:"ScalableDimension,omitempty"` - - // ScalingTargetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-scalingtargetid - ScalingTargetId string `json:"ScalingTargetId,omitempty"` - - // ServiceNamespace AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-servicenamespace - ServiceNamespace string `json:"ServiceNamespace,omitempty"` - - // StepScalingPolicyConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration - StepScalingPolicyConfiguration *AWSApplicationAutoScalingScalingPolicy_StepScalingPolicyConfiguration `json:"StepScalingPolicyConfiguration,omitempty"` - - // TargetTrackingScalingPolicyConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-applicationautoscaling-scalingpolicy.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration - TargetTrackingScalingPolicyConfiguration *AWSApplicationAutoScalingScalingPolicy_TargetTrackingScalingPolicyConfiguration `json:"TargetTrackingScalingPolicyConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSApplicationAutoScalingScalingPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSApplicationAutoScalingScalingPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSApplicationAutoScalingScalingPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSApplicationAutoScalingScalingPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSApplicationAutoScalingScalingPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSApplicationAutoScalingScalingPolicyResources retrieves all AWSApplicationAutoScalingScalingPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSApplicationAutoScalingScalingPolicyResources() map[string]AWSApplicationAutoScalingScalingPolicy { - results := map[string]AWSApplicationAutoScalingScalingPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSApplicationAutoScalingScalingPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApplicationAutoScaling::ScalingPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApplicationAutoScalingScalingPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSApplicationAutoScalingScalingPolicyWithName retrieves all AWSApplicationAutoScalingScalingPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSApplicationAutoScalingScalingPolicyWithName(name string) (AWSApplicationAutoScalingScalingPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSApplicationAutoScalingScalingPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ApplicationAutoScaling::ScalingPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSApplicationAutoScalingScalingPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSApplicationAutoScalingScalingPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_customizedmetricspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_customizedmetricspecification.go deleted file mode 100644 index d7b230718a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_customizedmetricspecification.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_CustomizedMetricSpecification AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.CustomizedMetricSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html -type AWSApplicationAutoScalingScalingPolicy_CustomizedMetricSpecification struct { - - // Dimensions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-customizedmetricspecification-dimensions - Dimensions []AWSApplicationAutoScalingScalingPolicy_MetricDimension `json:"Dimensions,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-customizedmetricspecification-metricname - MetricName string `json:"MetricName,omitempty"` - - // Namespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-customizedmetricspecification-namespace - Namespace string `json:"Namespace,omitempty"` - - // Statistic AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-customizedmetricspecification-statistic - Statistic string `json:"Statistic,omitempty"` - - // Unit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-customizedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-customizedmetricspecification-unit - Unit string `json:"Unit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_CustomizedMetricSpecification) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.CustomizedMetricSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_metricdimension.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_metricdimension.go deleted file mode 100644 index 11293772ea..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_metricdimension.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_MetricDimension AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.MetricDimension) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-metricdimension.html -type AWSApplicationAutoScalingScalingPolicy_MetricDimension struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-metricdimension.html#cfn-applicationautoscaling-scalingpolicy-metricdimension-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-metricdimension.html#cfn-applicationautoscaling-scalingpolicy-metricdimension-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_MetricDimension) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.MetricDimension" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_predefinedmetricspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_predefinedmetricspecification.go deleted file mode 100644 index 1623e565a4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_predefinedmetricspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_PredefinedMetricSpecification AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.PredefinedMetricSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-predefinedmetricspecification.html -type AWSApplicationAutoScalingScalingPolicy_PredefinedMetricSpecification struct { - - // PredefinedMetricType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-predefinedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-predefinedmetricspecification-predefinedmetrictype - PredefinedMetricType string `json:"PredefinedMetricType,omitempty"` - - // ResourceLabel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-predefinedmetricspecification.html#cfn-applicationautoscaling-scalingpolicy-predefinedmetricspecification-resourcelabel - ResourceLabel string `json:"ResourceLabel,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_PredefinedMetricSpecification) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.PredefinedMetricSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepadjustment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepadjustment.go deleted file mode 100644 index 449c55e0c0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepadjustment.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_StepAdjustment AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.StepAdjustment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment.html -type AWSApplicationAutoScalingScalingPolicy_StepAdjustment struct { - - // MetricIntervalLowerBound AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment-metricintervallowerbound - MetricIntervalLowerBound float64 `json:"MetricIntervalLowerBound,omitempty"` - - // MetricIntervalUpperBound AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment-metricintervalupperbound - MetricIntervalUpperBound float64 `json:"MetricIntervalUpperBound,omitempty"` - - // ScalingAdjustment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustment-scalingadjustment - ScalingAdjustment int `json:"ScalingAdjustment,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_StepAdjustment) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.StepAdjustment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepscalingpolicyconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepscalingpolicyconfiguration.go deleted file mode 100644 index 486fc58d33..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_stepscalingpolicyconfiguration.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_StepScalingPolicyConfiguration AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.StepScalingPolicyConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html -type AWSApplicationAutoScalingScalingPolicy_StepScalingPolicyConfiguration struct { - - // AdjustmentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-adjustmenttype - AdjustmentType string `json:"AdjustmentType,omitempty"` - - // Cooldown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-cooldown - Cooldown int `json:"Cooldown,omitempty"` - - // MetricAggregationType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-metricaggregationtype - MetricAggregationType string `json:"MetricAggregationType,omitempty"` - - // MinAdjustmentMagnitude AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-minadjustmentmagnitude - MinAdjustmentMagnitude int `json:"MinAdjustmentMagnitude,omitempty"` - - // StepAdjustments AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-stepscalingpolicyconfiguration-stepadjustments - StepAdjustments []AWSApplicationAutoScalingScalingPolicy_StepAdjustment `json:"StepAdjustments,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_StepScalingPolicyConfiguration) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.StepScalingPolicyConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_targettrackingscalingpolicyconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_targettrackingscalingpolicyconfiguration.go deleted file mode 100644 index 3a999b815f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-applicationautoscaling-scalingpolicy_targettrackingscalingpolicyconfiguration.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSApplicationAutoScalingScalingPolicy_TargetTrackingScalingPolicyConfiguration AWS CloudFormation Resource (AWS::ApplicationAutoScaling::ScalingPolicy.TargetTrackingScalingPolicyConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html -type AWSApplicationAutoScalingScalingPolicy_TargetTrackingScalingPolicyConfiguration struct { - - // CustomizedMetricSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration-customizedmetricspecification - CustomizedMetricSpecification *AWSApplicationAutoScalingScalingPolicy_CustomizedMetricSpecification `json:"CustomizedMetricSpecification,omitempty"` - - // PredefinedMetricSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration-predefinedmetricspecification - PredefinedMetricSpecification *AWSApplicationAutoScalingScalingPolicy_PredefinedMetricSpecification `json:"PredefinedMetricSpecification,omitempty"` - - // ScaleInCooldown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration-scaleincooldown - ScaleInCooldown int `json:"ScaleInCooldown,omitempty"` - - // ScaleOutCooldown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration-scaleoutcooldown - ScaleOutCooldown int `json:"ScaleOutCooldown,omitempty"` - - // TargetValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration.html#cfn-applicationautoscaling-scalingpolicy-targettrackingscalingpolicyconfiguration-targetvalue - TargetValue float64 `json:"TargetValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSApplicationAutoScalingScalingPolicy_TargetTrackingScalingPolicyConfiguration) AWSCloudFormationType() string { - return "AWS::ApplicationAutoScaling::ScalingPolicy.TargetTrackingScalingPolicyConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-athena-namedquery.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-athena-namedquery.go deleted file mode 100644 index 23a8289fa7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-athena-namedquery.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAthenaNamedQuery AWS CloudFormation Resource (AWS::Athena::NamedQuery) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-athena-namedquery.html -type AWSAthenaNamedQuery struct { - - // Database AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-athena-namedquery.html#cfn-athena-namedquery-database - Database string `json:"Database,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-athena-namedquery.html#cfn-athena-namedquery-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-athena-namedquery.html#cfn-athena-namedquery-name - Name string `json:"Name,omitempty"` - - // QueryString AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-athena-namedquery.html#cfn-athena-namedquery-querystring - QueryString string `json:"QueryString,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAthenaNamedQuery) AWSCloudFormationType() string { - return "AWS::Athena::NamedQuery" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAthenaNamedQuery) MarshalJSON() ([]byte, error) { - type Properties AWSAthenaNamedQuery - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAthenaNamedQuery) UnmarshalJSON(b []byte) error { - type Properties AWSAthenaNamedQuery - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAthenaNamedQuery(*res.Properties) - } - - return nil -} - -// GetAllAWSAthenaNamedQueryResources retrieves all AWSAthenaNamedQuery items from an AWS CloudFormation template -func (t *Template) GetAllAWSAthenaNamedQueryResources() map[string]AWSAthenaNamedQuery { - results := map[string]AWSAthenaNamedQuery{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAthenaNamedQuery: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Athena::NamedQuery" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAthenaNamedQuery - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAthenaNamedQueryWithName retrieves all AWSAthenaNamedQuery items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAthenaNamedQueryWithName(name string) (AWSAthenaNamedQuery, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAthenaNamedQuery: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Athena::NamedQuery" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAthenaNamedQuery - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAthenaNamedQuery{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup.go deleted file mode 100644 index 4ad2dfc7c0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup.go +++ /dev/null @@ -1,195 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAutoScalingAutoScalingGroup AWS CloudFormation Resource (AWS::AutoScaling::AutoScalingGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html -type AWSAutoScalingAutoScalingGroup struct { - - // AsTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-tags - AsTags []AWSAutoScalingAutoScalingGroup_TagProperty `json:"AsTags,omitempty"` - - // AvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-availabilityzones - AvailabilityZones []string `json:"AvailabilityZones,omitempty"` - - // Cooldown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-cooldown - Cooldown string `json:"Cooldown,omitempty"` - - // DesiredCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-desiredcapacity - DesiredCapacity string `json:"DesiredCapacity,omitempty"` - - // HealthCheckGracePeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-healthcheckgraceperiod - HealthCheckGracePeriod int `json:"HealthCheckGracePeriod,omitempty"` - - // HealthCheckType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-healthchecktype - HealthCheckType string `json:"HealthCheckType,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // LaunchConfigurationName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-launchconfigurationname - LaunchConfigurationName string `json:"LaunchConfigurationName,omitempty"` - - // LifecycleHookSpecificationList AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecificationlist - LifecycleHookSpecificationList []AWSAutoScalingAutoScalingGroup_LifecycleHookSpecification `json:"LifecycleHookSpecificationList,omitempty"` - - // LoadBalancerNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-loadbalancernames - LoadBalancerNames []string `json:"LoadBalancerNames,omitempty"` - - // MaxSize AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-maxsize - MaxSize string `json:"MaxSize,omitempty"` - - // MetricsCollection AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-metricscollection - MetricsCollection []AWSAutoScalingAutoScalingGroup_MetricsCollection `json:"MetricsCollection,omitempty"` - - // MinSize AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-minsize - MinSize string `json:"MinSize,omitempty"` - - // NotificationConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-notificationconfigurations - NotificationConfigurations []AWSAutoScalingAutoScalingGroup_NotificationConfiguration `json:"NotificationConfigurations,omitempty"` - - // PlacementGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-placementgroup - PlacementGroup string `json:"PlacementGroup,omitempty"` - - // TargetGroupARNs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-targetgrouparns - TargetGroupARNs []string `json:"TargetGroupARNs,omitempty"` - - // TerminationPolicies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-termpolicy - TerminationPolicies []string `json:"TerminationPolicies,omitempty"` - - // VPCZoneIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-group.html#cfn-as-group-vpczoneidentifier - VPCZoneIdentifier []string `json:"VPCZoneIdentifier,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingAutoScalingGroup) AWSCloudFormationType() string { - return "AWS::AutoScaling::AutoScalingGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAutoScalingAutoScalingGroup) MarshalJSON() ([]byte, error) { - type Properties AWSAutoScalingAutoScalingGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAutoScalingAutoScalingGroup) UnmarshalJSON(b []byte) error { - type Properties AWSAutoScalingAutoScalingGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAutoScalingAutoScalingGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSAutoScalingAutoScalingGroupResources retrieves all AWSAutoScalingAutoScalingGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSAutoScalingAutoScalingGroupResources() map[string]AWSAutoScalingAutoScalingGroup { - results := map[string]AWSAutoScalingAutoScalingGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAutoScalingAutoScalingGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::AutoScalingGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingAutoScalingGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAutoScalingAutoScalingGroupWithName retrieves all AWSAutoScalingAutoScalingGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAutoScalingAutoScalingGroupWithName(name string) (AWSAutoScalingAutoScalingGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAutoScalingAutoScalingGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::AutoScalingGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingAutoScalingGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAutoScalingAutoScalingGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_lifecyclehookspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_lifecyclehookspecification.go deleted file mode 100644 index 3a1c860d7e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_lifecyclehookspecification.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSAutoScalingAutoScalingGroup_LifecycleHookSpecification AWS CloudFormation Resource (AWS::AutoScaling::AutoScalingGroup.LifecycleHookSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html -type AWSAutoScalingAutoScalingGroup_LifecycleHookSpecification struct { - - // DefaultResult AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-defaultresult - DefaultResult string `json:"DefaultResult,omitempty"` - - // HeartbeatTimeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-heartbeattimeout - HeartbeatTimeout int `json:"HeartbeatTimeout,omitempty"` - - // LifecycleHookName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-lifecyclehookname - LifecycleHookName string `json:"LifecycleHookName,omitempty"` - - // LifecycleTransition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-lifecycletransition - LifecycleTransition string `json:"LifecycleTransition,omitempty"` - - // NotificationMetadata AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-notificationmetadata - NotificationMetadata string `json:"NotificationMetadata,omitempty"` - - // NotificationTargetARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-notificationtargetarn - NotificationTargetARN string `json:"NotificationTargetARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-autoscalinggroup-lifecyclehookspecification.html#cfn-autoscaling-autoscalinggroup-lifecyclehookspecification-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingAutoScalingGroup_LifecycleHookSpecification) AWSCloudFormationType() string { - return "AWS::AutoScaling::AutoScalingGroup.LifecycleHookSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_metricscollection.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_metricscollection.go deleted file mode 100644 index bbd0c266e8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_metricscollection.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSAutoScalingAutoScalingGroup_MetricsCollection AWS CloudFormation Resource (AWS::AutoScaling::AutoScalingGroup.MetricsCollection) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-metricscollection.html -type AWSAutoScalingAutoScalingGroup_MetricsCollection struct { - - // Granularity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-metricscollection.html#cfn-as-metricscollection-granularity - Granularity string `json:"Granularity,omitempty"` - - // Metrics AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-metricscollection.html#cfn-as-metricscollection-metrics - Metrics []string `json:"Metrics,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingAutoScalingGroup_MetricsCollection) AWSCloudFormationType() string { - return "AWS::AutoScaling::AutoScalingGroup.MetricsCollection" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_notificationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_notificationconfiguration.go deleted file mode 100644 index 5c24350973..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_notificationconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSAutoScalingAutoScalingGroup_NotificationConfiguration AWS CloudFormation Resource (AWS::AutoScaling::AutoScalingGroup.NotificationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-notificationconfigurations.html -type AWSAutoScalingAutoScalingGroup_NotificationConfiguration struct { - - // NotificationTypes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-notificationconfigurations.html#cfn-as-group-notificationconfigurations-notificationtypes - NotificationTypes []string `json:"NotificationTypes,omitempty"` - - // TopicARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-notificationconfigurations.html#cfn-autoscaling-autoscalinggroup-notificationconfigurations-topicarn - TopicARN string `json:"TopicARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingAutoScalingGroup_NotificationConfiguration) AWSCloudFormationType() string { - return "AWS::AutoScaling::AutoScalingGroup.NotificationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_tagproperty.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_tagproperty.go deleted file mode 100644 index 29ebeb8c93..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-autoscalinggroup_tagproperty.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSAutoScalingAutoScalingGroup_TagProperty AWS CloudFormation Resource (AWS::AutoScaling::AutoScalingGroup.TagProperty) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html -type AWSAutoScalingAutoScalingGroup_TagProperty struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-Key - Key string `json:"Key,omitempty"` - - // PropagateAtLaunch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-PropagateAtLaunch - PropagateAtLaunch bool `json:"PropagateAtLaunch,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-tags.html#cfn-as-tags-Value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingAutoScalingGroup_TagProperty) AWSCloudFormationType() string { - return "AWS::AutoScaling::AutoScalingGroup.TagProperty" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration.go deleted file mode 100644 index c7b29ace54..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration.go +++ /dev/null @@ -1,190 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAutoScalingLaunchConfiguration AWS CloudFormation Resource (AWS::AutoScaling::LaunchConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html -type AWSAutoScalingLaunchConfiguration struct { - - // AssociatePublicIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cf-as-launchconfig-associatepubip - AssociatePublicIpAddress bool `json:"AssociatePublicIpAddress,omitempty"` - - // BlockDeviceMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-blockdevicemappings - BlockDeviceMappings []AWSAutoScalingLaunchConfiguration_BlockDeviceMapping `json:"BlockDeviceMappings,omitempty"` - - // ClassicLinkVPCId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-classiclinkvpcid - ClassicLinkVPCId string `json:"ClassicLinkVPCId,omitempty"` - - // ClassicLinkVPCSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-classiclinkvpcsecuritygroups - ClassicLinkVPCSecurityGroups []string `json:"ClassicLinkVPCSecurityGroups,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` - - // IamInstanceProfile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-iaminstanceprofile - IamInstanceProfile string `json:"IamInstanceProfile,omitempty"` - - // ImageId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-imageid - ImageId string `json:"ImageId,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // InstanceMonitoring AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-instancemonitoring - InstanceMonitoring bool `json:"InstanceMonitoring,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // KernelId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-kernelid - KernelId string `json:"KernelId,omitempty"` - - // KeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-keyname - KeyName string `json:"KeyName,omitempty"` - - // PlacementTenancy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-placementtenancy - PlacementTenancy string `json:"PlacementTenancy,omitempty"` - - // RamDiskId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-ramdiskid - RamDiskId string `json:"RamDiskId,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-securitygroups - SecurityGroups []string `json:"SecurityGroups,omitempty"` - - // SpotPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-spotprice - SpotPrice string `json:"SpotPrice,omitempty"` - - // UserData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-userdata - UserData string `json:"UserData,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingLaunchConfiguration) AWSCloudFormationType() string { - return "AWS::AutoScaling::LaunchConfiguration" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAutoScalingLaunchConfiguration) MarshalJSON() ([]byte, error) { - type Properties AWSAutoScalingLaunchConfiguration - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAutoScalingLaunchConfiguration) UnmarshalJSON(b []byte) error { - type Properties AWSAutoScalingLaunchConfiguration - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAutoScalingLaunchConfiguration(*res.Properties) - } - - return nil -} - -// GetAllAWSAutoScalingLaunchConfigurationResources retrieves all AWSAutoScalingLaunchConfiguration items from an AWS CloudFormation template -func (t *Template) GetAllAWSAutoScalingLaunchConfigurationResources() map[string]AWSAutoScalingLaunchConfiguration { - results := map[string]AWSAutoScalingLaunchConfiguration{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAutoScalingLaunchConfiguration: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::LaunchConfiguration" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingLaunchConfiguration - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAutoScalingLaunchConfigurationWithName retrieves all AWSAutoScalingLaunchConfiguration items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAutoScalingLaunchConfigurationWithName(name string) (AWSAutoScalingLaunchConfiguration, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAutoScalingLaunchConfiguration: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::LaunchConfiguration" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingLaunchConfiguration - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAutoScalingLaunchConfiguration{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevice.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevice.go deleted file mode 100644 index c2cea84f37..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevice.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSAutoScalingLaunchConfiguration_BlockDevice AWS CloudFormation Resource (AWS::AutoScaling::LaunchConfiguration.BlockDevice) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html -type AWSAutoScalingLaunchConfiguration_BlockDevice struct { - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-deleteonterm - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-iops - Iops int `json:"Iops,omitempty"` - - // SnapshotId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-snapshotid - SnapshotId string `json:"SnapshotId,omitempty"` - - // VolumeSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-volumesize - VolumeSize int `json:"VolumeSize,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html#cfn-as-launchconfig-blockdev-template-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingLaunchConfiguration_BlockDevice) AWSCloudFormationType() string { - return "AWS::AutoScaling::LaunchConfiguration.BlockDevice" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevicemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevicemapping.go deleted file mode 100644 index 9f987307b0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-launchconfiguration_blockdevicemapping.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSAutoScalingLaunchConfiguration_BlockDeviceMapping AWS CloudFormation Resource (AWS::AutoScaling::LaunchConfiguration.BlockDeviceMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html -type AWSAutoScalingLaunchConfiguration_BlockDeviceMapping struct { - - // DeviceName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html#cfn-as-launchconfig-blockdev-mapping-devicename - DeviceName string `json:"DeviceName,omitempty"` - - // Ebs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html#cfn-as-launchconfig-blockdev-mapping-ebs - Ebs *AWSAutoScalingLaunchConfiguration_BlockDevice `json:"Ebs,omitempty"` - - // NoDevice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html#cfn-as-launchconfig-blockdev-mapping-nodevice - NoDevice bool `json:"NoDevice,omitempty"` - - // VirtualName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html#cfn-as-launchconfig-blockdev-mapping-virtualname - VirtualName string `json:"VirtualName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingLaunchConfiguration_BlockDeviceMapping) AWSCloudFormationType() string { - return "AWS::AutoScaling::LaunchConfiguration.BlockDeviceMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-lifecyclehook.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-lifecyclehook.go deleted file mode 100644 index 9cb7bbead2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-lifecyclehook.go +++ /dev/null @@ -1,145 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAutoScalingLifecycleHook AWS CloudFormation Resource (AWS::AutoScaling::LifecycleHook) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html -type AWSAutoScalingLifecycleHook struct { - - // AutoScalingGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-autoscalinggroupname - AutoScalingGroupName string `json:"AutoScalingGroupName,omitempty"` - - // DefaultResult AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-defaultresult - DefaultResult string `json:"DefaultResult,omitempty"` - - // HeartbeatTimeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-heartbeattimeout - HeartbeatTimeout int `json:"HeartbeatTimeout,omitempty"` - - // LifecycleHookName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-autoscaling-lifecyclehook-lifecyclehookname - LifecycleHookName string `json:"LifecycleHookName,omitempty"` - - // LifecycleTransition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-lifecycletransition - LifecycleTransition string `json:"LifecycleTransition,omitempty"` - - // NotificationMetadata AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-notificationmetadata - NotificationMetadata string `json:"NotificationMetadata,omitempty"` - - // NotificationTargetARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-notificationtargetarn - NotificationTargetARN string `json:"NotificationTargetARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingLifecycleHook) AWSCloudFormationType() string { - return "AWS::AutoScaling::LifecycleHook" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAutoScalingLifecycleHook) MarshalJSON() ([]byte, error) { - type Properties AWSAutoScalingLifecycleHook - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAutoScalingLifecycleHook) UnmarshalJSON(b []byte) error { - type Properties AWSAutoScalingLifecycleHook - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAutoScalingLifecycleHook(*res.Properties) - } - - return nil -} - -// GetAllAWSAutoScalingLifecycleHookResources retrieves all AWSAutoScalingLifecycleHook items from an AWS CloudFormation template -func (t *Template) GetAllAWSAutoScalingLifecycleHookResources() map[string]AWSAutoScalingLifecycleHook { - results := map[string]AWSAutoScalingLifecycleHook{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAutoScalingLifecycleHook: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::LifecycleHook" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingLifecycleHook - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAutoScalingLifecycleHookWithName retrieves all AWSAutoScalingLifecycleHook items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAutoScalingLifecycleHookWithName(name string) (AWSAutoScalingLifecycleHook, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAutoScalingLifecycleHook: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::LifecycleHook" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingLifecycleHook - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAutoScalingLifecycleHook{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy.go deleted file mode 100644 index 5c06a29825..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAutoScalingScalingPolicy AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html -type AWSAutoScalingScalingPolicy struct { - - // AdjustmentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-adjustmenttype - AdjustmentType string `json:"AdjustmentType,omitempty"` - - // AutoScalingGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-autoscalinggroupname - AutoScalingGroupName string `json:"AutoScalingGroupName,omitempty"` - - // Cooldown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-cooldown - Cooldown string `json:"Cooldown,omitempty"` - - // EstimatedInstanceWarmup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-estimatedinstancewarmup - EstimatedInstanceWarmup int `json:"EstimatedInstanceWarmup,omitempty"` - - // MetricAggregationType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-metricaggregationtype - MetricAggregationType string `json:"MetricAggregationType,omitempty"` - - // MinAdjustmentMagnitude AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-minadjustmentmagnitude - MinAdjustmentMagnitude int `json:"MinAdjustmentMagnitude,omitempty"` - - // PolicyType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-policytype - PolicyType string `json:"PolicyType,omitempty"` - - // ScalingAdjustment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-scalingadjustment - ScalingAdjustment int `json:"ScalingAdjustment,omitempty"` - - // StepAdjustments AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-as-scalingpolicy-stepadjustments - StepAdjustments []AWSAutoScalingScalingPolicy_StepAdjustment `json:"StepAdjustments,omitempty"` - - // TargetTrackingConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-policy.html#cfn-autoscaling-scalingpolicy-targettrackingconfiguration - TargetTrackingConfiguration *AWSAutoScalingScalingPolicy_TargetTrackingConfiguration `json:"TargetTrackingConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAutoScalingScalingPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSAutoScalingScalingPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAutoScalingScalingPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSAutoScalingScalingPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAutoScalingScalingPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSAutoScalingScalingPolicyResources retrieves all AWSAutoScalingScalingPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSAutoScalingScalingPolicyResources() map[string]AWSAutoScalingScalingPolicy { - results := map[string]AWSAutoScalingScalingPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAutoScalingScalingPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::ScalingPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingScalingPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAutoScalingScalingPolicyWithName retrieves all AWSAutoScalingScalingPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAutoScalingScalingPolicyWithName(name string) (AWSAutoScalingScalingPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAutoScalingScalingPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::ScalingPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingScalingPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAutoScalingScalingPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_customizedmetricspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_customizedmetricspecification.go deleted file mode 100644 index 7bc0e3bafd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_customizedmetricspecification.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSAutoScalingScalingPolicy_CustomizedMetricSpecification AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy.CustomizedMetricSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html -type AWSAutoScalingScalingPolicy_CustomizedMetricSpecification struct { - - // Dimensions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-dimensions - Dimensions []AWSAutoScalingScalingPolicy_MetricDimension `json:"Dimensions,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-metricname - MetricName string `json:"MetricName,omitempty"` - - // Namespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-namespace - Namespace string `json:"Namespace,omitempty"` - - // Statistic AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-statistic - Statistic string `json:"Statistic,omitempty"` - - // Unit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-customizedmetricspecification.html#cfn-autoscaling-scalingpolicy-customizedmetricspecification-unit - Unit string `json:"Unit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy_CustomizedMetricSpecification) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy.CustomizedMetricSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_metricdimension.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_metricdimension.go deleted file mode 100644 index 28d407a786..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_metricdimension.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSAutoScalingScalingPolicy_MetricDimension AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy.MetricDimension) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-metricdimension.html -type AWSAutoScalingScalingPolicy_MetricDimension struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-metricdimension.html#cfn-autoscaling-scalingpolicy-metricdimension-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-metricdimension.html#cfn-autoscaling-scalingpolicy-metricdimension-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy_MetricDimension) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy.MetricDimension" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_predefinedmetricspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_predefinedmetricspecification.go deleted file mode 100644 index 1d9c0fd3fd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_predefinedmetricspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSAutoScalingScalingPolicy_PredefinedMetricSpecification AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy.PredefinedMetricSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-predefinedmetricspecification.html -type AWSAutoScalingScalingPolicy_PredefinedMetricSpecification struct { - - // PredefinedMetricType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-predefinedmetricspecification.html#cfn-autoscaling-scalingpolicy-predefinedmetricspecification-predefinedmetrictype - PredefinedMetricType string `json:"PredefinedMetricType,omitempty"` - - // ResourceLabel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-predefinedmetricspecification.html#cfn-autoscaling-scalingpolicy-predefinedmetricspecification-resourcelabel - ResourceLabel string `json:"ResourceLabel,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy_PredefinedMetricSpecification) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy.PredefinedMetricSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_stepadjustment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_stepadjustment.go deleted file mode 100644 index 4558547993..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_stepadjustment.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSAutoScalingScalingPolicy_StepAdjustment AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy.StepAdjustment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-stepadjustments.html -type AWSAutoScalingScalingPolicy_StepAdjustment struct { - - // MetricIntervalLowerBound AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-stepadjustments.html#cfn-autoscaling-scalingpolicy-stepadjustment-metricintervallowerbound - MetricIntervalLowerBound float64 `json:"MetricIntervalLowerBound,omitempty"` - - // MetricIntervalUpperBound AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-stepadjustments.html#cfn-autoscaling-scalingpolicy-stepadjustment-metricintervalupperbound - MetricIntervalUpperBound float64 `json:"MetricIntervalUpperBound,omitempty"` - - // ScalingAdjustment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-stepadjustments.html#cfn-autoscaling-scalingpolicy-stepadjustment-scalingadjustment - ScalingAdjustment int `json:"ScalingAdjustment,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy_StepAdjustment) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy.StepAdjustment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_targettrackingconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_targettrackingconfiguration.go deleted file mode 100644 index 37431b739d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scalingpolicy_targettrackingconfiguration.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSAutoScalingScalingPolicy_TargetTrackingConfiguration AWS CloudFormation Resource (AWS::AutoScaling::ScalingPolicy.TargetTrackingConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-targettrackingconfiguration.html -type AWSAutoScalingScalingPolicy_TargetTrackingConfiguration struct { - - // CustomizedMetricSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-targettrackingconfiguration.html#cfn-autoscaling-scalingpolicy-targettrackingconfiguration-customizedmetricspecification - CustomizedMetricSpecification *AWSAutoScalingScalingPolicy_CustomizedMetricSpecification `json:"CustomizedMetricSpecification,omitempty"` - - // DisableScaleIn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-targettrackingconfiguration.html#cfn-autoscaling-scalingpolicy-targettrackingconfiguration-disablescalein - DisableScaleIn bool `json:"DisableScaleIn,omitempty"` - - // PredefinedMetricSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-targettrackingconfiguration.html#cfn-autoscaling-scalingpolicy-targettrackingconfiguration-predefinedmetricspecification - PredefinedMetricSpecification *AWSAutoScalingScalingPolicy_PredefinedMetricSpecification `json:"PredefinedMetricSpecification,omitempty"` - - // TargetValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscaling-scalingpolicy-targettrackingconfiguration.html#cfn-autoscaling-scalingpolicy-targettrackingconfiguration-targetvalue - TargetValue float64 `json:"TargetValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScalingPolicy_TargetTrackingConfiguration) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScalingPolicy.TargetTrackingConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scheduledaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scheduledaction.go deleted file mode 100644 index caac146c93..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-autoscaling-scheduledaction.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSAutoScalingScheduledAction AWS CloudFormation Resource (AWS::AutoScaling::ScheduledAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html -type AWSAutoScalingScheduledAction struct { - - // AutoScalingGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-asgname - AutoScalingGroupName string `json:"AutoScalingGroupName,omitempty"` - - // DesiredCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-desiredcapacity - DesiredCapacity int `json:"DesiredCapacity,omitempty"` - - // EndTime AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-endtime - EndTime string `json:"EndTime,omitempty"` - - // MaxSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-maxsize - MaxSize int `json:"MaxSize,omitempty"` - - // MinSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-minsize - MinSize int `json:"MinSize,omitempty"` - - // Recurrence AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-recurrence - Recurrence string `json:"Recurrence,omitempty"` - - // StartTime AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html#cfn-as-scheduledaction-starttime - StartTime string `json:"StartTime,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSAutoScalingScheduledAction) AWSCloudFormationType() string { - return "AWS::AutoScaling::ScheduledAction" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSAutoScalingScheduledAction) MarshalJSON() ([]byte, error) { - type Properties AWSAutoScalingScheduledAction - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSAutoScalingScheduledAction) UnmarshalJSON(b []byte) error { - type Properties AWSAutoScalingScheduledAction - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSAutoScalingScheduledAction(*res.Properties) - } - - return nil -} - -// GetAllAWSAutoScalingScheduledActionResources retrieves all AWSAutoScalingScheduledAction items from an AWS CloudFormation template -func (t *Template) GetAllAWSAutoScalingScheduledActionResources() map[string]AWSAutoScalingScheduledAction { - results := map[string]AWSAutoScalingScheduledAction{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSAutoScalingScheduledAction: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::ScheduledAction" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingScheduledAction - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSAutoScalingScheduledActionWithName retrieves all AWSAutoScalingScheduledAction items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSAutoScalingScheduledActionWithName(name string) (AWSAutoScalingScheduledAction, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSAutoScalingScheduledAction: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::AutoScaling::ScheduledAction" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSAutoScalingScheduledAction - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSAutoScalingScheduledAction{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment.go deleted file mode 100644 index ab722997bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSBatchComputeEnvironment AWS CloudFormation Resource (AWS::Batch::ComputeEnvironment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html -type AWSBatchComputeEnvironment struct { - - // ComputeEnvironmentName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-computeenvironmentname - ComputeEnvironmentName string `json:"ComputeEnvironmentName,omitempty"` - - // ComputeResources AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-computeresources - ComputeResources *AWSBatchComputeEnvironment_ComputeResources `json:"ComputeResources,omitempty"` - - // ServiceRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-servicerole - ServiceRole string `json:"ServiceRole,omitempty"` - - // State AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-state - State string `json:"State,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-computeenvironment.html#cfn-batch-computeenvironment-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchComputeEnvironment) AWSCloudFormationType() string { - return "AWS::Batch::ComputeEnvironment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSBatchComputeEnvironment) MarshalJSON() ([]byte, error) { - type Properties AWSBatchComputeEnvironment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSBatchComputeEnvironment) UnmarshalJSON(b []byte) error { - type Properties AWSBatchComputeEnvironment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSBatchComputeEnvironment(*res.Properties) - } - - return nil -} - -// GetAllAWSBatchComputeEnvironmentResources retrieves all AWSBatchComputeEnvironment items from an AWS CloudFormation template -func (t *Template) GetAllAWSBatchComputeEnvironmentResources() map[string]AWSBatchComputeEnvironment { - results := map[string]AWSBatchComputeEnvironment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSBatchComputeEnvironment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::ComputeEnvironment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchComputeEnvironment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSBatchComputeEnvironmentWithName retrieves all AWSBatchComputeEnvironment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSBatchComputeEnvironmentWithName(name string) (AWSBatchComputeEnvironment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSBatchComputeEnvironment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::ComputeEnvironment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchComputeEnvironment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSBatchComputeEnvironment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment_computeresources.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment_computeresources.go deleted file mode 100644 index a8da06bce9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-computeenvironment_computeresources.go +++ /dev/null @@ -1,76 +0,0 @@ -package cloudformation - -// AWSBatchComputeEnvironment_ComputeResources AWS CloudFormation Resource (AWS::Batch::ComputeEnvironment.ComputeResources) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html -type AWSBatchComputeEnvironment_ComputeResources struct { - - // BidPercentage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-bidpercentage - BidPercentage int `json:"BidPercentage,omitempty"` - - // DesiredvCpus AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-desiredvcpus - DesiredvCpus int `json:"DesiredvCpus,omitempty"` - - // Ec2KeyPair AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-ec2keypair - Ec2KeyPair string `json:"Ec2KeyPair,omitempty"` - - // ImageId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-imageid - ImageId string `json:"ImageId,omitempty"` - - // InstanceRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-instancerole - InstanceRole string `json:"InstanceRole,omitempty"` - - // InstanceTypes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-instancetypes - InstanceTypes []string `json:"InstanceTypes,omitempty"` - - // MaxvCpus AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-maxvcpus - MaxvCpus int `json:"MaxvCpus,omitempty"` - - // MinvCpus AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-minvcpus - MinvCpus int `json:"MinvCpus,omitempty"` - - // SecurityGroupIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SpotIamFleetRole AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-spotiamfleetrole - SpotIamFleetRole string `json:"SpotIamFleetRole,omitempty"` - - // Subnets AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-subnets - Subnets []string `json:"Subnets,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-tags - Tags interface{} `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-computeenvironment-computeresources.html#cfn-batch-computeenvironment-computeresources-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchComputeEnvironment_ComputeResources) AWSCloudFormationType() string { - return "AWS::Batch::ComputeEnvironment.ComputeResources" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition.go deleted file mode 100644 index 615099032a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSBatchJobDefinition AWS CloudFormation Resource (AWS::Batch::JobDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html -type AWSBatchJobDefinition struct { - - // ContainerProperties AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-containerproperties - ContainerProperties *AWSBatchJobDefinition_ContainerProperties `json:"ContainerProperties,omitempty"` - - // JobDefinitionName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-jobdefinitionname - JobDefinitionName string `json:"JobDefinitionName,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // RetryStrategy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-retrystrategy - RetryStrategy *AWSBatchJobDefinition_RetryStrategy `json:"RetryStrategy,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobdefinition.html#cfn-batch-jobdefinition-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSBatchJobDefinition) MarshalJSON() ([]byte, error) { - type Properties AWSBatchJobDefinition - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSBatchJobDefinition) UnmarshalJSON(b []byte) error { - type Properties AWSBatchJobDefinition - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSBatchJobDefinition(*res.Properties) - } - - return nil -} - -// GetAllAWSBatchJobDefinitionResources retrieves all AWSBatchJobDefinition items from an AWS CloudFormation template -func (t *Template) GetAllAWSBatchJobDefinitionResources() map[string]AWSBatchJobDefinition { - results := map[string]AWSBatchJobDefinition{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSBatchJobDefinition: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::JobDefinition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchJobDefinition - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSBatchJobDefinitionWithName retrieves all AWSBatchJobDefinition items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSBatchJobDefinitionWithName(name string) (AWSBatchJobDefinition, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSBatchJobDefinition: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::JobDefinition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchJobDefinition - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSBatchJobDefinition{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_containerproperties.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_containerproperties.go deleted file mode 100644 index 5726595025..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_containerproperties.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_ContainerProperties AWS CloudFormation Resource (AWS::Batch::JobDefinition.ContainerProperties) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html -type AWSBatchJobDefinition_ContainerProperties struct { - - // Command AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-command - Command []string `json:"Command,omitempty"` - - // Environment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-environment - Environment []AWSBatchJobDefinition_Environment `json:"Environment,omitempty"` - - // Image AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-image - Image string `json:"Image,omitempty"` - - // JobRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-jobrolearn - JobRoleArn string `json:"JobRoleArn,omitempty"` - - // Memory AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-memory - Memory int `json:"Memory,omitempty"` - - // MountPoints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-mountpoints - MountPoints []AWSBatchJobDefinition_MountPoints `json:"MountPoints,omitempty"` - - // Privileged AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-privileged - Privileged bool `json:"Privileged,omitempty"` - - // ReadonlyRootFilesystem AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-readonlyrootfilesystem - ReadonlyRootFilesystem bool `json:"ReadonlyRootFilesystem,omitempty"` - - // Ulimits AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-ulimits - Ulimits []AWSBatchJobDefinition_Ulimit `json:"Ulimits,omitempty"` - - // User AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-user - User string `json:"User,omitempty"` - - // Vcpus AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-vcpus - Vcpus int `json:"Vcpus,omitempty"` - - // Volumes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-containerproperties.html#cfn-batch-jobdefinition-containerproperties-volumes - Volumes []AWSBatchJobDefinition_Volumes `json:"Volumes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_ContainerProperties) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.ContainerProperties" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_environment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_environment.go deleted file mode 100644 index 62561546c5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_environment.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_Environment AWS CloudFormation Resource (AWS::Batch::JobDefinition.Environment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html -type AWSBatchJobDefinition_Environment struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html#cfn-batch-jobdefinition-environment-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-environment.html#cfn-batch-jobdefinition-environment-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_Environment) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.Environment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_mountpoints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_mountpoints.go deleted file mode 100644 index 957b6359b8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_mountpoints.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_MountPoints AWS CloudFormation Resource (AWS::Batch::JobDefinition.MountPoints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-mountpoints.html -type AWSBatchJobDefinition_MountPoints struct { - - // ContainerPath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-mountpoints.html#cfn-batch-jobdefinition-mountpoints-containerpath - ContainerPath string `json:"ContainerPath,omitempty"` - - // ReadOnly AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-mountpoints.html#cfn-batch-jobdefinition-mountpoints-readonly - ReadOnly bool `json:"ReadOnly,omitempty"` - - // SourceVolume AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-mountpoints.html#cfn-batch-jobdefinition-mountpoints-sourcevolume - SourceVolume string `json:"SourceVolume,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_MountPoints) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.MountPoints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_retrystrategy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_retrystrategy.go deleted file mode 100644 index 42aa890319..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_retrystrategy.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_RetryStrategy AWS CloudFormation Resource (AWS::Batch::JobDefinition.RetryStrategy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-retrystrategy.html -type AWSBatchJobDefinition_RetryStrategy struct { - - // Attempts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-retrystrategy.html#cfn-batch-jobdefinition-retrystrategy-attempts - Attempts int `json:"Attempts,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_RetryStrategy) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.RetryStrategy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_ulimit.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_ulimit.go deleted file mode 100644 index 9497cdeaf6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_ulimit.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_Ulimit AWS CloudFormation Resource (AWS::Batch::JobDefinition.Ulimit) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-ulimit.html -type AWSBatchJobDefinition_Ulimit struct { - - // HardLimit AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-ulimit.html#cfn-batch-jobdefinition-ulimit-hardlimit - HardLimit int `json:"HardLimit,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-ulimit.html#cfn-batch-jobdefinition-ulimit-name - Name string `json:"Name,omitempty"` - - // SoftLimit AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-ulimit.html#cfn-batch-jobdefinition-ulimit-softlimit - SoftLimit int `json:"SoftLimit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_Ulimit) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.Ulimit" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumes.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumes.go deleted file mode 100644 index 5622031c16..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumes.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_Volumes AWS CloudFormation Resource (AWS::Batch::JobDefinition.Volumes) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-volumes.html -type AWSBatchJobDefinition_Volumes struct { - - // Host AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-volumes.html#cfn-batch-jobdefinition-volumes-host - Host *AWSBatchJobDefinition_VolumesHost `json:"Host,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-volumes.html#cfn-batch-jobdefinition-volumes-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_Volumes) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.Volumes" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumeshost.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumeshost.go deleted file mode 100644 index 43ca56124e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobdefinition_volumeshost.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSBatchJobDefinition_VolumesHost AWS CloudFormation Resource (AWS::Batch::JobDefinition.VolumesHost) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-volumeshost.html -type AWSBatchJobDefinition_VolumesHost struct { - - // SourcePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobdefinition-volumeshost.html#cfn-batch-jobdefinition-volumeshost-sourcepath - SourcePath string `json:"SourcePath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobDefinition_VolumesHost) AWSCloudFormationType() string { - return "AWS::Batch::JobDefinition.VolumesHost" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue.go deleted file mode 100644 index 33ce578f87..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSBatchJobQueue AWS CloudFormation Resource (AWS::Batch::JobQueue) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html -type AWSBatchJobQueue struct { - - // ComputeEnvironmentOrder AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder - ComputeEnvironmentOrder []AWSBatchJobQueue_ComputeEnvironmentOrder `json:"ComputeEnvironmentOrder,omitempty"` - - // JobQueueName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobqueuename - JobQueueName string `json:"JobQueueName,omitempty"` - - // Priority AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-priority - Priority int `json:"Priority,omitempty"` - - // State AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-state - State string `json:"State,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobQueue) AWSCloudFormationType() string { - return "AWS::Batch::JobQueue" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSBatchJobQueue) MarshalJSON() ([]byte, error) { - type Properties AWSBatchJobQueue - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSBatchJobQueue) UnmarshalJSON(b []byte) error { - type Properties AWSBatchJobQueue - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSBatchJobQueue(*res.Properties) - } - - return nil -} - -// GetAllAWSBatchJobQueueResources retrieves all AWSBatchJobQueue items from an AWS CloudFormation template -func (t *Template) GetAllAWSBatchJobQueueResources() map[string]AWSBatchJobQueue { - results := map[string]AWSBatchJobQueue{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSBatchJobQueue: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::JobQueue" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchJobQueue - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSBatchJobQueueWithName retrieves all AWSBatchJobQueue items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSBatchJobQueueWithName(name string) (AWSBatchJobQueue, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSBatchJobQueue: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Batch::JobQueue" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSBatchJobQueue - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSBatchJobQueue{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue_computeenvironmentorder.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue_computeenvironmentorder.go deleted file mode 100644 index cbc889f906..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-batch-jobqueue_computeenvironmentorder.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSBatchJobQueue_ComputeEnvironmentOrder AWS CloudFormation Resource (AWS::Batch::JobQueue.ComputeEnvironmentOrder) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html -type AWSBatchJobQueue_ComputeEnvironmentOrder struct { - - // ComputeEnvironment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-computeenvironment - ComputeEnvironment string `json:"ComputeEnvironment,omitempty"` - - // Order AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-order - Order int `json:"Order,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSBatchJobQueue_ComputeEnvironmentOrder) AWSCloudFormationType() string { - return "AWS::Batch::JobQueue.ComputeEnvironmentOrder" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate.go deleted file mode 100644 index 9e889693a0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCertificateManagerCertificate AWS CloudFormation Resource (AWS::CertificateManager::Certificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html -type AWSCertificateManagerCertificate struct { - - // DomainName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-domainname - DomainName string `json:"DomainName,omitempty"` - - // DomainValidationOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-domainvalidationoptions - DomainValidationOptions []AWSCertificateManagerCertificate_DomainValidationOption `json:"DomainValidationOptions,omitempty"` - - // SubjectAlternativeNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-subjectalternativenames - SubjectAlternativeNames []string `json:"SubjectAlternativeNames,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-certificatemanager-certificate.html#cfn-certificatemanager-certificate-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCertificateManagerCertificate) AWSCloudFormationType() string { - return "AWS::CertificateManager::Certificate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCertificateManagerCertificate) MarshalJSON() ([]byte, error) { - type Properties AWSCertificateManagerCertificate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCertificateManagerCertificate) UnmarshalJSON(b []byte) error { - type Properties AWSCertificateManagerCertificate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCertificateManagerCertificate(*res.Properties) - } - - return nil -} - -// GetAllAWSCertificateManagerCertificateResources retrieves all AWSCertificateManagerCertificate items from an AWS CloudFormation template -func (t *Template) GetAllAWSCertificateManagerCertificateResources() map[string]AWSCertificateManagerCertificate { - results := map[string]AWSCertificateManagerCertificate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCertificateManagerCertificate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CertificateManager::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCertificateManagerCertificate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCertificateManagerCertificateWithName retrieves all AWSCertificateManagerCertificate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCertificateManagerCertificateWithName(name string) (AWSCertificateManagerCertificate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCertificateManagerCertificate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CertificateManager::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCertificateManagerCertificate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCertificateManagerCertificate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate_domainvalidationoption.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate_domainvalidationoption.go deleted file mode 100644 index 0cdf8d6c44..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-certificatemanager-certificate_domainvalidationoption.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCertificateManagerCertificate_DomainValidationOption AWS CloudFormation Resource (AWS::CertificateManager::Certificate.DomainValidationOption) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-certificatemanager-certificate-domainvalidationoption.html -type AWSCertificateManagerCertificate_DomainValidationOption struct { - - // DomainName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-certificatemanager-certificate-domainvalidationoption.html#cfn-certificatemanager-certificate-domainvalidationoptions-domainname - DomainName string `json:"DomainName,omitempty"` - - // ValidationDomain AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-certificatemanager-certificate-domainvalidationoption.html#cfn-certificatemanager-certificate-domainvalidationoption-validationdomain - ValidationDomain string `json:"ValidationDomain,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCertificateManagerCertificate_DomainValidationOption) AWSCloudFormationType() string { - return "AWS::CertificateManager::Certificate.DomainValidationOption" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-customresource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-customresource.go deleted file mode 100644 index deb5f33556..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-customresource.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudFormationCustomResource AWS CloudFormation Resource (AWS::CloudFormation::CustomResource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html -type AWSCloudFormationCustomResource struct { - - // ServiceToken AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html#cfn-customresource-servicetoken - ServiceToken string `json:"ServiceToken,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudFormationCustomResource) AWSCloudFormationType() string { - return "AWS::CloudFormation::CustomResource" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudFormationCustomResource) MarshalJSON() ([]byte, error) { - type Properties AWSCloudFormationCustomResource - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudFormationCustomResource) UnmarshalJSON(b []byte) error { - type Properties AWSCloudFormationCustomResource - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudFormationCustomResource(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudFormationCustomResourceResources retrieves all AWSCloudFormationCustomResource items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudFormationCustomResourceResources() map[string]AWSCloudFormationCustomResource { - results := map[string]AWSCloudFormationCustomResource{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudFormationCustomResource: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::CustomResource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationCustomResource - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudFormationCustomResourceWithName retrieves all AWSCloudFormationCustomResource items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudFormationCustomResourceWithName(name string) (AWSCloudFormationCustomResource, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudFormationCustomResource: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::CustomResource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationCustomResource - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudFormationCustomResource{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-stack.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-stack.go deleted file mode 100644 index 866d68651b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-stack.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudFormationStack AWS CloudFormation Resource (AWS::CloudFormation::Stack) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html -type AWSCloudFormationStack struct { - - // NotificationARNs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-notificationarns - NotificationARNs []string `json:"NotificationARNs,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-parameters - Parameters map[string]string `json:"Parameters,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-tags - Tags []Tag `json:"Tags,omitempty"` - - // TemplateURL AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-templateurl - TemplateURL string `json:"TemplateURL,omitempty"` - - // TimeoutInMinutes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-stack.html#cfn-cloudformation-stack-timeoutinminutes - TimeoutInMinutes int `json:"TimeoutInMinutes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudFormationStack) AWSCloudFormationType() string { - return "AWS::CloudFormation::Stack" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudFormationStack) MarshalJSON() ([]byte, error) { - type Properties AWSCloudFormationStack - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudFormationStack) UnmarshalJSON(b []byte) error { - type Properties AWSCloudFormationStack - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudFormationStack(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudFormationStackResources retrieves all AWSCloudFormationStack items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudFormationStackResources() map[string]AWSCloudFormationStack { - results := map[string]AWSCloudFormationStack{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudFormationStack: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::Stack" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationStack - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudFormationStackWithName retrieves all AWSCloudFormationStack items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudFormationStackWithName(name string) (AWSCloudFormationStack, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudFormationStack: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::Stack" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationStack - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudFormationStack{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitcondition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitcondition.go deleted file mode 100644 index ed3b56dd0b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitcondition.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudFormationWaitCondition AWS CloudFormation Resource (AWS::CloudFormation::WaitCondition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waitcondition.html -type AWSCloudFormationWaitCondition struct { - - // Count AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waitcondition.html#cfn-waitcondition-count - Count int `json:"Count,omitempty"` - - // Handle AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waitcondition.html#cfn-waitcondition-handle - Handle string `json:"Handle,omitempty"` - - // Timeout AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waitcondition.html#cfn-waitcondition-timeout - Timeout string `json:"Timeout,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudFormationWaitCondition) AWSCloudFormationType() string { - return "AWS::CloudFormation::WaitCondition" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudFormationWaitCondition) MarshalJSON() ([]byte, error) { - type Properties AWSCloudFormationWaitCondition - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudFormationWaitCondition) UnmarshalJSON(b []byte) error { - type Properties AWSCloudFormationWaitCondition - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudFormationWaitCondition(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudFormationWaitConditionResources retrieves all AWSCloudFormationWaitCondition items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudFormationWaitConditionResources() map[string]AWSCloudFormationWaitCondition { - results := map[string]AWSCloudFormationWaitCondition{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudFormationWaitCondition: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::WaitCondition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationWaitCondition - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudFormationWaitConditionWithName retrieves all AWSCloudFormationWaitCondition items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudFormationWaitConditionWithName(name string) (AWSCloudFormationWaitCondition, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudFormationWaitCondition: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::WaitCondition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationWaitCondition - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudFormationWaitCondition{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitconditionhandle.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitconditionhandle.go deleted file mode 100644 index 6766dbb918..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudformation-waitconditionhandle.go +++ /dev/null @@ -1,105 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudFormationWaitConditionHandle AWS CloudFormation Resource (AWS::CloudFormation::WaitConditionHandle) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waitconditionhandle.html -type AWSCloudFormationWaitConditionHandle struct { -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudFormationWaitConditionHandle) AWSCloudFormationType() string { - return "AWS::CloudFormation::WaitConditionHandle" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudFormationWaitConditionHandle) MarshalJSON() ([]byte, error) { - type Properties AWSCloudFormationWaitConditionHandle - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudFormationWaitConditionHandle) UnmarshalJSON(b []byte) error { - type Properties AWSCloudFormationWaitConditionHandle - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudFormationWaitConditionHandle(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudFormationWaitConditionHandleResources retrieves all AWSCloudFormationWaitConditionHandle items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudFormationWaitConditionHandleResources() map[string]AWSCloudFormationWaitConditionHandle { - results := map[string]AWSCloudFormationWaitConditionHandle{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudFormationWaitConditionHandle: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::WaitConditionHandle" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationWaitConditionHandle - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudFormationWaitConditionHandleWithName retrieves all AWSCloudFormationWaitConditionHandle items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudFormationWaitConditionHandleWithName(name string) (AWSCloudFormationWaitConditionHandle, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudFormationWaitConditionHandle: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudFormation::WaitConditionHandle" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudFormationWaitConditionHandle - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudFormationWaitConditionHandle{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail.go deleted file mode 100644 index efe1b52d4f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail.go +++ /dev/null @@ -1,170 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudTrailTrail AWS CloudFormation Resource (AWS::CloudTrail::Trail) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html -type AWSCloudTrailTrail struct { - - // CloudWatchLogsLogGroupArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-cloudwatchlogsloggrouparn - CloudWatchLogsLogGroupArn string `json:"CloudWatchLogsLogGroupArn,omitempty"` - - // CloudWatchLogsRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-cloudwatchlogsrolearn - CloudWatchLogsRoleArn string `json:"CloudWatchLogsRoleArn,omitempty"` - - // EnableLogFileValidation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-enablelogfilevalidation - EnableLogFileValidation bool `json:"EnableLogFileValidation,omitempty"` - - // EventSelectors AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-eventselectors - EventSelectors []AWSCloudTrailTrail_EventSelector `json:"EventSelectors,omitempty"` - - // IncludeGlobalServiceEvents AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-includeglobalserviceevents - IncludeGlobalServiceEvents bool `json:"IncludeGlobalServiceEvents,omitempty"` - - // IsLogging AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-islogging - IsLogging bool `json:"IsLogging,omitempty"` - - // IsMultiRegionTrail AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-ismultiregiontrail - IsMultiRegionTrail bool `json:"IsMultiRegionTrail,omitempty"` - - // KMSKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-kmskeyid - KMSKeyId string `json:"KMSKeyId,omitempty"` - - // S3BucketName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-s3bucketname - S3BucketName string `json:"S3BucketName,omitempty"` - - // S3KeyPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-s3keyprefix - S3KeyPrefix string `json:"S3KeyPrefix,omitempty"` - - // SnsTopicName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-snstopicname - SnsTopicName string `json:"SnsTopicName,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-tags - Tags []Tag `json:"Tags,omitempty"` - - // TrailName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudtrail-trail.html#cfn-cloudtrail-trail-trailname - TrailName string `json:"TrailName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudTrailTrail) AWSCloudFormationType() string { - return "AWS::CloudTrail::Trail" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudTrailTrail) MarshalJSON() ([]byte, error) { - type Properties AWSCloudTrailTrail - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudTrailTrail) UnmarshalJSON(b []byte) error { - type Properties AWSCloudTrailTrail - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudTrailTrail(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudTrailTrailResources retrieves all AWSCloudTrailTrail items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudTrailTrailResources() map[string]AWSCloudTrailTrail { - results := map[string]AWSCloudTrailTrail{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudTrailTrail: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudTrail::Trail" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudTrailTrail - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudTrailTrailWithName retrieves all AWSCloudTrailTrail items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudTrailTrailWithName(name string) (AWSCloudTrailTrail, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudTrailTrail: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudTrail::Trail" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudTrailTrail - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudTrailTrail{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_dataresource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_dataresource.go deleted file mode 100644 index bfbe4b369c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_dataresource.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCloudTrailTrail_DataResource AWS CloudFormation Resource (AWS::CloudTrail::Trail.DataResource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html -type AWSCloudTrailTrail_DataResource struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html#cfn-cloudtrail-trail-dataresource-type - Type string `json:"Type,omitempty"` - - // Values AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html#cfn-cloudtrail-trail-dataresource-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudTrailTrail_DataResource) AWSCloudFormationType() string { - return "AWS::CloudTrail::Trail.DataResource" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_eventselector.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_eventselector.go deleted file mode 100644 index cdc110e4a9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudtrail-trail_eventselector.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCloudTrailTrail_EventSelector AWS CloudFormation Resource (AWS::CloudTrail::Trail.EventSelector) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-eventselector.html -type AWSCloudTrailTrail_EventSelector struct { - - // DataResources AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-eventselector.html#cfn-cloudtrail-trail-eventselector-dataresources - DataResources []AWSCloudTrailTrail_DataResource `json:"DataResources,omitempty"` - - // IncludeManagementEvents AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-eventselector.html#cfn-cloudtrail-trail-eventselector-includemanagementevents - IncludeManagementEvents bool `json:"IncludeManagementEvents,omitempty"` - - // ReadWriteType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-eventselector.html#cfn-cloudtrail-trail-eventselector-readwritetype - ReadWriteType string `json:"ReadWriteType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudTrailTrail_EventSelector) AWSCloudFormationType() string { - return "AWS::CloudTrail::Trail.EventSelector" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm.go deleted file mode 100644 index 76d90fef87..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm.go +++ /dev/null @@ -1,195 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudWatchAlarm AWS CloudFormation Resource (AWS::CloudWatch::Alarm) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html -type AWSCloudWatchAlarm struct { - - // ActionsEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-actionsenabled - ActionsEnabled bool `json:"ActionsEnabled,omitempty"` - - // AlarmActions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-alarmactions - AlarmActions []string `json:"AlarmActions,omitempty"` - - // AlarmDescription AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-alarmdescription - AlarmDescription string `json:"AlarmDescription,omitempty"` - - // AlarmName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-alarmname - AlarmName string `json:"AlarmName,omitempty"` - - // ComparisonOperator AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-comparisonoperator - ComparisonOperator string `json:"ComparisonOperator,omitempty"` - - // Dimensions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-dimension - Dimensions []AWSCloudWatchAlarm_Dimension `json:"Dimensions,omitempty"` - - // EvaluateLowSampleCountPercentile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-evaluatelowsamplecountpercentile - EvaluateLowSampleCountPercentile string `json:"EvaluateLowSampleCountPercentile,omitempty"` - - // EvaluationPeriods AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-evaluationperiods - EvaluationPeriods int `json:"EvaluationPeriods,omitempty"` - - // ExtendedStatistic AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-extendedstatistic - ExtendedStatistic string `json:"ExtendedStatistic,omitempty"` - - // InsufficientDataActions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-insufficientdataactions - InsufficientDataActions []string `json:"InsufficientDataActions,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-metricname - MetricName string `json:"MetricName,omitempty"` - - // Namespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-namespace - Namespace string `json:"Namespace,omitempty"` - - // OKActions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-okactions - OKActions []string `json:"OKActions,omitempty"` - - // Period AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-period - Period int `json:"Period,omitempty"` - - // Statistic AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-statistic - Statistic string `json:"Statistic,omitempty"` - - // Threshold AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-threshold - Threshold float64 `json:"Threshold,omitempty"` - - // TreatMissingData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-treatmissingdata - TreatMissingData string `json:"TreatMissingData,omitempty"` - - // Unit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-alarm.html#cfn-cloudwatch-alarms-unit - Unit string `json:"Unit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudWatchAlarm) AWSCloudFormationType() string { - return "AWS::CloudWatch::Alarm" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudWatchAlarm) MarshalJSON() ([]byte, error) { - type Properties AWSCloudWatchAlarm - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudWatchAlarm) UnmarshalJSON(b []byte) error { - type Properties AWSCloudWatchAlarm - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudWatchAlarm(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudWatchAlarmResources retrieves all AWSCloudWatchAlarm items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudWatchAlarmResources() map[string]AWSCloudWatchAlarm { - results := map[string]AWSCloudWatchAlarm{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudWatchAlarm: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudWatch::Alarm" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudWatchAlarm - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudWatchAlarmWithName retrieves all AWSCloudWatchAlarm items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudWatchAlarmWithName(name string) (AWSCloudWatchAlarm, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudWatchAlarm: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudWatch::Alarm" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudWatchAlarm - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudWatchAlarm{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm_dimension.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm_dimension.go deleted file mode 100644 index c0ec2ca484..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-alarm_dimension.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCloudWatchAlarm_Dimension AWS CloudFormation Resource (AWS::CloudWatch::Alarm.Dimension) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-dimension.html -type AWSCloudWatchAlarm_Dimension struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-dimension.html#cfn-cloudwatch-alarm-dimension-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cw-dimension.html#cfn-cloudwatch-alarm-dimension-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudWatchAlarm_Dimension) AWSCloudFormationType() string { - return "AWS::CloudWatch::Alarm.Dimension" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-dashboard.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-dashboard.go deleted file mode 100644 index 7133edeb4f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cloudwatch-dashboard.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCloudWatchDashboard AWS CloudFormation Resource (AWS::CloudWatch::Dashboard) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html -type AWSCloudWatchDashboard struct { - - // DashboardBody AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html#cfn-cloudwatch-dashboard-dashboardbody - DashboardBody string `json:"DashboardBody,omitempty"` - - // DashboardName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html#cfn-cloudwatch-dashboard-dashboardname - DashboardName string `json:"DashboardName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCloudWatchDashboard) AWSCloudFormationType() string { - return "AWS::CloudWatch::Dashboard" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCloudWatchDashboard) MarshalJSON() ([]byte, error) { - type Properties AWSCloudWatchDashboard - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCloudWatchDashboard) UnmarshalJSON(b []byte) error { - type Properties AWSCloudWatchDashboard - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCloudWatchDashboard(*res.Properties) - } - - return nil -} - -// GetAllAWSCloudWatchDashboardResources retrieves all AWSCloudWatchDashboard items from an AWS CloudFormation template -func (t *Template) GetAllAWSCloudWatchDashboardResources() map[string]AWSCloudWatchDashboard { - results := map[string]AWSCloudWatchDashboard{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCloudWatchDashboard: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudWatch::Dashboard" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudWatchDashboard - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCloudWatchDashboardWithName retrieves all AWSCloudWatchDashboard items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCloudWatchDashboardWithName(name string) (AWSCloudWatchDashboard, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCloudWatchDashboard: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CloudWatch::Dashboard" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCloudWatchDashboard - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCloudWatchDashboard{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project.go deleted file mode 100644 index 6426423d67..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodeBuildProject AWS CloudFormation Resource (AWS::CodeBuild::Project) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html -type AWSCodeBuildProject struct { - - // Artifacts AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-artifacts - Artifacts *AWSCodeBuildProject_Artifacts `json:"Artifacts,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-description - Description string `json:"Description,omitempty"` - - // EncryptionKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-encryptionkey - EncryptionKey string `json:"EncryptionKey,omitempty"` - - // Environment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-environment - Environment *AWSCodeBuildProject_Environment `json:"Environment,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-name - Name string `json:"Name,omitempty"` - - // ServiceRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-servicerole - ServiceRole string `json:"ServiceRole,omitempty"` - - // Source AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-source - Source *AWSCodeBuildProject_Source `json:"Source,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-tags - Tags []Tag `json:"Tags,omitempty"` - - // TimeoutInMinutes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html#cfn-codebuild-project-timeoutinminutes - TimeoutInMinutes int `json:"TimeoutInMinutes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodeBuildProject) MarshalJSON() ([]byte, error) { - type Properties AWSCodeBuildProject - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodeBuildProject) UnmarshalJSON(b []byte) error { - type Properties AWSCodeBuildProject - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodeBuildProject(*res.Properties) - } - - return nil -} - -// GetAllAWSCodeBuildProjectResources retrieves all AWSCodeBuildProject items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodeBuildProjectResources() map[string]AWSCodeBuildProject { - results := map[string]AWSCodeBuildProject{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodeBuildProject: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeBuild::Project" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeBuildProject - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodeBuildProjectWithName retrieves all AWSCodeBuildProject items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodeBuildProjectWithName(name string) (AWSCodeBuildProject, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodeBuildProject: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeBuild::Project" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeBuildProject - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodeBuildProject{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_artifacts.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_artifacts.go deleted file mode 100644 index 87469e4f79..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_artifacts.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSCodeBuildProject_Artifacts AWS CloudFormation Resource (AWS::CodeBuild::Project.Artifacts) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html -type AWSCodeBuildProject_Artifacts struct { - - // Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-location - Location string `json:"Location,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-name - Name string `json:"Name,omitempty"` - - // NamespaceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-namespacetype - NamespaceType string `json:"NamespaceType,omitempty"` - - // Packaging AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-packaging - Packaging string `json:"Packaging,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-path - Path string `json:"Path,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html#cfn-codebuild-project-artifacts-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject_Artifacts) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project.Artifacts" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environment.go deleted file mode 100644 index 08786ac31e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environment.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSCodeBuildProject_Environment AWS CloudFormation Resource (AWS::CodeBuild::Project.Environment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html -type AWSCodeBuildProject_Environment struct { - - // ComputeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-computetype - ComputeType string `json:"ComputeType,omitempty"` - - // EnvironmentVariables AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-environmentvariables - EnvironmentVariables []AWSCodeBuildProject_EnvironmentVariable `json:"EnvironmentVariables,omitempty"` - - // Image AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-image - Image string `json:"Image,omitempty"` - - // PrivilegedMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-privilegedmode - PrivilegedMode bool `json:"PrivilegedMode,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environment.html#cfn-codebuild-project-environment-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject_Environment) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project.Environment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environmentvariable.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environmentvariable.go deleted file mode 100644 index 2d30e32bce..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_environmentvariable.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeBuildProject_EnvironmentVariable AWS CloudFormation Resource (AWS::CodeBuild::Project.EnvironmentVariable) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html -type AWSCodeBuildProject_EnvironmentVariable struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-environmentvariable.html#cfn-codebuild-project-environmentvariable-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject_EnvironmentVariable) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project.EnvironmentVariable" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_source.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_source.go deleted file mode 100644 index 3e5fb3c301..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_source.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSCodeBuildProject_Source AWS CloudFormation Resource (AWS::CodeBuild::Project.Source) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html -type AWSCodeBuildProject_Source struct { - - // Auth AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-auth - Auth *AWSCodeBuildProject_SourceAuth `json:"Auth,omitempty"` - - // BuildSpec AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-buildspec - BuildSpec string `json:"BuildSpec,omitempty"` - - // Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-location - Location string `json:"Location,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-source.html#cfn-codebuild-project-source-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject_Source) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project.Source" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_sourceauth.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_sourceauth.go deleted file mode 100644 index 06aa1dd961..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codebuild-project_sourceauth.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodeBuildProject_SourceAuth AWS CloudFormation Resource (AWS::CodeBuild::Project.SourceAuth) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html -type AWSCodeBuildProject_SourceAuth struct { - - // Resource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-resource - Resource string `json:"Resource,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-sourceauth.html#cfn-codebuild-project-sourceauth-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeBuildProject_SourceAuth) AWSCloudFormationType() string { - return "AWS::CodeBuild::Project.SourceAuth" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository.go deleted file mode 100644 index bec9860afc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodeCommitRepository AWS CloudFormation Resource (AWS::CodeCommit::Repository) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codecommit-repository.html -type AWSCodeCommitRepository struct { - - // RepositoryDescription AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codecommit-repository.html#cfn-codecommit-repository-repositorydescription - RepositoryDescription string `json:"RepositoryDescription,omitempty"` - - // RepositoryName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codecommit-repository.html#cfn-codecommit-repository-repositoryname - RepositoryName string `json:"RepositoryName,omitempty"` - - // Triggers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codecommit-repository.html#cfn-codecommit-repository-triggers - Triggers []AWSCodeCommitRepository_RepositoryTrigger `json:"Triggers,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeCommitRepository) AWSCloudFormationType() string { - return "AWS::CodeCommit::Repository" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodeCommitRepository) MarshalJSON() ([]byte, error) { - type Properties AWSCodeCommitRepository - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodeCommitRepository) UnmarshalJSON(b []byte) error { - type Properties AWSCodeCommitRepository - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodeCommitRepository(*res.Properties) - } - - return nil -} - -// GetAllAWSCodeCommitRepositoryResources retrieves all AWSCodeCommitRepository items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodeCommitRepositoryResources() map[string]AWSCodeCommitRepository { - results := map[string]AWSCodeCommitRepository{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodeCommitRepository: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeCommit::Repository" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeCommitRepository - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodeCommitRepositoryWithName retrieves all AWSCodeCommitRepository items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodeCommitRepositoryWithName(name string) (AWSCodeCommitRepository, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodeCommitRepository: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeCommit::Repository" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeCommitRepository - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodeCommitRepository{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository_repositorytrigger.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository_repositorytrigger.go deleted file mode 100644 index 04bcbd8827..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codecommit-repository_repositorytrigger.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSCodeCommitRepository_RepositoryTrigger AWS CloudFormation Resource (AWS::CodeCommit::Repository.RepositoryTrigger) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html -type AWSCodeCommitRepository_RepositoryTrigger struct { - - // Branches AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html#cfn-codecommit-repository-repositorytrigger-branches - Branches []string `json:"Branches,omitempty"` - - // CustomData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html#cfn-codecommit-repository-repositorytrigger-customdata - CustomData string `json:"CustomData,omitempty"` - - // DestinationArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html#cfn-codecommit-repository-repositorytrigger-destinationarn - DestinationArn string `json:"DestinationArn,omitempty"` - - // Events AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html#cfn-codecommit-repository-repositorytrigger-events - Events []string `json:"Events,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codecommit-repository-repositorytrigger.html#cfn-codecommit-repository-repositorytrigger-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeCommitRepository_RepositoryTrigger) AWSCloudFormationType() string { - return "AWS::CodeCommit::Repository.RepositoryTrigger" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-application.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-application.go deleted file mode 100644 index c7980df772..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-application.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodeDeployApplication AWS CloudFormation Resource (AWS::CodeDeploy::Application) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-application.html -type AWSCodeDeployApplication struct { - - // ApplicationName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-application.html#cfn-codedeploy-application-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployApplication) AWSCloudFormationType() string { - return "AWS::CodeDeploy::Application" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodeDeployApplication) MarshalJSON() ([]byte, error) { - type Properties AWSCodeDeployApplication - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodeDeployApplication) UnmarshalJSON(b []byte) error { - type Properties AWSCodeDeployApplication - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodeDeployApplication(*res.Properties) - } - - return nil -} - -// GetAllAWSCodeDeployApplicationResources retrieves all AWSCodeDeployApplication items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodeDeployApplicationResources() map[string]AWSCodeDeployApplication { - results := map[string]AWSCodeDeployApplication{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodeDeployApplication: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployApplication - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodeDeployApplicationWithName retrieves all AWSCodeDeployApplication items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodeDeployApplicationWithName(name string) (AWSCodeDeployApplication, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodeDeployApplication: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployApplication - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodeDeployApplication{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig.go deleted file mode 100644 index 88204a7250..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodeDeployDeploymentConfig AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentconfig.html -type AWSCodeDeployDeploymentConfig struct { - - // DeploymentConfigName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentconfig.html#cfn-codedeploy-deploymentconfig-deploymentconfigname - DeploymentConfigName string `json:"DeploymentConfigName,omitempty"` - - // MinimumHealthyHosts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentconfig.html#cfn-codedeploy-deploymentconfig-minimumhealthyhosts - MinimumHealthyHosts *AWSCodeDeployDeploymentConfig_MinimumHealthyHosts `json:"MinimumHealthyHosts,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentConfig) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentConfig" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodeDeployDeploymentConfig) MarshalJSON() ([]byte, error) { - type Properties AWSCodeDeployDeploymentConfig - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodeDeployDeploymentConfig) UnmarshalJSON(b []byte) error { - type Properties AWSCodeDeployDeploymentConfig - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodeDeployDeploymentConfig(*res.Properties) - } - - return nil -} - -// GetAllAWSCodeDeployDeploymentConfigResources retrieves all AWSCodeDeployDeploymentConfig items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodeDeployDeploymentConfigResources() map[string]AWSCodeDeployDeploymentConfig { - results := map[string]AWSCodeDeployDeploymentConfig{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodeDeployDeploymentConfig: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::DeploymentConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployDeploymentConfig - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodeDeployDeploymentConfigWithName retrieves all AWSCodeDeployDeploymentConfig items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodeDeployDeploymentConfigWithName(name string) (AWSCodeDeployDeploymentConfig, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodeDeployDeploymentConfig: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::DeploymentConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployDeploymentConfig - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodeDeployDeploymentConfig{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig_minimumhealthyhosts.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig_minimumhealthyhosts.go deleted file mode 100644 index 1653689d7a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentconfig_minimumhealthyhosts.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentConfig_MinimumHealthyHosts AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentConfig.MinimumHealthyHosts) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentconfig-minimumhealthyhosts.html -type AWSCodeDeployDeploymentConfig_MinimumHealthyHosts struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentconfig-minimumhealthyhosts.html#cfn-codedeploy-deploymentconfig-minimumhealthyhosts-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentconfig-minimumhealthyhosts.html#cfn-codedeploy-deploymentconfig-minimumhealthyhosts-value - Value int `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentConfig_MinimumHealthyHosts) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentConfig.MinimumHealthyHosts" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup.go deleted file mode 100644 index 3e2dbce9b1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup.go +++ /dev/null @@ -1,170 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodeDeployDeploymentGroup AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html -type AWSCodeDeployDeploymentGroup struct { - - // AlarmConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-alarmconfiguration - AlarmConfiguration *AWSCodeDeployDeploymentGroup_AlarmConfiguration `json:"AlarmConfiguration,omitempty"` - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // AutoRollbackConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-autorollbackconfiguration - AutoRollbackConfiguration *AWSCodeDeployDeploymentGroup_AutoRollbackConfiguration `json:"AutoRollbackConfiguration,omitempty"` - - // AutoScalingGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-autoscalinggroups - AutoScalingGroups []string `json:"AutoScalingGroups,omitempty"` - - // Deployment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-deployment - Deployment *AWSCodeDeployDeploymentGroup_Deployment `json:"Deployment,omitempty"` - - // DeploymentConfigName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-deploymentconfigname - DeploymentConfigName string `json:"DeploymentConfigName,omitempty"` - - // DeploymentGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-deploymentgroupname - DeploymentGroupName string `json:"DeploymentGroupName,omitempty"` - - // DeploymentStyle AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-deploymentstyle - DeploymentStyle *AWSCodeDeployDeploymentGroup_DeploymentStyle `json:"DeploymentStyle,omitempty"` - - // Ec2TagFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-ec2tagfilters - Ec2TagFilters []AWSCodeDeployDeploymentGroup_EC2TagFilter `json:"Ec2TagFilters,omitempty"` - - // LoadBalancerInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-loadbalancerinfo - LoadBalancerInfo *AWSCodeDeployDeploymentGroup_LoadBalancerInfo `json:"LoadBalancerInfo,omitempty"` - - // OnPremisesInstanceTagFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-onpremisesinstancetagfilters - OnPremisesInstanceTagFilters []AWSCodeDeployDeploymentGroup_TagFilter `json:"OnPremisesInstanceTagFilters,omitempty"` - - // ServiceRoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-servicerolearn - ServiceRoleArn string `json:"ServiceRoleArn,omitempty"` - - // TriggerConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codedeploy-deploymentgroup.html#cfn-codedeploy-deploymentgroup-triggerconfigurations - TriggerConfigurations []AWSCodeDeployDeploymentGroup_TriggerConfig `json:"TriggerConfigurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodeDeployDeploymentGroup) MarshalJSON() ([]byte, error) { - type Properties AWSCodeDeployDeploymentGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodeDeployDeploymentGroup) UnmarshalJSON(b []byte) error { - type Properties AWSCodeDeployDeploymentGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodeDeployDeploymentGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSCodeDeployDeploymentGroupResources retrieves all AWSCodeDeployDeploymentGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodeDeployDeploymentGroupResources() map[string]AWSCodeDeployDeploymentGroup { - results := map[string]AWSCodeDeployDeploymentGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodeDeployDeploymentGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::DeploymentGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployDeploymentGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodeDeployDeploymentGroupWithName retrieves all AWSCodeDeployDeploymentGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodeDeployDeploymentGroupWithName(name string) (AWSCodeDeployDeploymentGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodeDeployDeploymentGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodeDeploy::DeploymentGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodeDeployDeploymentGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodeDeployDeploymentGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarm.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarm.go deleted file mode 100644 index 6f8c064215..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarm.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_Alarm AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.Alarm) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarm.html -type AWSCodeDeployDeploymentGroup_Alarm struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarm.html#cfn-codedeploy-deploymentgroup-alarm-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_Alarm) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.Alarm" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarmconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarmconfiguration.go deleted file mode 100644 index 9b6d143249..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_alarmconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_AlarmConfiguration AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.AlarmConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarmconfiguration.html -type AWSCodeDeployDeploymentGroup_AlarmConfiguration struct { - - // Alarms AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarmconfiguration.html#cfn-codedeploy-deploymentgroup-alarmconfiguration-alarms - Alarms []AWSCodeDeployDeploymentGroup_Alarm `json:"Alarms,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarmconfiguration.html#cfn-codedeploy-deploymentgroup-alarmconfiguration-enabled - Enabled bool `json:"Enabled,omitempty"` - - // IgnorePollAlarmFailure AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-alarmconfiguration.html#cfn-codedeploy-deploymentgroup-alarmconfiguration-ignorepollalarmfailure - IgnorePollAlarmFailure bool `json:"IgnorePollAlarmFailure,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_AlarmConfiguration) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.AlarmConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_autorollbackconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_autorollbackconfiguration.go deleted file mode 100644 index c98b5400f8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_autorollbackconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_AutoRollbackConfiguration AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.AutoRollbackConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-autorollbackconfiguration.html -type AWSCodeDeployDeploymentGroup_AutoRollbackConfiguration struct { - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-autorollbackconfiguration.html#cfn-codedeploy-deploymentgroup-autorollbackconfiguration-enabled - Enabled bool `json:"Enabled,omitempty"` - - // Events AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-autorollbackconfiguration.html#cfn-codedeploy-deploymentgroup-autorollbackconfiguration-events - Events []string `json:"Events,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_AutoRollbackConfiguration) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.AutoRollbackConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deployment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deployment.go deleted file mode 100644 index b51f7488d4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deployment.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_Deployment AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.Deployment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment.html -type AWSCodeDeployDeploymentGroup_Deployment struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment.html#cfn-properties-codedeploy-deploymentgroup-deployment-description - Description string `json:"Description,omitempty"` - - // IgnoreApplicationStopFailures AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment.html#cfn-properties-codedeploy-deploymentgroup-deployment-ignoreapplicationstopfailures - IgnoreApplicationStopFailures bool `json:"IgnoreApplicationStopFailures,omitempty"` - - // Revision AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision - Revision *AWSCodeDeployDeploymentGroup_RevisionLocation `json:"Revision,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_Deployment) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.Deployment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deploymentstyle.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deploymentstyle.go deleted file mode 100644 index 112f724bdc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_deploymentstyle.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_DeploymentStyle AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.DeploymentStyle) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deploymentstyle.html -type AWSCodeDeployDeploymentGroup_DeploymentStyle struct { - - // DeploymentOption AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deploymentstyle.html#cfn-codedeploy-deploymentgroup-deploymentstyle-deploymentoption - DeploymentOption string `json:"DeploymentOption,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_DeploymentStyle) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.DeploymentStyle" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_ec2tagfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_ec2tagfilter.go deleted file mode 100644 index 2337a79fb1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_ec2tagfilter.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_EC2TagFilter AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.EC2TagFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-ec2tagfilters.html -type AWSCodeDeployDeploymentGroup_EC2TagFilter struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-ec2tagfilters.html#cfn-properties-codedeploy-deploymentgroup-ec2tagfilters-key - Key string `json:"Key,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-ec2tagfilters.html#cfn-properties-codedeploy-deploymentgroup-ec2tagfilters-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-ec2tagfilters.html#cfn-properties-codedeploy-deploymentgroup-ec2tagfilters-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_EC2TagFilter) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.EC2TagFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_elbinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_elbinfo.go deleted file mode 100644 index 6aa4a5e14e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_elbinfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_ELBInfo AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.ELBInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-elbinfo.html -type AWSCodeDeployDeploymentGroup_ELBInfo struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-elbinfo.html#cfn-codedeploy-deploymentgroup-elbinfo-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_ELBInfo) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.ELBInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_githublocation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_githublocation.go deleted file mode 100644 index 1eceddba7d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_githublocation.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_GitHubLocation AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.GitHubLocation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-githublocation.html -type AWSCodeDeployDeploymentGroup_GitHubLocation struct { - - // CommitId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-githublocation.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-githublocation-commitid - CommitId string `json:"CommitId,omitempty"` - - // Repository AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-githublocation.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-githublocation-repository - Repository string `json:"Repository,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_GitHubLocation) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.GitHubLocation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_loadbalancerinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_loadbalancerinfo.go deleted file mode 100644 index 683a44d7fa..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_loadbalancerinfo.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_LoadBalancerInfo AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.LoadBalancerInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-loadbalancerinfo.html -type AWSCodeDeployDeploymentGroup_LoadBalancerInfo struct { - - // ElbInfoList AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-loadbalancerinfo.html#cfn-codedeploy-deploymentgroup-loadbalancerinfo-elbinfolist - ElbInfoList []AWSCodeDeployDeploymentGroup_ELBInfo `json:"ElbInfoList,omitempty"` - - // TargetGroupInfoList AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-loadbalancerinfo.html#cfn-codedeploy-deploymentgroup-loadbalancerinfo-targetgroupinfolist - TargetGroupInfoList []AWSCodeDeployDeploymentGroup_TargetGroupInfo `json:"TargetGroupInfoList,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_LoadBalancerInfo) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.LoadBalancerInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_revisionlocation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_revisionlocation.go deleted file mode 100644 index a74c7e4d18..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_revisionlocation.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_RevisionLocation AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.RevisionLocation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision.html -type AWSCodeDeployDeploymentGroup_RevisionLocation struct { - - // GitHubLocation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-githublocation - GitHubLocation *AWSCodeDeployDeploymentGroup_GitHubLocation `json:"GitHubLocation,omitempty"` - - // RevisionType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-revisiontype - RevisionType string `json:"RevisionType,omitempty"` - - // S3Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location - S3Location *AWSCodeDeployDeploymentGroup_S3Location `json:"S3Location,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_RevisionLocation) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.RevisionLocation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_s3location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_s3location.go deleted file mode 100644 index 40c7ebbd3b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_s3location.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_S3Location AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.S3Location) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html -type AWSCodeDeployDeploymentGroup_S3Location struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location-bucket - Bucket string `json:"Bucket,omitempty"` - - // BundleType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location-bundletype - BundleType string `json:"BundleType,omitempty"` - - // ETag AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location-etag - ETag string `json:"ETag,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location-key - Key string `json:"Key,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-deployment-revision-s3location.html#cfn-properties-codedeploy-deploymentgroup-deployment-revision-s3location-value - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_S3Location) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.S3Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_tagfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_tagfilter.go deleted file mode 100644 index 91e988c08c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_tagfilter.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_TagFilter AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.TagFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters.html -type AWSCodeDeployDeploymentGroup_TagFilter struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters.html#cfn-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters-key - Key string `json:"Key,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters.html#cfn-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters.html#cfn-properties-codedeploy-deploymentgroup-onpremisesinstancetagfilters-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_TagFilter) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.TagFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_targetgroupinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_targetgroupinfo.go deleted file mode 100644 index 0efb7f3e6b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_targetgroupinfo.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_TargetGroupInfo AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.TargetGroupInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-targetgroupinfo.html -type AWSCodeDeployDeploymentGroup_TargetGroupInfo struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-targetgroupinfo.html#cfn-codedeploy-deploymentgroup-targetgroupinfo-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_TargetGroupInfo) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.TargetGroupInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_triggerconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_triggerconfig.go deleted file mode 100644 index fd5d1e8f12..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codedeploy-deploymentgroup_triggerconfig.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodeDeployDeploymentGroup_TriggerConfig AWS CloudFormation Resource (AWS::CodeDeploy::DeploymentGroup.TriggerConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-triggerconfig.html -type AWSCodeDeployDeploymentGroup_TriggerConfig struct { - - // TriggerEvents AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-triggerconfig.html#cfn-codedeploy-deploymentgroup-triggerconfig-triggerevents - TriggerEvents []string `json:"TriggerEvents,omitempty"` - - // TriggerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-triggerconfig.html#cfn-codedeploy-deploymentgroup-triggerconfig-triggername - TriggerName string `json:"TriggerName,omitempty"` - - // TriggerTargetArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codedeploy-deploymentgroup-triggerconfig.html#cfn-codedeploy-deploymentgroup-triggerconfig-triggertargetarn - TriggerTargetArn string `json:"TriggerTargetArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodeDeployDeploymentGroup_TriggerConfig) AWSCloudFormationType() string { - return "AWS::CodeDeploy::DeploymentGroup.TriggerConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype.go deleted file mode 100644 index 990df7163e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodePipelineCustomActionType AWS CloudFormation Resource (AWS::CodePipeline::CustomActionType) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html -type AWSCodePipelineCustomActionType struct { - - // Category AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-category - Category string `json:"Category,omitempty"` - - // ConfigurationProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-configurationproperties - ConfigurationProperties []AWSCodePipelineCustomActionType_ConfigurationProperties `json:"ConfigurationProperties,omitempty"` - - // InputArtifactDetails AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-inputartifactdetails - InputArtifactDetails *AWSCodePipelineCustomActionType_ArtifactDetails `json:"InputArtifactDetails,omitempty"` - - // OutputArtifactDetails AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-outputartifactdetails - OutputArtifactDetails *AWSCodePipelineCustomActionType_ArtifactDetails `json:"OutputArtifactDetails,omitempty"` - - // Provider AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-provider - Provider string `json:"Provider,omitempty"` - - // Settings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-settings - Settings *AWSCodePipelineCustomActionType_Settings `json:"Settings,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html#cfn-codepipeline-customactiontype-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelineCustomActionType) AWSCloudFormationType() string { - return "AWS::CodePipeline::CustomActionType" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodePipelineCustomActionType) MarshalJSON() ([]byte, error) { - type Properties AWSCodePipelineCustomActionType - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodePipelineCustomActionType) UnmarshalJSON(b []byte) error { - type Properties AWSCodePipelineCustomActionType - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodePipelineCustomActionType(*res.Properties) - } - - return nil -} - -// GetAllAWSCodePipelineCustomActionTypeResources retrieves all AWSCodePipelineCustomActionType items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodePipelineCustomActionTypeResources() map[string]AWSCodePipelineCustomActionType { - results := map[string]AWSCodePipelineCustomActionType{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodePipelineCustomActionType: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodePipeline::CustomActionType" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodePipelineCustomActionType - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodePipelineCustomActionTypeWithName retrieves all AWSCodePipelineCustomActionType items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodePipelineCustomActionTypeWithName(name string) (AWSCodePipelineCustomActionType, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodePipelineCustomActionType: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodePipeline::CustomActionType" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodePipelineCustomActionType - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodePipelineCustomActionType{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_artifactdetails.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_artifactdetails.go deleted file mode 100644 index ccb42aa00b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_artifactdetails.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodePipelineCustomActionType_ArtifactDetails AWS CloudFormation Resource (AWS::CodePipeline::CustomActionType.ArtifactDetails) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html -type AWSCodePipelineCustomActionType_ArtifactDetails struct { - - // MaximumCount AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html#cfn-codepipeline-customactiontype-artifactdetails-maximumcount - MaximumCount int `json:"MaximumCount,omitempty"` - - // MinimumCount AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-artifactdetails.html#cfn-codepipeline-customactiontype-artifactdetails-minimumcount - MinimumCount int `json:"MinimumCount,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelineCustomActionType_ArtifactDetails) AWSCloudFormationType() string { - return "AWS::CodePipeline::CustomActionType.ArtifactDetails" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_configurationproperties.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_configurationproperties.go deleted file mode 100644 index ac4c8eb7e2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_configurationproperties.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSCodePipelineCustomActionType_ConfigurationProperties AWS CloudFormation Resource (AWS::CodePipeline::CustomActionType.ConfigurationProperties) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html -type AWSCodePipelineCustomActionType_ConfigurationProperties struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-description - Description string `json:"Description,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-key - Key bool `json:"Key,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-name - Name string `json:"Name,omitempty"` - - // Queryable AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-queryable - Queryable bool `json:"Queryable,omitempty"` - - // Required AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-required - Required bool `json:"Required,omitempty"` - - // Secret AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-secret - Secret bool `json:"Secret,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-configurationproperties.html#cfn-codepipeline-customactiontype-configurationproperties-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelineCustomActionType_ConfigurationProperties) AWSCloudFormationType() string { - return "AWS::CodePipeline::CustomActionType.ConfigurationProperties" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_settings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_settings.go deleted file mode 100644 index 62eb0a759a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-customactiontype_settings.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSCodePipelineCustomActionType_Settings AWS CloudFormation Resource (AWS::CodePipeline::CustomActionType.Settings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html -type AWSCodePipelineCustomActionType_Settings struct { - - // EntityUrlTemplate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-entityurltemplate - EntityUrlTemplate string `json:"EntityUrlTemplate,omitempty"` - - // ExecutionUrlTemplate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-executionurltemplate - ExecutionUrlTemplate string `json:"ExecutionUrlTemplate,omitempty"` - - // RevisionUrlTemplate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-revisionurltemplate - RevisionUrlTemplate string `json:"RevisionUrlTemplate,omitempty"` - - // ThirdPartyConfigurationUrl AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-customactiontype-settings.html#cfn-codepipeline-customactiontype-settings-thirdpartyconfigurationurl - ThirdPartyConfigurationUrl string `json:"ThirdPartyConfigurationUrl,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelineCustomActionType_Settings) AWSCloudFormationType() string { - return "AWS::CodePipeline::CustomActionType.Settings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline.go deleted file mode 100644 index e5a81baa97..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCodePipelinePipeline AWS CloudFormation Resource (AWS::CodePipeline::Pipeline) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html -type AWSCodePipelinePipeline struct { - - // ArtifactStore AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-artifactstore - ArtifactStore *AWSCodePipelinePipeline_ArtifactStore `json:"ArtifactStore,omitempty"` - - // DisableInboundStageTransitions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-disableinboundstagetransitions - DisableInboundStageTransitions []AWSCodePipelinePipeline_StageTransition `json:"DisableInboundStageTransitions,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-name - Name string `json:"Name,omitempty"` - - // RestartExecutionOnUpdate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-restartexecutiononupdate - RestartExecutionOnUpdate bool `json:"RestartExecutionOnUpdate,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // Stages AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html#cfn-codepipeline-pipeline-stages - Stages []AWSCodePipelinePipeline_StageDeclaration `json:"Stages,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCodePipelinePipeline) MarshalJSON() ([]byte, error) { - type Properties AWSCodePipelinePipeline - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCodePipelinePipeline) UnmarshalJSON(b []byte) error { - type Properties AWSCodePipelinePipeline - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCodePipelinePipeline(*res.Properties) - } - - return nil -} - -// GetAllAWSCodePipelinePipelineResources retrieves all AWSCodePipelinePipeline items from an AWS CloudFormation template -func (t *Template) GetAllAWSCodePipelinePipelineResources() map[string]AWSCodePipelinePipeline { - results := map[string]AWSCodePipelinePipeline{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCodePipelinePipeline: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodePipeline::Pipeline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodePipelinePipeline - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCodePipelinePipelineWithName retrieves all AWSCodePipelinePipeline items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCodePipelinePipelineWithName(name string) (AWSCodePipelinePipeline, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCodePipelinePipeline: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::CodePipeline::Pipeline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCodePipelinePipeline - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCodePipelinePipeline{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiondeclaration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiondeclaration.go deleted file mode 100644 index 12f8a1bc4d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiondeclaration.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_ActionDeclaration AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.ActionDeclaration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html -type AWSCodePipelinePipeline_ActionDeclaration struct { - - // ActionTypeId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid - ActionTypeId *AWSCodePipelinePipeline_ActionTypeId `json:"ActionTypeId,omitempty"` - - // Configuration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-configuration - Configuration interface{} `json:"Configuration,omitempty"` - - // InputArtifacts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts - InputArtifacts []AWSCodePipelinePipeline_InputArtifact `json:"InputArtifacts,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-name - Name string `json:"Name,omitempty"` - - // OutputArtifacts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts - OutputArtifacts []AWSCodePipelinePipeline_OutputArtifact `json:"OutputArtifacts,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // RunOrder AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions.html#cfn-codepipeline-pipeline-stages-actions-runorder - RunOrder int `json:"RunOrder,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_ActionDeclaration) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.ActionDeclaration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiontypeid.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiontypeid.go deleted file mode 100644 index aa35ba2f2a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_actiontypeid.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_ActionTypeId AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.ActionTypeId) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html -type AWSCodePipelinePipeline_ActionTypeId struct { - - // Category AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-category - Category string `json:"Category,omitempty"` - - // Owner AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-owner - Owner string `json:"Owner,omitempty"` - - // Provider AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-provider - Provider string `json:"Provider,omitempty"` - - // Version AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-actiontypeid.html#cfn-codepipeline-pipeline-stages-actions-actiontypeid-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_ActionTypeId) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.ActionTypeId" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_artifactstore.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_artifactstore.go deleted file mode 100644 index 97f4f33a5e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_artifactstore.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_ArtifactStore AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.ArtifactStore) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html -type AWSCodePipelinePipeline_ArtifactStore struct { - - // EncryptionKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey - EncryptionKey *AWSCodePipelinePipeline_EncryptionKey `json:"EncryptionKey,omitempty"` - - // Location AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-location - Location string `json:"Location,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore.html#cfn-codepipeline-pipeline-artifactstore-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_ArtifactStore) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.ArtifactStore" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_blockerdeclaration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_blockerdeclaration.go deleted file mode 100644 index 96c6e1062f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_blockerdeclaration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_BlockerDeclaration AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.BlockerDeclaration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html -type AWSCodePipelinePipeline_BlockerDeclaration struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-blockers.html#cfn-codepipeline-pipeline-stages-blockers-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_BlockerDeclaration) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.BlockerDeclaration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_encryptionkey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_encryptionkey.go deleted file mode 100644 index dd78aa03bc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_encryptionkey.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_EncryptionKey AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.EncryptionKey) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html -type AWSCodePipelinePipeline_EncryptionKey struct { - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-id - Id string `json:"Id,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-artifactstore-encryptionkey.html#cfn-codepipeline-pipeline-artifactstore-encryptionkey-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_EncryptionKey) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.EncryptionKey" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_inputartifact.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_inputartifact.go deleted file mode 100644 index 93613601fb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_inputartifact.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_InputArtifact AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.InputArtifact) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-inputartifacts.html -type AWSCodePipelinePipeline_InputArtifact struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-inputartifacts.html#cfn-codepipeline-pipeline-stages-actions-inputartifacts-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_InputArtifact) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.InputArtifact" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_outputartifact.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_outputartifact.go deleted file mode 100644 index 7655efb3da..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_outputartifact.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_OutputArtifact AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.OutputArtifact) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-outputartifacts.html -type AWSCodePipelinePipeline_OutputArtifact struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages-actions-outputartifacts.html#cfn-codepipeline-pipeline-stages-actions-outputartifacts-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_OutputArtifact) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.OutputArtifact" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagedeclaration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagedeclaration.go deleted file mode 100644 index 771ef17d5b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagedeclaration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_StageDeclaration AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.StageDeclaration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html -type AWSCodePipelinePipeline_StageDeclaration struct { - - // Actions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-actions - Actions []AWSCodePipelinePipeline_ActionDeclaration `json:"Actions,omitempty"` - - // Blockers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-blockers - Blockers []AWSCodePipelinePipeline_BlockerDeclaration `json:"Blockers,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-stages.html#cfn-codepipeline-pipeline-stages-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_StageDeclaration) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.StageDeclaration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagetransition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagetransition.go deleted file mode 100644 index c37925d928..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-codepipeline-pipeline_stagetransition.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCodePipelinePipeline_StageTransition AWS CloudFormation Resource (AWS::CodePipeline::Pipeline.StageTransition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html -type AWSCodePipelinePipeline_StageTransition struct { - - // Reason AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-reason - Reason string `json:"Reason,omitempty"` - - // StageName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codepipeline-pipeline-disableinboundstagetransitions.html#cfn-codepipeline-pipeline-disableinboundstagetransitions-stagename - StageName string `json:"StageName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCodePipelinePipeline_StageTransition) AWSCloudFormationType() string { - return "AWS::CodePipeline::Pipeline.StageTransition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool.go deleted file mode 100644 index 4f9b3031f6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoIdentityPool AWS CloudFormation Resource (AWS::Cognito::IdentityPool) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html -type AWSCognitoIdentityPool struct { - - // AllowUnauthenticatedIdentities AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-allowunauthenticatedidentities - AllowUnauthenticatedIdentities bool `json:"AllowUnauthenticatedIdentities,omitempty"` - - // CognitoEvents AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-cognitoevents - CognitoEvents interface{} `json:"CognitoEvents,omitempty"` - - // CognitoIdentityProviders AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-cognitoidentityproviders - CognitoIdentityProviders []AWSCognitoIdentityPool_CognitoIdentityProvider `json:"CognitoIdentityProviders,omitempty"` - - // CognitoStreams AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-cognitostreams - CognitoStreams *AWSCognitoIdentityPool_CognitoStreams `json:"CognitoStreams,omitempty"` - - // DeveloperProviderName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-developerprovidername - DeveloperProviderName string `json:"DeveloperProviderName,omitempty"` - - // IdentityPoolName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-identitypoolname - IdentityPoolName string `json:"IdentityPoolName,omitempty"` - - // OpenIdConnectProviderARNs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-openidconnectproviderarns - OpenIdConnectProviderARNs []string `json:"OpenIdConnectProviderARNs,omitempty"` - - // PushSync AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-pushsync - PushSync *AWSCognitoIdentityPool_PushSync `json:"PushSync,omitempty"` - - // SamlProviderARNs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-samlproviderarns - SamlProviderARNs []string `json:"SamlProviderARNs,omitempty"` - - // SupportedLoginProviders AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypool.html#cfn-cognito-identitypool-supportedloginproviders - SupportedLoginProviders interface{} `json:"SupportedLoginProviders,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPool) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPool" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoIdentityPool) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoIdentityPool - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoIdentityPool) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoIdentityPool - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoIdentityPool(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoIdentityPoolResources retrieves all AWSCognitoIdentityPool items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoIdentityPoolResources() map[string]AWSCognitoIdentityPool { - results := map[string]AWSCognitoIdentityPool{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoIdentityPool: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::IdentityPool" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoIdentityPool - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoIdentityPoolWithName retrieves all AWSCognitoIdentityPool items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoIdentityPoolWithName(name string) (AWSCognitoIdentityPool, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoIdentityPool: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::IdentityPool" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoIdentityPool - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoIdentityPool{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitoidentityprovider.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitoidentityprovider.go deleted file mode 100644 index f0945732b6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitoidentityprovider.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPool_CognitoIdentityProvider AWS CloudFormation Resource (AWS::Cognito::IdentityPool.CognitoIdentityProvider) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitoidentityprovider.html -type AWSCognitoIdentityPool_CognitoIdentityProvider struct { - - // ClientId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitoidentityprovider.html#cfn-cognito-identitypool-cognitoidentityprovider-clientid - ClientId string `json:"ClientId,omitempty"` - - // ProviderName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitoidentityprovider.html#cfn-cognito-identitypool-cognitoidentityprovider-providername - ProviderName string `json:"ProviderName,omitempty"` - - // ServerSideTokenCheck AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitoidentityprovider.html#cfn-cognito-identitypool-cognitoidentityprovider-serversidetokencheck - ServerSideTokenCheck bool `json:"ServerSideTokenCheck,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPool_CognitoIdentityProvider) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPool.CognitoIdentityProvider" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitostreams.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitostreams.go deleted file mode 100644 index 14d9ee3923..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_cognitostreams.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPool_CognitoStreams AWS CloudFormation Resource (AWS::Cognito::IdentityPool.CognitoStreams) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitostreams.html -type AWSCognitoIdentityPool_CognitoStreams struct { - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitostreams.html#cfn-cognito-identitypool-cognitostreams-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // StreamName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitostreams.html#cfn-cognito-identitypool-cognitostreams-streamname - StreamName string `json:"StreamName,omitempty"` - - // StreamingStatus AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-cognitostreams.html#cfn-cognito-identitypool-cognitostreams-streamingstatus - StreamingStatus string `json:"StreamingStatus,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPool_CognitoStreams) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPool.CognitoStreams" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_pushsync.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_pushsync.go deleted file mode 100644 index da9db28727..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypool_pushsync.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPool_PushSync AWS CloudFormation Resource (AWS::Cognito::IdentityPool.PushSync) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-pushsync.html -type AWSCognitoIdentityPool_PushSync struct { - - // ApplicationArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-pushsync.html#cfn-cognito-identitypool-pushsync-applicationarns - ApplicationArns []string `json:"ApplicationArns,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypool-pushsync.html#cfn-cognito-identitypool-pushsync-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPool_PushSync) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPool.PushSync" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment.go deleted file mode 100644 index 2c94428361..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoIdentityPoolRoleAttachment AWS CloudFormation Resource (AWS::Cognito::IdentityPoolRoleAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypoolroleattachment.html -type AWSCognitoIdentityPoolRoleAttachment struct { - - // IdentityPoolId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypoolroleattachment.html#cfn-cognito-identitypoolroleattachment-identitypoolid - IdentityPoolId string `json:"IdentityPoolId,omitempty"` - - // RoleMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypoolroleattachment.html#cfn-cognito-identitypoolroleattachment-rolemappings - RoleMappings interface{} `json:"RoleMappings,omitempty"` - - // Roles AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-identitypoolroleattachment.html#cfn-cognito-identitypoolroleattachment-roles - Roles interface{} `json:"Roles,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPoolRoleAttachment) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPoolRoleAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoIdentityPoolRoleAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoIdentityPoolRoleAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoIdentityPoolRoleAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoIdentityPoolRoleAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoIdentityPoolRoleAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoIdentityPoolRoleAttachmentResources retrieves all AWSCognitoIdentityPoolRoleAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoIdentityPoolRoleAttachmentResources() map[string]AWSCognitoIdentityPoolRoleAttachment { - results := map[string]AWSCognitoIdentityPoolRoleAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoIdentityPoolRoleAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::IdentityPoolRoleAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoIdentityPoolRoleAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoIdentityPoolRoleAttachmentWithName retrieves all AWSCognitoIdentityPoolRoleAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoIdentityPoolRoleAttachmentWithName(name string) (AWSCognitoIdentityPoolRoleAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoIdentityPoolRoleAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::IdentityPoolRoleAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoIdentityPoolRoleAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoIdentityPoolRoleAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_mappingrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_mappingrule.go deleted file mode 100644 index 173ea186d8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_mappingrule.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPoolRoleAttachment_MappingRule AWS CloudFormation Resource (AWS::Cognito::IdentityPoolRoleAttachment.MappingRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-mappingrule.html -type AWSCognitoIdentityPoolRoleAttachment_MappingRule struct { - - // Claim AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-mappingrule.html#cfn-cognito-identitypoolroleattachment-mappingrule-claim - Claim string `json:"Claim,omitempty"` - - // MatchType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-mappingrule.html#cfn-cognito-identitypoolroleattachment-mappingrule-matchtype - MatchType string `json:"MatchType,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-mappingrule.html#cfn-cognito-identitypoolroleattachment-mappingrule-rolearn - RoleARN string `json:"RoleARN,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-mappingrule.html#cfn-cognito-identitypoolroleattachment-mappingrule-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPoolRoleAttachment_MappingRule) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPoolRoleAttachment.MappingRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rolemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rolemapping.go deleted file mode 100644 index eea3113d58..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rolemapping.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPoolRoleAttachment_RoleMapping AWS CloudFormation Resource (AWS::Cognito::IdentityPoolRoleAttachment.RoleMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html -type AWSCognitoIdentityPoolRoleAttachment_RoleMapping struct { - - // AmbiguousRoleResolution AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-ambiguousroleresolution - AmbiguousRoleResolution string `json:"AmbiguousRoleResolution,omitempty"` - - // RulesConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-rulesconfiguration - RulesConfiguration *AWSCognitoIdentityPoolRoleAttachment_RulesConfigurationType `json:"RulesConfiguration,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rolemapping.html#cfn-cognito-identitypoolroleattachment-rolemapping-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPoolRoleAttachment_RoleMapping) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPoolRoleAttachment.RoleMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rulesconfigurationtype.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rulesconfigurationtype.go deleted file mode 100644 index 9803d12abe..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-identitypoolroleattachment_rulesconfigurationtype.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCognitoIdentityPoolRoleAttachment_RulesConfigurationType AWS CloudFormation Resource (AWS::Cognito::IdentityPoolRoleAttachment.RulesConfigurationType) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rulesconfigurationtype.html -type AWSCognitoIdentityPoolRoleAttachment_RulesConfigurationType struct { - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-identitypoolroleattachment-rulesconfigurationtype.html#cfn-cognito-identitypoolroleattachment-rulesconfigurationtype-rules - Rules []AWSCognitoIdentityPoolRoleAttachment_MappingRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoIdentityPoolRoleAttachment_RulesConfigurationType) AWSCloudFormationType() string { - return "AWS::Cognito::IdentityPoolRoleAttachment.RulesConfigurationType" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool.go deleted file mode 100644 index d94baf59bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoUserPool AWS CloudFormation Resource (AWS::Cognito::UserPool) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html -type AWSCognitoUserPool struct { - - // AdminCreateUserConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-admincreateuserconfig - AdminCreateUserConfig *AWSCognitoUserPool_AdminCreateUserConfig `json:"AdminCreateUserConfig,omitempty"` - - // AliasAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-aliasattributes - AliasAttributes []string `json:"AliasAttributes,omitempty"` - - // AutoVerifiedAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-autoverifiedattributes - AutoVerifiedAttributes []string `json:"AutoVerifiedAttributes,omitempty"` - - // DeviceConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-deviceconfiguration - DeviceConfiguration *AWSCognitoUserPool_DeviceConfiguration `json:"DeviceConfiguration,omitempty"` - - // EmailConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-emailconfiguration - EmailConfiguration *AWSCognitoUserPool_EmailConfiguration `json:"EmailConfiguration,omitempty"` - - // EmailVerificationMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-emailverificationmessage - EmailVerificationMessage string `json:"EmailVerificationMessage,omitempty"` - - // EmailVerificationSubject AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-emailverificationsubject - EmailVerificationSubject string `json:"EmailVerificationSubject,omitempty"` - - // LambdaConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-lambdaconfig - LambdaConfig *AWSCognitoUserPool_LambdaConfig `json:"LambdaConfig,omitempty"` - - // MfaConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-mfaconfiguration - MfaConfiguration string `json:"MfaConfiguration,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-policies - Policies *AWSCognitoUserPool_Policies `json:"Policies,omitempty"` - - // Schema AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-schema - Schema []AWSCognitoUserPool_SchemaAttribute `json:"Schema,omitempty"` - - // SmsAuthenticationMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-smsauthenticationmessage - SmsAuthenticationMessage string `json:"SmsAuthenticationMessage,omitempty"` - - // SmsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-smsconfiguration - SmsConfiguration *AWSCognitoUserPool_SmsConfiguration `json:"SmsConfiguration,omitempty"` - - // SmsVerificationMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-smsverificationmessage - SmsVerificationMessage string `json:"SmsVerificationMessage,omitempty"` - - // UserPoolName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-userpoolname - UserPoolName string `json:"UserPoolName,omitempty"` - - // UserPoolTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpool.html#cfn-cognito-userpool-userpooltags - UserPoolTags interface{} `json:"UserPoolTags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoUserPool) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoUserPool - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoUserPool) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoUserPool - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoUserPool(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoUserPoolResources retrieves all AWSCognitoUserPool items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoUserPoolResources() map[string]AWSCognitoUserPool { - results := map[string]AWSCognitoUserPool{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoUserPool: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPool" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPool - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoUserPoolWithName retrieves all AWSCognitoUserPool items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoUserPoolWithName(name string) (AWSCognitoUserPool, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoUserPool: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPool" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPool - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoUserPool{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_admincreateuserconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_admincreateuserconfig.go deleted file mode 100644 index d918c5738c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_admincreateuserconfig.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_AdminCreateUserConfig AWS CloudFormation Resource (AWS::Cognito::UserPool.AdminCreateUserConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html -type AWSCognitoUserPool_AdminCreateUserConfig struct { - - // AllowAdminCreateUserOnly AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-allowadmincreateuseronly - AllowAdminCreateUserOnly bool `json:"AllowAdminCreateUserOnly,omitempty"` - - // InviteMessageTemplate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-invitemessagetemplate - InviteMessageTemplate *AWSCognitoUserPool_InviteMessageTemplate `json:"InviteMessageTemplate,omitempty"` - - // UnusedAccountValidityDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-admincreateuserconfig.html#cfn-cognito-userpool-admincreateuserconfig-unusedaccountvaliditydays - UnusedAccountValidityDays float64 `json:"UnusedAccountValidityDays,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_AdminCreateUserConfig) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.AdminCreateUserConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_deviceconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_deviceconfiguration.go deleted file mode 100644 index 173e977ff6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_deviceconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_DeviceConfiguration AWS CloudFormation Resource (AWS::Cognito::UserPool.DeviceConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-deviceconfiguration.html -type AWSCognitoUserPool_DeviceConfiguration struct { - - // ChallengeRequiredOnNewDevice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-deviceconfiguration.html#cfn-cognito-userpool-deviceconfiguration-challengerequiredonnewdevice - ChallengeRequiredOnNewDevice bool `json:"ChallengeRequiredOnNewDevice,omitempty"` - - // DeviceOnlyRememberedOnUserPrompt AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-deviceconfiguration.html#cfn-cognito-userpool-deviceconfiguration-deviceonlyrememberedonuserprompt - DeviceOnlyRememberedOnUserPrompt bool `json:"DeviceOnlyRememberedOnUserPrompt,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_DeviceConfiguration) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.DeviceConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_emailconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_emailconfiguration.go deleted file mode 100644 index e767cc4873..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_emailconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_EmailConfiguration AWS CloudFormation Resource (AWS::Cognito::UserPool.EmailConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-emailconfiguration.html -type AWSCognitoUserPool_EmailConfiguration struct { - - // ReplyToEmailAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-emailconfiguration.html#cfn-cognito-userpool-emailconfiguration-replytoemailaddress - ReplyToEmailAddress string `json:"ReplyToEmailAddress,omitempty"` - - // SourceArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-emailconfiguration.html#cfn-cognito-userpool-emailconfiguration-sourcearn - SourceArn string `json:"SourceArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_EmailConfiguration) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.EmailConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_invitemessagetemplate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_invitemessagetemplate.go deleted file mode 100644 index 17e2e5e303..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_invitemessagetemplate.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_InviteMessageTemplate AWS CloudFormation Resource (AWS::Cognito::UserPool.InviteMessageTemplate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html -type AWSCognitoUserPool_InviteMessageTemplate struct { - - // EmailMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html#cfn-cognito-userpool-invitemessagetemplate-emailmessage - EmailMessage string `json:"EmailMessage,omitempty"` - - // EmailSubject AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html#cfn-cognito-userpool-invitemessagetemplate-emailsubject - EmailSubject string `json:"EmailSubject,omitempty"` - - // SMSMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-invitemessagetemplate.html#cfn-cognito-userpool-invitemessagetemplate-smsmessage - SMSMessage string `json:"SMSMessage,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_InviteMessageTemplate) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.InviteMessageTemplate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_lambdaconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_lambdaconfig.go deleted file mode 100644 index b4f1857c6c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_lambdaconfig.go +++ /dev/null @@ -1,51 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_LambdaConfig AWS CloudFormation Resource (AWS::Cognito::UserPool.LambdaConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html -type AWSCognitoUserPool_LambdaConfig struct { - - // CreateAuthChallenge AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-createauthchallenge - CreateAuthChallenge string `json:"CreateAuthChallenge,omitempty"` - - // CustomMessage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-custommessage - CustomMessage string `json:"CustomMessage,omitempty"` - - // DefineAuthChallenge AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-defineauthchallenge - DefineAuthChallenge string `json:"DefineAuthChallenge,omitempty"` - - // PostAuthentication AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-postauthentication - PostAuthentication string `json:"PostAuthentication,omitempty"` - - // PostConfirmation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-postconfirmation - PostConfirmation string `json:"PostConfirmation,omitempty"` - - // PreAuthentication AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-preauthentication - PreAuthentication string `json:"PreAuthentication,omitempty"` - - // PreSignUp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-presignup - PreSignUp string `json:"PreSignUp,omitempty"` - - // VerifyAuthChallengeResponse AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-lambdaconfig.html#cfn-cognito-userpool-lambdaconfig-verifyauthchallengeresponse - VerifyAuthChallengeResponse string `json:"VerifyAuthChallengeResponse,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_LambdaConfig) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.LambdaConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_numberattributeconstraints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_numberattributeconstraints.go deleted file mode 100644 index a6e3603a10..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_numberattributeconstraints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_NumberAttributeConstraints AWS CloudFormation Resource (AWS::Cognito::UserPool.NumberAttributeConstraints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-numberattributeconstraints.html -type AWSCognitoUserPool_NumberAttributeConstraints struct { - - // MaxValue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-numberattributeconstraints.html#cfn-cognito-userpool-numberattributeconstraints-maxvalue - MaxValue string `json:"MaxValue,omitempty"` - - // MinValue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-numberattributeconstraints.html#cfn-cognito-userpool-numberattributeconstraints-minvalue - MinValue string `json:"MinValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_NumberAttributeConstraints) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.NumberAttributeConstraints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_passwordpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_passwordpolicy.go deleted file mode 100644 index c1171a5ce9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_passwordpolicy.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_PasswordPolicy AWS CloudFormation Resource (AWS::Cognito::UserPool.PasswordPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html -type AWSCognitoUserPool_PasswordPolicy struct { - - // MinimumLength AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html#cfn-cognito-userpool-passwordpolicy-minimumlength - MinimumLength int `json:"MinimumLength,omitempty"` - - // RequireLowercase AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html#cfn-cognito-userpool-passwordpolicy-requirelowercase - RequireLowercase bool `json:"RequireLowercase,omitempty"` - - // RequireNumbers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html#cfn-cognito-userpool-passwordpolicy-requirenumbers - RequireNumbers bool `json:"RequireNumbers,omitempty"` - - // RequireSymbols AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html#cfn-cognito-userpool-passwordpolicy-requiresymbols - RequireSymbols bool `json:"RequireSymbols,omitempty"` - - // RequireUppercase AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-passwordpolicy.html#cfn-cognito-userpool-passwordpolicy-requireuppercase - RequireUppercase bool `json:"RequireUppercase,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_PasswordPolicy) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.PasswordPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_policies.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_policies.go deleted file mode 100644 index 56de90c6f3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_policies.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_Policies AWS CloudFormation Resource (AWS::Cognito::UserPool.Policies) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-policies.html -type AWSCognitoUserPool_Policies struct { - - // PasswordPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-policies.html#cfn-cognito-userpool-policies-passwordpolicy - PasswordPolicy *AWSCognitoUserPool_PasswordPolicy `json:"PasswordPolicy,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_Policies) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.Policies" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_schemaattribute.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_schemaattribute.go deleted file mode 100644 index 49523d7f7a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_schemaattribute.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_SchemaAttribute AWS CloudFormation Resource (AWS::Cognito::UserPool.SchemaAttribute) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html -type AWSCognitoUserPool_SchemaAttribute struct { - - // AttributeDataType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-attributedatatype - AttributeDataType string `json:"AttributeDataType,omitempty"` - - // DeveloperOnlyAttribute AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-developeronlyattribute - DeveloperOnlyAttribute bool `json:"DeveloperOnlyAttribute,omitempty"` - - // Mutable AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-mutable - Mutable bool `json:"Mutable,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-name - Name string `json:"Name,omitempty"` - - // NumberAttributeConstraints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-numberattributeconstraints - NumberAttributeConstraints *AWSCognitoUserPool_NumberAttributeConstraints `json:"NumberAttributeConstraints,omitempty"` - - // Required AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-required - Required bool `json:"Required,omitempty"` - - // StringAttributeConstraints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-schemaattribute.html#cfn-cognito-userpool-schemaattribute-stringattributeconstraints - StringAttributeConstraints *AWSCognitoUserPool_StringAttributeConstraints `json:"StringAttributeConstraints,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_SchemaAttribute) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.SchemaAttribute" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_smsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_smsconfiguration.go deleted file mode 100644 index 1166462f4c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_smsconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_SmsConfiguration AWS CloudFormation Resource (AWS::Cognito::UserPool.SmsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-smsconfiguration.html -type AWSCognitoUserPool_SmsConfiguration struct { - - // ExternalId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-smsconfiguration.html#cfn-cognito-userpool-smsconfiguration-externalid - ExternalId string `json:"ExternalId,omitempty"` - - // SnsCallerArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-smsconfiguration.html#cfn-cognito-userpool-smsconfiguration-snscallerarn - SnsCallerArn string `json:"SnsCallerArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_SmsConfiguration) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.SmsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_stringattributeconstraints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_stringattributeconstraints.go deleted file mode 100644 index c5857a75d2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpool_stringattributeconstraints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPool_StringAttributeConstraints AWS CloudFormation Resource (AWS::Cognito::UserPool.StringAttributeConstraints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-stringattributeconstraints.html -type AWSCognitoUserPool_StringAttributeConstraints struct { - - // MaxLength AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-stringattributeconstraints.html#cfn-cognito-userpool-stringattributeconstraints-maxlength - MaxLength string `json:"MaxLength,omitempty"` - - // MinLength AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpool-stringattributeconstraints.html#cfn-cognito-userpool-stringattributeconstraints-minlength - MinLength string `json:"MinLength,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPool_StringAttributeConstraints) AWSCloudFormationType() string { - return "AWS::Cognito::UserPool.StringAttributeConstraints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolclient.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolclient.go deleted file mode 100644 index e20622708e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolclient.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoUserPoolClient AWS CloudFormation Resource (AWS::Cognito::UserPoolClient) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html -type AWSCognitoUserPoolClient struct { - - // ClientName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-clientname - ClientName string `json:"ClientName,omitempty"` - - // ExplicitAuthFlows AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-explicitauthflows - ExplicitAuthFlows []string `json:"ExplicitAuthFlows,omitempty"` - - // GenerateSecret AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-generatesecret - GenerateSecret bool `json:"GenerateSecret,omitempty"` - - // ReadAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-readattributes - ReadAttributes []string `json:"ReadAttributes,omitempty"` - - // RefreshTokenValidity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-refreshtokenvalidity - RefreshTokenValidity float64 `json:"RefreshTokenValidity,omitempty"` - - // UserPoolId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-userpoolid - UserPoolId string `json:"UserPoolId,omitempty"` - - // WriteAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolclient.html#cfn-cognito-userpoolclient-writeattributes - WriteAttributes []string `json:"WriteAttributes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPoolClient) AWSCloudFormationType() string { - return "AWS::Cognito::UserPoolClient" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoUserPoolClient) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoUserPoolClient - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoUserPoolClient) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoUserPoolClient - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoUserPoolClient(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoUserPoolClientResources retrieves all AWSCognitoUserPoolClient items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoUserPoolClientResources() map[string]AWSCognitoUserPoolClient { - results := map[string]AWSCognitoUserPoolClient{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoUserPoolClient: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolClient" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolClient - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoUserPoolClientWithName retrieves all AWSCognitoUserPoolClient items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoUserPoolClientWithName(name string) (AWSCognitoUserPoolClient, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoUserPoolClient: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolClient" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolClient - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoUserPoolClient{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolgroup.go deleted file mode 100644 index b7cc3f4ec4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolgroup.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoUserPoolGroup AWS CloudFormation Resource (AWS::Cognito::UserPoolGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html -type AWSCognitoUserPoolGroup struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#cfn-cognito-userpoolgroup-description - Description string `json:"Description,omitempty"` - - // GroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#cfn-cognito-userpoolgroup-groupname - GroupName string `json:"GroupName,omitempty"` - - // Precedence AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#cfn-cognito-userpoolgroup-precedence - Precedence float64 `json:"Precedence,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#cfn-cognito-userpoolgroup-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // UserPoolId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolgroup.html#cfn-cognito-userpoolgroup-userpoolid - UserPoolId string `json:"UserPoolId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPoolGroup) AWSCloudFormationType() string { - return "AWS::Cognito::UserPoolGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoUserPoolGroup) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoUserPoolGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoUserPoolGroup) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoUserPoolGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoUserPoolGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoUserPoolGroupResources retrieves all AWSCognitoUserPoolGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoUserPoolGroupResources() map[string]AWSCognitoUserPoolGroup { - results := map[string]AWSCognitoUserPoolGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoUserPoolGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoUserPoolGroupWithName retrieves all AWSCognitoUserPoolGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoUserPoolGroupWithName(name string) (AWSCognitoUserPoolGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoUserPoolGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoUserPoolGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser.go deleted file mode 100644 index 462fc49a19..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoUserPoolUser AWS CloudFormation Resource (AWS::Cognito::UserPoolUser) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html -type AWSCognitoUserPoolUser struct { - - // DesiredDeliveryMediums AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-desireddeliverymediums - DesiredDeliveryMediums []string `json:"DesiredDeliveryMediums,omitempty"` - - // ForceAliasCreation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-forcealiascreation - ForceAliasCreation bool `json:"ForceAliasCreation,omitempty"` - - // MessageAction AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-messageaction - MessageAction string `json:"MessageAction,omitempty"` - - // UserAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-userattributes - UserAttributes []AWSCognitoUserPoolUser_AttributeType `json:"UserAttributes,omitempty"` - - // UserPoolId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-userpoolid - UserPoolId string `json:"UserPoolId,omitempty"` - - // Username AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-username - Username string `json:"Username,omitempty"` - - // ValidationData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpooluser.html#cfn-cognito-userpooluser-validationdata - ValidationData []AWSCognitoUserPoolUser_AttributeType `json:"ValidationData,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPoolUser) AWSCloudFormationType() string { - return "AWS::Cognito::UserPoolUser" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoUserPoolUser) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoUserPoolUser - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoUserPoolUser) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoUserPoolUser - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoUserPoolUser(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoUserPoolUserResources retrieves all AWSCognitoUserPoolUser items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoUserPoolUserResources() map[string]AWSCognitoUserPoolUser { - results := map[string]AWSCognitoUserPoolUser{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoUserPoolUser: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolUser" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolUser - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoUserPoolUserWithName retrieves all AWSCognitoUserPoolUser items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoUserPoolUserWithName(name string) (AWSCognitoUserPoolUser, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoUserPoolUser: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolUser" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolUser - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoUserPoolUser{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser_attributetype.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser_attributetype.go deleted file mode 100644 index 7318245cf1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpooluser_attributetype.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSCognitoUserPoolUser_AttributeType AWS CloudFormation Resource (AWS::Cognito::UserPoolUser.AttributeType) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpooluser-attributetype.html -type AWSCognitoUserPoolUser_AttributeType struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpooluser-attributetype.html#cfn-cognito-userpooluser-attributetype-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cognito-userpooluser-attributetype.html#cfn-cognito-userpooluser-attributetype-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPoolUser_AttributeType) AWSCloudFormationType() string { - return "AWS::Cognito::UserPoolUser.AttributeType" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolusertogroupattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolusertogroupattachment.go deleted file mode 100644 index 9009485746..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-cognito-userpoolusertogroupattachment.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSCognitoUserPoolUserToGroupAttachment AWS CloudFormation Resource (AWS::Cognito::UserPoolUserToGroupAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolusertogroupattachment.html -type AWSCognitoUserPoolUserToGroupAttachment struct { - - // GroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolusertogroupattachment.html#cfn-cognito-userpoolusertogroupattachment-groupname - GroupName string `json:"GroupName,omitempty"` - - // UserPoolId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolusertogroupattachment.html#cfn-cognito-userpoolusertogroupattachment-userpoolid - UserPoolId string `json:"UserPoolId,omitempty"` - - // Username AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cognito-userpoolusertogroupattachment.html#cfn-cognito-userpoolusertogroupattachment-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSCognitoUserPoolUserToGroupAttachment) AWSCloudFormationType() string { - return "AWS::Cognito::UserPoolUserToGroupAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSCognitoUserPoolUserToGroupAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSCognitoUserPoolUserToGroupAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSCognitoUserPoolUserToGroupAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSCognitoUserPoolUserToGroupAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSCognitoUserPoolUserToGroupAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSCognitoUserPoolUserToGroupAttachmentResources retrieves all AWSCognitoUserPoolUserToGroupAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSCognitoUserPoolUserToGroupAttachmentResources() map[string]AWSCognitoUserPoolUserToGroupAttachment { - results := map[string]AWSCognitoUserPoolUserToGroupAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSCognitoUserPoolUserToGroupAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolUserToGroupAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolUserToGroupAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSCognitoUserPoolUserToGroupAttachmentWithName retrieves all AWSCognitoUserPoolUserToGroupAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSCognitoUserPoolUserToGroupAttachmentWithName(name string) (AWSCognitoUserPoolUserToGroupAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSCognitoUserPoolUserToGroupAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Cognito::UserPoolUserToGroupAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSCognitoUserPoolUserToGroupAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSCognitoUserPoolUserToGroupAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule.go deleted file mode 100644 index bf1208b84d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSConfigConfigRule AWS CloudFormation Resource (AWS::Config::ConfigRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html -type AWSConfigConfigRule struct { - - // ConfigRuleName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-configrulename - ConfigRuleName string `json:"ConfigRuleName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-description - Description string `json:"Description,omitempty"` - - // InputParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-inputparameters - InputParameters interface{} `json:"InputParameters,omitempty"` - - // MaximumExecutionFrequency AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-maximumexecutionfrequency - MaximumExecutionFrequency string `json:"MaximumExecutionFrequency,omitempty"` - - // Scope AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-scope - Scope *AWSConfigConfigRule_Scope `json:"Scope,omitempty"` - - // Source AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configrule.html#cfn-config-configrule-source - Source *AWSConfigConfigRule_Source `json:"Source,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigRule) AWSCloudFormationType() string { - return "AWS::Config::ConfigRule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSConfigConfigRule) MarshalJSON() ([]byte, error) { - type Properties AWSConfigConfigRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSConfigConfigRule) UnmarshalJSON(b []byte) error { - type Properties AWSConfigConfigRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSConfigConfigRule(*res.Properties) - } - - return nil -} - -// GetAllAWSConfigConfigRuleResources retrieves all AWSConfigConfigRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSConfigConfigRuleResources() map[string]AWSConfigConfigRule { - results := map[string]AWSConfigConfigRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSConfigConfigRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::ConfigRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigConfigRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSConfigConfigRuleWithName retrieves all AWSConfigConfigRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSConfigConfigRuleWithName(name string) (AWSConfigConfigRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSConfigConfigRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::ConfigRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigConfigRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSConfigConfigRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_scope.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_scope.go deleted file mode 100644 index 733c6a69e9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_scope.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSConfigConfigRule_Scope AWS CloudFormation Resource (AWS::Config::ConfigRule.Scope) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html -type AWSConfigConfigRule_Scope struct { - - // ComplianceResourceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html#cfn-config-configrule-scope-complianceresourceid - ComplianceResourceId string `json:"ComplianceResourceId,omitempty"` - - // ComplianceResourceTypes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html#cfn-config-configrule-scope-complianceresourcetypes - ComplianceResourceTypes []string `json:"ComplianceResourceTypes,omitempty"` - - // TagKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html#cfn-config-configrule-scope-tagkey - TagKey string `json:"TagKey,omitempty"` - - // TagValue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-scope.html#cfn-config-configrule-scope-tagvalue - TagValue string `json:"TagValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigRule_Scope) AWSCloudFormationType() string { - return "AWS::Config::ConfigRule.Scope" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_source.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_source.go deleted file mode 100644 index 2d4d48938e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_source.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSConfigConfigRule_Source AWS CloudFormation Resource (AWS::Config::ConfigRule.Source) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source.html -type AWSConfigConfigRule_Source struct { - - // Owner AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source.html#cfn-config-configrule-source-owner - Owner string `json:"Owner,omitempty"` - - // SourceDetails AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source.html#cfn-config-configrule-source-sourcedetails - SourceDetails []AWSConfigConfigRule_SourceDetail `json:"SourceDetails,omitempty"` - - // SourceIdentifier AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source.html#cfn-config-configrule-source-sourceidentifier - SourceIdentifier string `json:"SourceIdentifier,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigRule_Source) AWSCloudFormationType() string { - return "AWS::Config::ConfigRule.Source" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_sourcedetail.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_sourcedetail.go deleted file mode 100644 index 84cb646434..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configrule_sourcedetail.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSConfigConfigRule_SourceDetail AWS CloudFormation Resource (AWS::Config::ConfigRule.SourceDetail) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source-sourcedetails.html -type AWSConfigConfigRule_SourceDetail struct { - - // EventSource AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source-sourcedetails.html#cfn-config-configrule-source-sourcedetail-eventsource - EventSource string `json:"EventSource,omitempty"` - - // MaximumExecutionFrequency AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source-sourcedetails.html#cfn-config-configrule-sourcedetail-maximumexecutionfrequency - MaximumExecutionFrequency string `json:"MaximumExecutionFrequency,omitempty"` - - // MessageType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configrule-source-sourcedetails.html#cfn-config-configrule-source-sourcedetail-messagetype - MessageType string `json:"MessageType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigRule_SourceDetail) AWSCloudFormationType() string { - return "AWS::Config::ConfigRule.SourceDetail" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder.go deleted file mode 100644 index 5c49de8ce0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSConfigConfigurationRecorder AWS CloudFormation Resource (AWS::Config::ConfigurationRecorder) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configurationrecorder.html -type AWSConfigConfigurationRecorder struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configurationrecorder.html#cfn-config-configurationrecorder-name - Name string `json:"Name,omitempty"` - - // RecordingGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configurationrecorder.html#cfn-config-configurationrecorder-recordinggroup - RecordingGroup *AWSConfigConfigurationRecorder_RecordingGroup `json:"RecordingGroup,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-configurationrecorder.html#cfn-config-configurationrecorder-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigurationRecorder) AWSCloudFormationType() string { - return "AWS::Config::ConfigurationRecorder" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSConfigConfigurationRecorder) MarshalJSON() ([]byte, error) { - type Properties AWSConfigConfigurationRecorder - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSConfigConfigurationRecorder) UnmarshalJSON(b []byte) error { - type Properties AWSConfigConfigurationRecorder - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSConfigConfigurationRecorder(*res.Properties) - } - - return nil -} - -// GetAllAWSConfigConfigurationRecorderResources retrieves all AWSConfigConfigurationRecorder items from an AWS CloudFormation template -func (t *Template) GetAllAWSConfigConfigurationRecorderResources() map[string]AWSConfigConfigurationRecorder { - results := map[string]AWSConfigConfigurationRecorder{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSConfigConfigurationRecorder: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::ConfigurationRecorder" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigConfigurationRecorder - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSConfigConfigurationRecorderWithName retrieves all AWSConfigConfigurationRecorder items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSConfigConfigurationRecorderWithName(name string) (AWSConfigConfigurationRecorder, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSConfigConfigurationRecorder: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::ConfigurationRecorder" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigConfigurationRecorder - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSConfigConfigurationRecorder{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder_recordinggroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder_recordinggroup.go deleted file mode 100644 index f23d025b12..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-configurationrecorder_recordinggroup.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSConfigConfigurationRecorder_RecordingGroup AWS CloudFormation Resource (AWS::Config::ConfigurationRecorder.RecordingGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationrecorder-recordinggroup.html -type AWSConfigConfigurationRecorder_RecordingGroup struct { - - // AllSupported AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationrecorder-recordinggroup.html#cfn-config-configurationrecorder-recordinggroup-allsupported - AllSupported bool `json:"AllSupported,omitempty"` - - // IncludeGlobalResourceTypes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationrecorder-recordinggroup.html#cfn-config-configurationrecorder-recordinggroup-includeglobalresourcetypes - IncludeGlobalResourceTypes bool `json:"IncludeGlobalResourceTypes,omitempty"` - - // ResourceTypes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-configurationrecorder-recordinggroup.html#cfn-config-configurationrecorder-recordinggroup-resourcetypes - ResourceTypes []string `json:"ResourceTypes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigConfigurationRecorder_RecordingGroup) AWSCloudFormationType() string { - return "AWS::Config::ConfigurationRecorder.RecordingGroup" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel.go deleted file mode 100644 index 06663baf1a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSConfigDeliveryChannel AWS CloudFormation Resource (AWS::Config::DeliveryChannel) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html -type AWSConfigDeliveryChannel struct { - - // ConfigSnapshotDeliveryProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html#cfn-config-deliverychannel-configsnapshotdeliveryproperties - ConfigSnapshotDeliveryProperties *AWSConfigDeliveryChannel_ConfigSnapshotDeliveryProperties `json:"ConfigSnapshotDeliveryProperties,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html#cfn-config-deliverychannel-name - Name string `json:"Name,omitempty"` - - // S3BucketName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html#cfn-config-deliverychannel-s3bucketname - S3BucketName string `json:"S3BucketName,omitempty"` - - // S3KeyPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html#cfn-config-deliverychannel-s3keyprefix - S3KeyPrefix string `json:"S3KeyPrefix,omitempty"` - - // SnsTopicARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-config-deliverychannel.html#cfn-config-deliverychannel-snstopicarn - SnsTopicARN string `json:"SnsTopicARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigDeliveryChannel) AWSCloudFormationType() string { - return "AWS::Config::DeliveryChannel" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSConfigDeliveryChannel) MarshalJSON() ([]byte, error) { - type Properties AWSConfigDeliveryChannel - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSConfigDeliveryChannel) UnmarshalJSON(b []byte) error { - type Properties AWSConfigDeliveryChannel - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSConfigDeliveryChannel(*res.Properties) - } - - return nil -} - -// GetAllAWSConfigDeliveryChannelResources retrieves all AWSConfigDeliveryChannel items from an AWS CloudFormation template -func (t *Template) GetAllAWSConfigDeliveryChannelResources() map[string]AWSConfigDeliveryChannel { - results := map[string]AWSConfigDeliveryChannel{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSConfigDeliveryChannel: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::DeliveryChannel" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigDeliveryChannel - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSConfigDeliveryChannelWithName retrieves all AWSConfigDeliveryChannel items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSConfigDeliveryChannelWithName(name string) (AWSConfigDeliveryChannel, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSConfigDeliveryChannel: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Config::DeliveryChannel" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSConfigDeliveryChannel - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSConfigDeliveryChannel{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel_configsnapshotdeliveryproperties.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel_configsnapshotdeliveryproperties.go deleted file mode 100644 index 011c75e9c9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-config-deliverychannel_configsnapshotdeliveryproperties.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSConfigDeliveryChannel_ConfigSnapshotDeliveryProperties AWS CloudFormation Resource (AWS::Config::DeliveryChannel.ConfigSnapshotDeliveryProperties) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-deliverychannel-configsnapshotdeliveryproperties.html -type AWSConfigDeliveryChannel_ConfigSnapshotDeliveryProperties struct { - - // DeliveryFrequency AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-config-deliverychannel-configsnapshotdeliveryproperties.html#cfn-config-deliverychannel-configsnapshotdeliveryproperties-deliveryfrequency - DeliveryFrequency string `json:"DeliveryFrequency,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSConfigDeliveryChannel_ConfigSnapshotDeliveryProperties) AWSCloudFormationType() string { - return "AWS::Config::DeliveryChannel.ConfigSnapshotDeliveryProperties" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline.go deleted file mode 100644 index fe31240dc3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDataPipelinePipeline AWS CloudFormation Resource (AWS::DataPipeline::Pipeline) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html -type AWSDataPipelinePipeline struct { - - // Activate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-activate - Activate bool `json:"Activate,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-name - Name string `json:"Name,omitempty"` - - // ParameterObjects AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-parameterobjects - ParameterObjects []AWSDataPipelinePipeline_ParameterObject `json:"ParameterObjects,omitempty"` - - // ParameterValues AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-parametervalues - ParameterValues []AWSDataPipelinePipeline_ParameterValue `json:"ParameterValues,omitempty"` - - // PipelineObjects AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-pipelineobjects - PipelineObjects []AWSDataPipelinePipeline_PipelineObject `json:"PipelineObjects,omitempty"` - - // PipelineTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-datapipeline-pipeline.html#cfn-datapipeline-pipeline-pipelinetags - PipelineTags []AWSDataPipelinePipeline_PipelineTag `json:"PipelineTags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDataPipelinePipeline) MarshalJSON() ([]byte, error) { - type Properties AWSDataPipelinePipeline - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDataPipelinePipeline) UnmarshalJSON(b []byte) error { - type Properties AWSDataPipelinePipeline - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDataPipelinePipeline(*res.Properties) - } - - return nil -} - -// GetAllAWSDataPipelinePipelineResources retrieves all AWSDataPipelinePipeline items from an AWS CloudFormation template -func (t *Template) GetAllAWSDataPipelinePipelineResources() map[string]AWSDataPipelinePipeline { - results := map[string]AWSDataPipelinePipeline{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDataPipelinePipeline: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DataPipeline::Pipeline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDataPipelinePipeline - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDataPipelinePipelineWithName retrieves all AWSDataPipelinePipeline items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDataPipelinePipelineWithName(name string) (AWSDataPipelinePipeline, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDataPipelinePipeline: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DataPipeline::Pipeline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDataPipelinePipeline - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDataPipelinePipeline{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_field.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_field.go deleted file mode 100644 index 08cc3f6eb3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_field.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_Field AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.Field) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects-fields.html -type AWSDataPipelinePipeline_Field struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects-fields.html#cfn-datapipeline-pipeline-pipelineobjects-fields-key - Key string `json:"Key,omitempty"` - - // RefValue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects-fields.html#cfn-datapipeline-pipeline-pipelineobjects-fields-refvalue - RefValue string `json:"RefValue,omitempty"` - - // StringValue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects-fields.html#cfn-datapipeline-pipeline-pipelineobjects-fields-stringvalue - StringValue string `json:"StringValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_Field) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.Field" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterattribute.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterattribute.go deleted file mode 100644 index 2edc518f1b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterattribute.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_ParameterAttribute AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.ParameterAttribute) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects-attributes.html -type AWSDataPipelinePipeline_ParameterAttribute struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects-attributes.html#cfn-datapipeline-pipeline-parameterobjects-attribtues-key - Key string `json:"Key,omitempty"` - - // StringValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects-attributes.html#cfn-datapipeline-pipeline-parameterobjects-attribtues-stringvalue - StringValue string `json:"StringValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_ParameterAttribute) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.ParameterAttribute" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterobject.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterobject.go deleted file mode 100644 index fcbdad4d0c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parameterobject.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_ParameterObject AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.ParameterObject) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html -type AWSDataPipelinePipeline_ParameterObject struct { - - // Attributes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html#cfn-datapipeline-pipeline-parameterobjects-attributes - Attributes []AWSDataPipelinePipeline_ParameterAttribute `json:"Attributes,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html#cfn-datapipeline-pipeline-parameterobjects-id - Id string `json:"Id,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_ParameterObject) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.ParameterObject" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parametervalue.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parametervalue.go deleted file mode 100644 index ac71d3b7db..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_parametervalue.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_ParameterValue AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.ParameterValue) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parametervalues.html -type AWSDataPipelinePipeline_ParameterValue struct { - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parametervalues.html#cfn-datapipeline-pipeline-parametervalues-id - Id string `json:"Id,omitempty"` - - // StringValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parametervalues.html#cfn-datapipeline-pipeline-parametervalues-stringvalue - StringValue string `json:"StringValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_ParameterValue) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.ParameterValue" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelineobject.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelineobject.go deleted file mode 100644 index 1087a4e7cf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelineobject.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_PipelineObject AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.PipelineObject) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects.html -type AWSDataPipelinePipeline_PipelineObject struct { - - // Fields AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects.html#cfn-datapipeline-pipeline-pipelineobjects-fields - Fields []AWSDataPipelinePipeline_Field `json:"Fields,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects.html#cfn-datapipeline-pipeline-pipelineobjects-id - Id string `json:"Id,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelineobjects.html#cfn-datapipeline-pipeline-pipelineobjects-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_PipelineObject) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.PipelineObject" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelinetag.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelinetag.go deleted file mode 100644 index 8c0b8a834c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-datapipeline-pipeline_pipelinetag.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDataPipelinePipeline_PipelineTag AWS CloudFormation Resource (AWS::DataPipeline::Pipeline.PipelineTag) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelinetags.html -type AWSDataPipelinePipeline_PipelineTag struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelinetags.html#cfn-datapipeline-pipeline-pipelinetags-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-pipelinetags.html#cfn-datapipeline-pipeline-pipelinetags-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDataPipelinePipeline_PipelineTag) AWSCloudFormationType() string { - return "AWS::DataPipeline::Pipeline.PipelineTag" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-cluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-cluster.go deleted file mode 100644 index 239e677c86..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-cluster.go +++ /dev/null @@ -1,165 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDAXCluster AWS CloudFormation Resource (AWS::DAX::Cluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html -type AWSDAXCluster struct { - - // AvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-availabilityzones - AvailabilityZones []string `json:"AvailabilityZones,omitempty"` - - // ClusterName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-clustername - ClusterName string `json:"ClusterName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-description - Description string `json:"Description,omitempty"` - - // IAMRoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-iamrolearn - IAMRoleARN string `json:"IAMRoleARN,omitempty"` - - // NodeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-nodetype - NodeType string `json:"NodeType,omitempty"` - - // NotificationTopicARN AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-notificationtopicarn - NotificationTopicARN string `json:"NotificationTopicARN,omitempty"` - - // ParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-parametergroupname - ParameterGroupName string `json:"ParameterGroupName,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // ReplicationFactor AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-replicationfactor - ReplicationFactor int `json:"ReplicationFactor,omitempty"` - - // SecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-subnetgroupname - SubnetGroupName string `json:"SubnetGroupName,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-cluster.html#cfn-dax-cluster-tags - Tags interface{} `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDAXCluster) AWSCloudFormationType() string { - return "AWS::DAX::Cluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDAXCluster) MarshalJSON() ([]byte, error) { - type Properties AWSDAXCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDAXCluster) UnmarshalJSON(b []byte) error { - type Properties AWSDAXCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDAXCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSDAXClusterResources retrieves all AWSDAXCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSDAXClusterResources() map[string]AWSDAXCluster { - results := map[string]AWSDAXCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDAXCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDAXClusterWithName retrieves all AWSDAXCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDAXClusterWithName(name string) (AWSDAXCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDAXCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDAXCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-parametergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-parametergroup.go deleted file mode 100644 index 5a47a7b014..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-parametergroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDAXParameterGroup AWS CloudFormation Resource (AWS::DAX::ParameterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-parametergroup.html -type AWSDAXParameterGroup struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-parametergroup.html#cfn-dax-parametergroup-description - Description string `json:"Description,omitempty"` - - // ParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-parametergroup.html#cfn-dax-parametergroup-parametergroupname - ParameterGroupName string `json:"ParameterGroupName,omitempty"` - - // ParameterNameValues AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-parametergroup.html#cfn-dax-parametergroup-parameternamevalues - ParameterNameValues interface{} `json:"ParameterNameValues,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDAXParameterGroup) AWSCloudFormationType() string { - return "AWS::DAX::ParameterGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDAXParameterGroup) MarshalJSON() ([]byte, error) { - type Properties AWSDAXParameterGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDAXParameterGroup) UnmarshalJSON(b []byte) error { - type Properties AWSDAXParameterGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDAXParameterGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSDAXParameterGroupResources retrieves all AWSDAXParameterGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSDAXParameterGroupResources() map[string]AWSDAXParameterGroup { - results := map[string]AWSDAXParameterGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDAXParameterGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::ParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDAXParameterGroupWithName retrieves all AWSDAXParameterGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDAXParameterGroupWithName(name string) (AWSDAXParameterGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDAXParameterGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::ParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDAXParameterGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-subnetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-subnetgroup.go deleted file mode 100644 index becc31461b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dax-subnetgroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDAXSubnetGroup AWS CloudFormation Resource (AWS::DAX::SubnetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-subnetgroup.html -type AWSDAXSubnetGroup struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-subnetgroup.html#cfn-dax-subnetgroup-description - Description string `json:"Description,omitempty"` - - // SubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-subnetgroup.html#cfn-dax-subnetgroup-subnetgroupname - SubnetGroupName string `json:"SubnetGroupName,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dax-subnetgroup.html#cfn-dax-subnetgroup-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDAXSubnetGroup) AWSCloudFormationType() string { - return "AWS::DAX::SubnetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDAXSubnetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSDAXSubnetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDAXSubnetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSDAXSubnetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDAXSubnetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSDAXSubnetGroupResources retrieves all AWSDAXSubnetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSDAXSubnetGroupResources() map[string]AWSDAXSubnetGroup { - results := map[string]AWSDAXSubnetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDAXSubnetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::SubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDAXSubnetGroupWithName retrieves all AWSDAXSubnetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDAXSubnetGroupWithName(name string) (AWSDAXSubnetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDAXSubnetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DAX::SubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDAXSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDAXSubnetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad.go deleted file mode 100644 index 308cb7d378..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDirectoryServiceMicrosoftAD AWS CloudFormation Resource (AWS::DirectoryService::MicrosoftAD) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html -type AWSDirectoryServiceMicrosoftAD struct { - - // CreateAlias AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-createalias - CreateAlias bool `json:"CreateAlias,omitempty"` - - // EnableSso AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-enablesso - EnableSso bool `json:"EnableSso,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-name - Name string `json:"Name,omitempty"` - - // Password AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-password - Password string `json:"Password,omitempty"` - - // ShortName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-shortname - ShortName string `json:"ShortName,omitempty"` - - // VpcSettings AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-microsoftad.html#cfn-directoryservice-microsoftad-vpcsettings - VpcSettings *AWSDirectoryServiceMicrosoftAD_VpcSettings `json:"VpcSettings,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDirectoryServiceMicrosoftAD) AWSCloudFormationType() string { - return "AWS::DirectoryService::MicrosoftAD" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDirectoryServiceMicrosoftAD) MarshalJSON() ([]byte, error) { - type Properties AWSDirectoryServiceMicrosoftAD - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDirectoryServiceMicrosoftAD) UnmarshalJSON(b []byte) error { - type Properties AWSDirectoryServiceMicrosoftAD - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDirectoryServiceMicrosoftAD(*res.Properties) - } - - return nil -} - -// GetAllAWSDirectoryServiceMicrosoftADResources retrieves all AWSDirectoryServiceMicrosoftAD items from an AWS CloudFormation template -func (t *Template) GetAllAWSDirectoryServiceMicrosoftADResources() map[string]AWSDirectoryServiceMicrosoftAD { - results := map[string]AWSDirectoryServiceMicrosoftAD{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDirectoryServiceMicrosoftAD: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DirectoryService::MicrosoftAD" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDirectoryServiceMicrosoftAD - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDirectoryServiceMicrosoftADWithName retrieves all AWSDirectoryServiceMicrosoftAD items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDirectoryServiceMicrosoftADWithName(name string) (AWSDirectoryServiceMicrosoftAD, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDirectoryServiceMicrosoftAD: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DirectoryService::MicrosoftAD" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDirectoryServiceMicrosoftAD - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDirectoryServiceMicrosoftAD{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad_vpcsettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad_vpcsettings.go deleted file mode 100644 index 05b0760c5d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-microsoftad_vpcsettings.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDirectoryServiceMicrosoftAD_VpcSettings AWS CloudFormation Resource (AWS::DirectoryService::MicrosoftAD.VpcSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html -type AWSDirectoryServiceMicrosoftAD_VpcSettings struct { - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html#cfn-directoryservice-microsoftad-vpcsettings-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-microsoftad-vpcsettings.html#cfn-directoryservice-microsoftad-vpcsettings-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDirectoryServiceMicrosoftAD_VpcSettings) AWSCloudFormationType() string { - return "AWS::DirectoryService::MicrosoftAD.VpcSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead.go deleted file mode 100644 index 1f486fcfdb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead.go +++ /dev/null @@ -1,145 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDirectoryServiceSimpleAD AWS CloudFormation Resource (AWS::DirectoryService::SimpleAD) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html -type AWSDirectoryServiceSimpleAD struct { - - // CreateAlias AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-createalias - CreateAlias bool `json:"CreateAlias,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-description - Description string `json:"Description,omitempty"` - - // EnableSso AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-enablesso - EnableSso bool `json:"EnableSso,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-name - Name string `json:"Name,omitempty"` - - // Password AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-password - Password string `json:"Password,omitempty"` - - // ShortName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-shortname - ShortName string `json:"ShortName,omitempty"` - - // Size AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-size - Size string `json:"Size,omitempty"` - - // VpcSettings AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-directoryservice-simplead.html#cfn-directoryservice-simplead-vpcsettings - VpcSettings *AWSDirectoryServiceSimpleAD_VpcSettings `json:"VpcSettings,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDirectoryServiceSimpleAD) AWSCloudFormationType() string { - return "AWS::DirectoryService::SimpleAD" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDirectoryServiceSimpleAD) MarshalJSON() ([]byte, error) { - type Properties AWSDirectoryServiceSimpleAD - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDirectoryServiceSimpleAD) UnmarshalJSON(b []byte) error { - type Properties AWSDirectoryServiceSimpleAD - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDirectoryServiceSimpleAD(*res.Properties) - } - - return nil -} - -// GetAllAWSDirectoryServiceSimpleADResources retrieves all AWSDirectoryServiceSimpleAD items from an AWS CloudFormation template -func (t *Template) GetAllAWSDirectoryServiceSimpleADResources() map[string]AWSDirectoryServiceSimpleAD { - results := map[string]AWSDirectoryServiceSimpleAD{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDirectoryServiceSimpleAD: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DirectoryService::SimpleAD" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDirectoryServiceSimpleAD - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDirectoryServiceSimpleADWithName retrieves all AWSDirectoryServiceSimpleAD items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDirectoryServiceSimpleADWithName(name string) (AWSDirectoryServiceSimpleAD, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDirectoryServiceSimpleAD: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DirectoryService::SimpleAD" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDirectoryServiceSimpleAD - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDirectoryServiceSimpleAD{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead_vpcsettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead_vpcsettings.go deleted file mode 100644 index 3db230f671..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-directoryservice-simplead_vpcsettings.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDirectoryServiceSimpleAD_VpcSettings AWS CloudFormation Resource (AWS::DirectoryService::SimpleAD.VpcSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-simplead-vpcsettings.html -type AWSDirectoryServiceSimpleAD_VpcSettings struct { - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-simplead-vpcsettings.html#cfn-directoryservice-simplead-vpcsettings-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-directoryservice-simplead-vpcsettings.html#cfn-directoryservice-simplead-vpcsettings-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDirectoryServiceSimpleAD_VpcSettings) AWSCloudFormationType() string { - return "AWS::DirectoryService::SimpleAD.VpcSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-certificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-certificate.go deleted file mode 100644 index 3268f45d75..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-certificate.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSCertificate AWS CloudFormation Resource (AWS::DMS::Certificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html -type AWSDMSCertificate struct { - - // CertificateIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificateidentifier - CertificateIdentifier string `json:"CertificateIdentifier,omitempty"` - - // CertificatePem AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificatepem - CertificatePem string `json:"CertificatePem,omitempty"` - - // CertificateWallet AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-certificate.html#cfn-dms-certificate-certificatewallet - CertificateWallet string `json:"CertificateWallet,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSCertificate) AWSCloudFormationType() string { - return "AWS::DMS::Certificate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSCertificate) MarshalJSON() ([]byte, error) { - type Properties AWSDMSCertificate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSCertificate) UnmarshalJSON(b []byte) error { - type Properties AWSDMSCertificate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSCertificate(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSCertificateResources retrieves all AWSDMSCertificate items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSCertificateResources() map[string]AWSDMSCertificate { - results := map[string]AWSDMSCertificate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSCertificate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSCertificate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSCertificateWithName retrieves all AWSDMSCertificate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSCertificateWithName(name string) (AWSDMSCertificate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSCertificate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSCertificate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSCertificate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint.go deleted file mode 100644 index 36b75d0c3d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSEndpoint AWS CloudFormation Resource (AWS::DMS::Endpoint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html -type AWSDMSEndpoint struct { - - // CertificateArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-certificatearn - CertificateArn string `json:"CertificateArn,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // DynamoDbSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-dynamodbsettings - DynamoDbSettings *AWSDMSEndpoint_DynamoDbSettings `json:"DynamoDbSettings,omitempty"` - - // EndpointIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-endpointidentifier - EndpointIdentifier string `json:"EndpointIdentifier,omitempty"` - - // EndpointType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-endpointtype - EndpointType string `json:"EndpointType,omitempty"` - - // EngineName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-enginename - EngineName string `json:"EngineName,omitempty"` - - // ExtraConnectionAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-extraconnectionattributes - ExtraConnectionAttributes string `json:"ExtraConnectionAttributes,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // MongoDbSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-mongodbsettings - MongoDbSettings *AWSDMSEndpoint_MongoDbSettings `json:"MongoDbSettings,omitempty"` - - // Password AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-password - Password string `json:"Password,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-port - Port int `json:"Port,omitempty"` - - // S3Settings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-s3settings - S3Settings *AWSDMSEndpoint_S3Settings `json:"S3Settings,omitempty"` - - // ServerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-servername - ServerName string `json:"ServerName,omitempty"` - - // SslMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-sslmode - SslMode string `json:"SslMode,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-tags - Tags []Tag `json:"Tags,omitempty"` - - // Username AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-endpoint.html#cfn-dms-endpoint-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSEndpoint) AWSCloudFormationType() string { - return "AWS::DMS::Endpoint" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSEndpoint) MarshalJSON() ([]byte, error) { - type Properties AWSDMSEndpoint - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSEndpoint) UnmarshalJSON(b []byte) error { - type Properties AWSDMSEndpoint - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSEndpoint(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSEndpointResources retrieves all AWSDMSEndpoint items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSEndpointResources() map[string]AWSDMSEndpoint { - results := map[string]AWSDMSEndpoint{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSEndpoint: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::Endpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSEndpoint - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSEndpointWithName retrieves all AWSDMSEndpoint items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSEndpointWithName(name string) (AWSDMSEndpoint, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSEndpoint: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::Endpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSEndpoint - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSEndpoint{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_dynamodbsettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_dynamodbsettings.go deleted file mode 100644 index a0381945a5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_dynamodbsettings.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSDMSEndpoint_DynamoDbSettings AWS CloudFormation Resource (AWS::DMS::Endpoint.DynamoDbSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-dynamodbsettings.html -type AWSDMSEndpoint_DynamoDbSettings struct { - - // ServiceAccessRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-dynamodbsettings.html#cfn-dms-endpoint-dynamodbsettings-serviceaccessrolearn - ServiceAccessRoleArn string `json:"ServiceAccessRoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSEndpoint_DynamoDbSettings) AWSCloudFormationType() string { - return "AWS::DMS::Endpoint.DynamoDbSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_mongodbsettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_mongodbsettings.go deleted file mode 100644 index 7702c1d811..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_mongodbsettings.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudformation - -// AWSDMSEndpoint_MongoDbSettings AWS CloudFormation Resource (AWS::DMS::Endpoint.MongoDbSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html -type AWSDMSEndpoint_MongoDbSettings struct { - - // AuthMechanism AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-authmechanism - AuthMechanism string `json:"AuthMechanism,omitempty"` - - // AuthSource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-authsource - AuthSource string `json:"AuthSource,omitempty"` - - // AuthType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-authtype - AuthType string `json:"AuthType,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // DocsToInvestigate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-docstoinvestigate - DocsToInvestigate string `json:"DocsToInvestigate,omitempty"` - - // ExtractDocId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-extractdocid - ExtractDocId string `json:"ExtractDocId,omitempty"` - - // NestingLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-nestinglevel - NestingLevel string `json:"NestingLevel,omitempty"` - - // Password AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-password - Password string `json:"Password,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-port - Port int `json:"Port,omitempty"` - - // ServerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-servername - ServerName string `json:"ServerName,omitempty"` - - // Username AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-mongodbsettings.html#cfn-dms-endpoint-mongodbsettings-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSEndpoint_MongoDbSettings) AWSCloudFormationType() string { - return "AWS::DMS::Endpoint.MongoDbSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_s3settings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_s3settings.go deleted file mode 100644 index a5e93b0394..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-endpoint_s3settings.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSDMSEndpoint_S3Settings AWS CloudFormation Resource (AWS::DMS::Endpoint.S3Settings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html -type AWSDMSEndpoint_S3Settings struct { - - // BucketFolder AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-bucketfolder - BucketFolder string `json:"BucketFolder,omitempty"` - - // BucketName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-bucketname - BucketName string `json:"BucketName,omitempty"` - - // CompressionType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-compressiontype - CompressionType string `json:"CompressionType,omitempty"` - - // CsvDelimiter AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-csvdelimiter - CsvDelimiter string `json:"CsvDelimiter,omitempty"` - - // CsvRowDelimiter AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-csvrowdelimiter - CsvRowDelimiter string `json:"CsvRowDelimiter,omitempty"` - - // ExternalTableDefinition AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-externaltabledefinition - ExternalTableDefinition string `json:"ExternalTableDefinition,omitempty"` - - // ServiceAccessRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dms-endpoint-s3settings.html#cfn-dms-endpoint-s3settings-serviceaccessrolearn - ServiceAccessRoleArn string `json:"ServiceAccessRoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSEndpoint_S3Settings) AWSCloudFormationType() string { - return "AWS::DMS::Endpoint.S3Settings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-eventsubscription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-eventsubscription.go deleted file mode 100644 index 0d6ab95a53..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-eventsubscription.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSEventSubscription AWS CloudFormation Resource (AWS::DMS::EventSubscription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html -type AWSDMSEventSubscription struct { - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-enabled - Enabled bool `json:"Enabled,omitempty"` - - // EventCategories AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-eventcategories - EventCategories []string `json:"EventCategories,omitempty"` - - // SnsTopicArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-snstopicarn - SnsTopicArn string `json:"SnsTopicArn,omitempty"` - - // SourceIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-sourceids - SourceIds []string `json:"SourceIds,omitempty"` - - // SourceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-sourcetype - SourceType string `json:"SourceType,omitempty"` - - // SubscriptionName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-subscriptionname - SubscriptionName string `json:"SubscriptionName,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-eventsubscription.html#cfn-dms-eventsubscription-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSEventSubscription) AWSCloudFormationType() string { - return "AWS::DMS::EventSubscription" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSEventSubscription) MarshalJSON() ([]byte, error) { - type Properties AWSDMSEventSubscription - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSEventSubscription) UnmarshalJSON(b []byte) error { - type Properties AWSDMSEventSubscription - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSEventSubscription(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSEventSubscriptionResources retrieves all AWSDMSEventSubscription items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSEventSubscriptionResources() map[string]AWSDMSEventSubscription { - results := map[string]AWSDMSEventSubscription{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSEventSubscription: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::EventSubscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSEventSubscription - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSEventSubscriptionWithName retrieves all AWSDMSEventSubscription items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSEventSubscriptionWithName(name string) (AWSDMSEventSubscription, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSEventSubscription: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::EventSubscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSEventSubscription - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSEventSubscription{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationinstance.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationinstance.go deleted file mode 100644 index 8ec13e44f4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationinstance.go +++ /dev/null @@ -1,175 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSReplicationInstance AWS CloudFormation Resource (AWS::DMS::ReplicationInstance) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html -type AWSDMSReplicationInstance struct { - - // AllocatedStorage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-allocatedstorage - AllocatedStorage int `json:"AllocatedStorage,omitempty"` - - // AllowMajorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-allowmajorversionupgrade - AllowMajorVersionUpgrade bool `json:"AllowMajorVersionUpgrade,omitempty"` - - // AutoMinorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-autominorversionupgrade - AutoMinorVersionUpgrade bool `json:"AutoMinorVersionUpgrade,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // EngineVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-engineversion - EngineVersion string `json:"EngineVersion,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // MultiAZ AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-multiaz - MultiAZ bool `json:"MultiAZ,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // PubliclyAccessible AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-publiclyaccessible - PubliclyAccessible bool `json:"PubliclyAccessible,omitempty"` - - // ReplicationInstanceClass AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-replicationinstanceclass - ReplicationInstanceClass string `json:"ReplicationInstanceClass,omitempty"` - - // ReplicationInstanceIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-replicationinstanceidentifier - ReplicationInstanceIdentifier string `json:"ReplicationInstanceIdentifier,omitempty"` - - // ReplicationSubnetGroupIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-replicationsubnetgroupidentifier - ReplicationSubnetGroupIdentifier string `json:"ReplicationSubnetGroupIdentifier,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcSecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationinstance.html#cfn-dms-replicationinstance-vpcsecuritygroupids - VpcSecurityGroupIds []string `json:"VpcSecurityGroupIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSReplicationInstance) AWSCloudFormationType() string { - return "AWS::DMS::ReplicationInstance" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSReplicationInstance) MarshalJSON() ([]byte, error) { - type Properties AWSDMSReplicationInstance - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSReplicationInstance) UnmarshalJSON(b []byte) error { - type Properties AWSDMSReplicationInstance - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSReplicationInstance(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSReplicationInstanceResources retrieves all AWSDMSReplicationInstance items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSReplicationInstanceResources() map[string]AWSDMSReplicationInstance { - results := map[string]AWSDMSReplicationInstance{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSReplicationInstance: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationInstance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationInstance - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSReplicationInstanceWithName retrieves all AWSDMSReplicationInstance items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSReplicationInstanceWithName(name string) (AWSDMSReplicationInstance, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSReplicationInstance: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationInstance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationInstance - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSReplicationInstance{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationsubnetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationsubnetgroup.go deleted file mode 100644 index d6abfa3b6d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationsubnetgroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSReplicationSubnetGroup AWS CloudFormation Resource (AWS::DMS::ReplicationSubnetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationsubnetgroup.html -type AWSDMSReplicationSubnetGroup struct { - - // ReplicationSubnetGroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationsubnetgroup.html#cfn-dms-replicationsubnetgroup-replicationsubnetgroupdescription - ReplicationSubnetGroupDescription string `json:"ReplicationSubnetGroupDescription,omitempty"` - - // ReplicationSubnetGroupIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationsubnetgroup.html#cfn-dms-replicationsubnetgroup-replicationsubnetgroupidentifier - ReplicationSubnetGroupIdentifier string `json:"ReplicationSubnetGroupIdentifier,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationsubnetgroup.html#cfn-dms-replicationsubnetgroup-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationsubnetgroup.html#cfn-dms-replicationsubnetgroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSReplicationSubnetGroup) AWSCloudFormationType() string { - return "AWS::DMS::ReplicationSubnetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSReplicationSubnetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSDMSReplicationSubnetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSReplicationSubnetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSDMSReplicationSubnetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSReplicationSubnetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSReplicationSubnetGroupResources retrieves all AWSDMSReplicationSubnetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSReplicationSubnetGroupResources() map[string]AWSDMSReplicationSubnetGroup { - results := map[string]AWSDMSReplicationSubnetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSReplicationSubnetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSReplicationSubnetGroupWithName retrieves all AWSDMSReplicationSubnetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSReplicationSubnetGroupWithName(name string) (AWSDMSReplicationSubnetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSReplicationSubnetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSReplicationSubnetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationtask.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationtask.go deleted file mode 100644 index afdefcea59..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dms-replicationtask.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDMSReplicationTask AWS CloudFormation Resource (AWS::DMS::ReplicationTask) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html -type AWSDMSReplicationTask struct { - - // CdcStartTime AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-cdcstarttime - CdcStartTime float64 `json:"CdcStartTime,omitempty"` - - // MigrationType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-migrationtype - MigrationType string `json:"MigrationType,omitempty"` - - // ReplicationInstanceArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-replicationinstancearn - ReplicationInstanceArn string `json:"ReplicationInstanceArn,omitempty"` - - // ReplicationTaskIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-replicationtaskidentifier - ReplicationTaskIdentifier string `json:"ReplicationTaskIdentifier,omitempty"` - - // ReplicationTaskSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-replicationtasksettings - ReplicationTaskSettings string `json:"ReplicationTaskSettings,omitempty"` - - // SourceEndpointArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-sourceendpointarn - SourceEndpointArn string `json:"SourceEndpointArn,omitempty"` - - // TableMappings AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-tablemappings - TableMappings string `json:"TableMappings,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-tags - Tags []Tag `json:"Tags,omitempty"` - - // TargetEndpointArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dms-replicationtask.html#cfn-dms-replicationtask-targetendpointarn - TargetEndpointArn string `json:"TargetEndpointArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDMSReplicationTask) AWSCloudFormationType() string { - return "AWS::DMS::ReplicationTask" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDMSReplicationTask) MarshalJSON() ([]byte, error) { - type Properties AWSDMSReplicationTask - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDMSReplicationTask) UnmarshalJSON(b []byte) error { - type Properties AWSDMSReplicationTask - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDMSReplicationTask(*res.Properties) - } - - return nil -} - -// GetAllAWSDMSReplicationTaskResources retrieves all AWSDMSReplicationTask items from an AWS CloudFormation template -func (t *Template) GetAllAWSDMSReplicationTaskResources() map[string]AWSDMSReplicationTask { - results := map[string]AWSDMSReplicationTask{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDMSReplicationTask: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationTask" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationTask - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDMSReplicationTaskWithName retrieves all AWSDMSReplicationTask items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDMSReplicationTaskWithName(name string) (AWSDMSReplicationTask, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDMSReplicationTask: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DMS::ReplicationTask" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDMSReplicationTask - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDMSReplicationTask{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table.go deleted file mode 100644 index 70a20c3297..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSDynamoDBTable AWS CloudFormation Resource (AWS::DynamoDB::Table) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html -type AWSDynamoDBTable struct { - - // AttributeDefinitions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-attributedef - AttributeDefinitions []AWSDynamoDBTable_AttributeDefinition `json:"AttributeDefinitions,omitempty"` - - // GlobalSecondaryIndexes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-gsi - GlobalSecondaryIndexes []AWSDynamoDBTable_GlobalSecondaryIndex `json:"GlobalSecondaryIndexes,omitempty"` - - // KeySchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-keyschema - KeySchema []AWSDynamoDBTable_KeySchema `json:"KeySchema,omitempty"` - - // LocalSecondaryIndexes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-lsi - LocalSecondaryIndexes []AWSDynamoDBTable_LocalSecondaryIndex `json:"LocalSecondaryIndexes,omitempty"` - - // ProvisionedThroughput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-provisionedthroughput - ProvisionedThroughput *AWSDynamoDBTable_ProvisionedThroughput `json:"ProvisionedThroughput,omitempty"` - - // StreamSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-streamspecification - StreamSpecification *AWSDynamoDBTable_StreamSpecification `json:"StreamSpecification,omitempty"` - - // TableName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-tablename - TableName string `json:"TableName,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-tags - Tags []Tag `json:"Tags,omitempty"` - - // TimeToLiveSpecification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-table.html#cfn-dynamodb-table-timetolivespecification - TimeToLiveSpecification *AWSDynamoDBTable_TimeToLiveSpecification `json:"TimeToLiveSpecification,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSDynamoDBTable) MarshalJSON() ([]byte, error) { - type Properties AWSDynamoDBTable - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSDynamoDBTable) UnmarshalJSON(b []byte) error { - type Properties AWSDynamoDBTable - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSDynamoDBTable(*res.Properties) - } - - return nil -} - -// GetAllAWSDynamoDBTableResources retrieves all AWSDynamoDBTable items from an AWS CloudFormation template -func (t *Template) GetAllAWSDynamoDBTableResources() map[string]AWSDynamoDBTable { - results := map[string]AWSDynamoDBTable{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSDynamoDBTable: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DynamoDB::Table" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDynamoDBTable - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSDynamoDBTableWithName retrieves all AWSDynamoDBTable items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSDynamoDBTableWithName(name string) (AWSDynamoDBTable, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSDynamoDBTable: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::DynamoDB::Table" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSDynamoDBTable - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSDynamoDBTable{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_attributedefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_attributedefinition.go deleted file mode 100644 index 2b91b05238..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_attributedefinition.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_AttributeDefinition AWS CloudFormation Resource (AWS::DynamoDB::Table.AttributeDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html -type AWSDynamoDBTable_AttributeDefinition struct { - - // AttributeName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename - AttributeName string `json:"AttributeName,omitempty"` - - // AttributeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-attributedef.html#cfn-dynamodb-attributedef-attributename-attributetype - AttributeType string `json:"AttributeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_AttributeDefinition) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.AttributeDefinition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_globalsecondaryindex.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_globalsecondaryindex.go deleted file mode 100644 index 6ee3a0ccf9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_globalsecondaryindex.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_GlobalSecondaryIndex AWS CloudFormation Resource (AWS::DynamoDB::Table.GlobalSecondaryIndex) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-gsi.html -type AWSDynamoDBTable_GlobalSecondaryIndex struct { - - // IndexName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-gsi.html#cfn-dynamodb-gsi-indexname - IndexName string `json:"IndexName,omitempty"` - - // KeySchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-gsi.html#cfn-dynamodb-gsi-keyschema - KeySchema []AWSDynamoDBTable_KeySchema `json:"KeySchema,omitempty"` - - // Projection AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-gsi.html#cfn-dynamodb-gsi-projection - Projection *AWSDynamoDBTable_Projection `json:"Projection,omitempty"` - - // ProvisionedThroughput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-gsi.html#cfn-dynamodb-gsi-provisionedthroughput - ProvisionedThroughput *AWSDynamoDBTable_ProvisionedThroughput `json:"ProvisionedThroughput,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_GlobalSecondaryIndex) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.GlobalSecondaryIndex" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_keyschema.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_keyschema.go deleted file mode 100644 index 495b8b2ff8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_keyschema.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_KeySchema AWS CloudFormation Resource (AWS::DynamoDB::Table.KeySchema) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-keyschema.html -type AWSDynamoDBTable_KeySchema struct { - - // AttributeName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-keyschema.html#aws-properties-dynamodb-keyschema-attributename - AttributeName string `json:"AttributeName,omitempty"` - - // KeyType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-keyschema.html#aws-properties-dynamodb-keyschema-keytype - KeyType string `json:"KeyType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_KeySchema) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.KeySchema" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_localsecondaryindex.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_localsecondaryindex.go deleted file mode 100644 index 4b1411f3d0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_localsecondaryindex.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_LocalSecondaryIndex AWS CloudFormation Resource (AWS::DynamoDB::Table.LocalSecondaryIndex) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-lsi.html -type AWSDynamoDBTable_LocalSecondaryIndex struct { - - // IndexName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-lsi.html#cfn-dynamodb-lsi-indexname - IndexName string `json:"IndexName,omitempty"` - - // KeySchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-lsi.html#cfn-dynamodb-lsi-keyschema - KeySchema []AWSDynamoDBTable_KeySchema `json:"KeySchema,omitempty"` - - // Projection AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-lsi.html#cfn-dynamodb-lsi-projection - Projection *AWSDynamoDBTable_Projection `json:"Projection,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_LocalSecondaryIndex) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.LocalSecondaryIndex" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_projection.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_projection.go deleted file mode 100644 index ae2ce9f308..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_projection.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_Projection AWS CloudFormation Resource (AWS::DynamoDB::Table.Projection) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-projectionobject.html -type AWSDynamoDBTable_Projection struct { - - // NonKeyAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-projectionobject.html#cfn-dynamodb-projectionobj-nonkeyatt - NonKeyAttributes []string `json:"NonKeyAttributes,omitempty"` - - // ProjectionType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-projectionobject.html#cfn-dynamodb-projectionobj-projtype - ProjectionType string `json:"ProjectionType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_Projection) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.Projection" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_provisionedthroughput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_provisionedthroughput.go deleted file mode 100644 index 244b147210..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_provisionedthroughput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_ProvisionedThroughput AWS CloudFormation Resource (AWS::DynamoDB::Table.ProvisionedThroughput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html -type AWSDynamoDBTable_ProvisionedThroughput struct { - - // ReadCapacityUnits AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html#cfn-dynamodb-provisionedthroughput-readcapacityunits - ReadCapacityUnits int64 `json:"ReadCapacityUnits,omitempty"` - - // WriteCapacityUnits AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html#cfn-dynamodb-provisionedthroughput-writecapacityunits - WriteCapacityUnits int64 `json:"WriteCapacityUnits,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_ProvisionedThroughput) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.ProvisionedThroughput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_streamspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_streamspecification.go deleted file mode 100644 index 67755dbcb1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_streamspecification.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_StreamSpecification AWS CloudFormation Resource (AWS::DynamoDB::Table.StreamSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-streamspecification.html -type AWSDynamoDBTable_StreamSpecification struct { - - // StreamViewType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-streamspecification.html#cfn-dynamodb-streamspecification-streamviewtype - StreamViewType string `json:"StreamViewType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_StreamSpecification) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.StreamSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_timetolivespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_timetolivespecification.go deleted file mode 100644 index 1bfef1d459..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-dynamodb-table_timetolivespecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSDynamoDBTable_TimeToLiveSpecification AWS CloudFormation Resource (AWS::DynamoDB::Table.TimeToLiveSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-timetolivespecification.html -type AWSDynamoDBTable_TimeToLiveSpecification struct { - - // AttributeName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-timetolivespecification.html#cfn-dynamodb-timetolivespecification-attributename - AttributeName string `json:"AttributeName,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-timetolivespecification.html#cfn-dynamodb-timetolivespecification-enabled - Enabled bool `json:"Enabled,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSDynamoDBTable_TimeToLiveSpecification) AWSCloudFormationType() string { - return "AWS::DynamoDB::Table.TimeToLiveSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-customergateway.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-customergateway.go deleted file mode 100644 index e6087c9789..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-customergateway.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2CustomerGateway AWS CloudFormation Resource (AWS::EC2::CustomerGateway) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html -type AWSEC2CustomerGateway struct { - - // BgpAsn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-bgpasn - BgpAsn int `json:"BgpAsn,omitempty"` - - // IpAddress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-ipaddress - IpAddress string `json:"IpAddress,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-tags - Tags []Tag `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-customer-gateway.html#cfn-ec2-customergateway-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2CustomerGateway) AWSCloudFormationType() string { - return "AWS::EC2::CustomerGateway" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2CustomerGateway) MarshalJSON() ([]byte, error) { - type Properties AWSEC2CustomerGateway - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2CustomerGateway) UnmarshalJSON(b []byte) error { - type Properties AWSEC2CustomerGateway - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2CustomerGateway(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2CustomerGatewayResources retrieves all AWSEC2CustomerGateway items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2CustomerGatewayResources() map[string]AWSEC2CustomerGateway { - results := map[string]AWSEC2CustomerGateway{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2CustomerGateway: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::CustomerGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2CustomerGateway - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2CustomerGatewayWithName retrieves all AWSEC2CustomerGateway items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2CustomerGatewayWithName(name string) (AWSEC2CustomerGateway, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2CustomerGateway: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::CustomerGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2CustomerGateway - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2CustomerGateway{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-dhcpoptions.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-dhcpoptions.go deleted file mode 100644 index 2e2f5dc144..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-dhcpoptions.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2DHCPOptions AWS CloudFormation Resource (AWS::EC2::DHCPOptions) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html -type AWSEC2DHCPOptions struct { - - // DomainName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainname - DomainName string `json:"DomainName,omitempty"` - - // DomainNameServers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-domainnameservers - DomainNameServers []string `json:"DomainNameServers,omitempty"` - - // NetbiosNameServers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnameservers - NetbiosNameServers []string `json:"NetbiosNameServers,omitempty"` - - // NetbiosNodeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-netbiosnodetype - NetbiosNodeType int `json:"NetbiosNodeType,omitempty"` - - // NtpServers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-ntpservers - NtpServers []string `json:"NtpServers,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-dhcp-options.html#cfn-ec2-dhcpoptions-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2DHCPOptions) AWSCloudFormationType() string { - return "AWS::EC2::DHCPOptions" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2DHCPOptions) MarshalJSON() ([]byte, error) { - type Properties AWSEC2DHCPOptions - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2DHCPOptions) UnmarshalJSON(b []byte) error { - type Properties AWSEC2DHCPOptions - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2DHCPOptions(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2DHCPOptionsResources retrieves all AWSEC2DHCPOptions items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2DHCPOptionsResources() map[string]AWSEC2DHCPOptions { - results := map[string]AWSEC2DHCPOptions{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2DHCPOptions: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::DHCPOptions" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2DHCPOptions - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2DHCPOptionsWithName retrieves all AWSEC2DHCPOptions items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2DHCPOptionsWithName(name string) (AWSEC2DHCPOptions, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2DHCPOptions: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::DHCPOptions" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2DHCPOptions - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2DHCPOptions{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-egressonlyinternetgateway.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-egressonlyinternetgateway.go deleted file mode 100644 index d397159ce5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-egressonlyinternetgateway.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2EgressOnlyInternetGateway AWS CloudFormation Resource (AWS::EC2::EgressOnlyInternetGateway) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html -type AWSEC2EgressOnlyInternetGateway struct { - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-egressonlyinternetgateway.html#cfn-ec2-egressonlyinternetgateway-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2EgressOnlyInternetGateway) AWSCloudFormationType() string { - return "AWS::EC2::EgressOnlyInternetGateway" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2EgressOnlyInternetGateway) MarshalJSON() ([]byte, error) { - type Properties AWSEC2EgressOnlyInternetGateway - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2EgressOnlyInternetGateway) UnmarshalJSON(b []byte) error { - type Properties AWSEC2EgressOnlyInternetGateway - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2EgressOnlyInternetGateway(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2EgressOnlyInternetGatewayResources retrieves all AWSEC2EgressOnlyInternetGateway items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2EgressOnlyInternetGatewayResources() map[string]AWSEC2EgressOnlyInternetGateway { - results := map[string]AWSEC2EgressOnlyInternetGateway{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2EgressOnlyInternetGateway: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EgressOnlyInternetGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EgressOnlyInternetGateway - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2EgressOnlyInternetGatewayWithName retrieves all AWSEC2EgressOnlyInternetGateway items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2EgressOnlyInternetGatewayWithName(name string) (AWSEC2EgressOnlyInternetGateway, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2EgressOnlyInternetGateway: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EgressOnlyInternetGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EgressOnlyInternetGateway - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2EgressOnlyInternetGateway{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eip.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eip.go deleted file mode 100644 index 2c19499663..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eip.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2EIP AWS CloudFormation Resource (AWS::EC2::EIP) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html -type AWSEC2EIP struct { - - // Domain AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-domain - Domain string `json:"Domain,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip.html#cfn-ec2-eip-instanceid - InstanceId string `json:"InstanceId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2EIP) AWSCloudFormationType() string { - return "AWS::EC2::EIP" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2EIP) MarshalJSON() ([]byte, error) { - type Properties AWSEC2EIP - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2EIP) UnmarshalJSON(b []byte) error { - type Properties AWSEC2EIP - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2EIP(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2EIPResources retrieves all AWSEC2EIP items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2EIPResources() map[string]AWSEC2EIP { - results := map[string]AWSEC2EIP{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2EIP: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EIP" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EIP - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2EIPWithName retrieves all AWSEC2EIP items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2EIPWithName(name string) (AWSEC2EIP, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2EIP: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EIP" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EIP - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2EIP{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eipassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eipassociation.go deleted file mode 100644 index 66e77ce592..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-eipassociation.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2EIPAssociation AWS CloudFormation Resource (AWS::EC2::EIPAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html -type AWSEC2EIPAssociation struct { - - // AllocationId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-allocationid - AllocationId string `json:"AllocationId,omitempty"` - - // EIP AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-eip - EIP string `json:"EIP,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-networkinterfaceid - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-eip-association.html#cfn-ec2-eipassociation-PrivateIpAddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2EIPAssociation) AWSCloudFormationType() string { - return "AWS::EC2::EIPAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2EIPAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2EIPAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2EIPAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2EIPAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2EIPAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2EIPAssociationResources retrieves all AWSEC2EIPAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2EIPAssociationResources() map[string]AWSEC2EIPAssociation { - results := map[string]AWSEC2EIPAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2EIPAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EIPAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EIPAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2EIPAssociationWithName retrieves all AWSEC2EIPAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2EIPAssociationWithName(name string) (AWSEC2EIPAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2EIPAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::EIPAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2EIPAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2EIPAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-flowlog.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-flowlog.go deleted file mode 100644 index 65dfe8acd8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-flowlog.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2FlowLog AWS CloudFormation Resource (AWS::EC2::FlowLog) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html -type AWSEC2FlowLog struct { - - // DeliverLogsPermissionArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-deliverlogspermissionarn - DeliverLogsPermissionArn string `json:"DeliverLogsPermissionArn,omitempty"` - - // LogGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // ResourceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourceid - ResourceId string `json:"ResourceId,omitempty"` - - // ResourceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-resourcetype - ResourceType string `json:"ResourceType,omitempty"` - - // TrafficType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-flowlog.html#cfn-ec2-flowlog-traffictype - TrafficType string `json:"TrafficType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2FlowLog) AWSCloudFormationType() string { - return "AWS::EC2::FlowLog" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2FlowLog) MarshalJSON() ([]byte, error) { - type Properties AWSEC2FlowLog - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2FlowLog) UnmarshalJSON(b []byte) error { - type Properties AWSEC2FlowLog - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2FlowLog(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2FlowLogResources retrieves all AWSEC2FlowLog items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2FlowLogResources() map[string]AWSEC2FlowLog { - results := map[string]AWSEC2FlowLog{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2FlowLog: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::FlowLog" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2FlowLog - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2FlowLogWithName retrieves all AWSEC2FlowLog items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2FlowLogWithName(name string) (AWSEC2FlowLog, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2FlowLog: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::FlowLog" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2FlowLog - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2FlowLog{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-host.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-host.go deleted file mode 100644 index 08f7f87ff0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-host.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2Host AWS CloudFormation Resource (AWS::EC2::Host) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html -type AWSEC2Host struct { - - // AutoPlacement AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-autoplacement - AutoPlacement string `json:"AutoPlacement,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-host.html#cfn-ec2-host-instancetype - InstanceType string `json:"InstanceType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Host) AWSCloudFormationType() string { - return "AWS::EC2::Host" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2Host) MarshalJSON() ([]byte, error) { - type Properties AWSEC2Host - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2Host) UnmarshalJSON(b []byte) error { - type Properties AWSEC2Host - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2Host(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2HostResources retrieves all AWSEC2Host items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2HostResources() map[string]AWSEC2Host { - results := map[string]AWSEC2Host{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2Host: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Host" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Host - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2HostWithName retrieves all AWSEC2Host items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2HostWithName(name string) (AWSEC2Host, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2Host: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Host" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Host - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2Host{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance.go deleted file mode 100644 index 9282233224..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance.go +++ /dev/null @@ -1,255 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2Instance AWS CloudFormation Resource (AWS::EC2::Instance) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html -type AWSEC2Instance struct { - - // AdditionalInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-additionalinfo - AdditionalInfo string `json:"AdditionalInfo,omitempty"` - - // Affinity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-affinity - Affinity string `json:"Affinity,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // BlockDeviceMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-blockdevicemappings - BlockDeviceMappings []AWSEC2Instance_BlockDeviceMapping `json:"BlockDeviceMappings,omitempty"` - - // DisableApiTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-disableapitermination - DisableApiTermination bool `json:"DisableApiTermination,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` - - // ElasticGpuSpecifications AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-elasticgpuspecifications - ElasticGpuSpecifications []AWSEC2Instance_ElasticGpuSpecification `json:"ElasticGpuSpecifications,omitempty"` - - // HostId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-hostid - HostId string `json:"HostId,omitempty"` - - // IamInstanceProfile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-iaminstanceprofile - IamInstanceProfile string `json:"IamInstanceProfile,omitempty"` - - // ImageId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-imageid - ImageId string `json:"ImageId,omitempty"` - - // InstanceInitiatedShutdownBehavior AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instanceinitiatedshutdownbehavior - InstanceInitiatedShutdownBehavior string `json:"InstanceInitiatedShutdownBehavior,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // Ipv6AddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresscount - Ipv6AddressCount int `json:"Ipv6AddressCount,omitempty"` - - // Ipv6Addresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ipv6addresses - Ipv6Addresses []AWSEC2Instance_InstanceIpv6Address `json:"Ipv6Addresses,omitempty"` - - // KernelId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-kernelid - KernelId string `json:"KernelId,omitempty"` - - // KeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-keyname - KeyName string `json:"KeyName,omitempty"` - - // Monitoring AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-monitoring - Monitoring bool `json:"Monitoring,omitempty"` - - // NetworkInterfaces AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-networkinterfaces - NetworkInterfaces []AWSEC2Instance_NetworkInterface `json:"NetworkInterfaces,omitempty"` - - // PlacementGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-placementgroupname - PlacementGroupName string `json:"PlacementGroupName,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` - - // RamdiskId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ramdiskid - RamdiskId string `json:"RamdiskId,omitempty"` - - // SecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-securitygroups - SecurityGroups []string `json:"SecurityGroups,omitempty"` - - // SourceDestCheck AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-sourcedestcheck - SourceDestCheck bool `json:"SourceDestCheck,omitempty"` - - // SsmAssociations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-ssmassociations - SsmAssociations []AWSEC2Instance_SsmAssociation `json:"SsmAssociations,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-subnetid - SubnetId string `json:"SubnetId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tags - Tags []Tag `json:"Tags,omitempty"` - - // Tenancy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-tenancy - Tenancy string `json:"Tenancy,omitempty"` - - // UserData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-userdata - UserData string `json:"UserData,omitempty"` - - // Volumes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance.html#cfn-ec2-instance-volumes - Volumes []AWSEC2Instance_Volume `json:"Volumes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance) AWSCloudFormationType() string { - return "AWS::EC2::Instance" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2Instance) MarshalJSON() ([]byte, error) { - type Properties AWSEC2Instance - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2Instance) UnmarshalJSON(b []byte) error { - type Properties AWSEC2Instance - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2Instance(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2InstanceResources retrieves all AWSEC2Instance items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2InstanceResources() map[string]AWSEC2Instance { - results := map[string]AWSEC2Instance{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2Instance: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Instance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Instance - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2InstanceWithName retrieves all AWSEC2Instance items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2InstanceWithName(name string) (AWSEC2Instance, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2Instance: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Instance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Instance - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2Instance{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_associationparameter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_associationparameter.go deleted file mode 100644 index 0af8b10922..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_associationparameter.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2Instance_AssociationParameter AWS CloudFormation Resource (AWS::EC2::Instance.AssociationParameter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html -type AWSEC2Instance_AssociationParameter struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html#cfn-ec2-instance-ssmassociations-associationparameters-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations-associationparameters.html#cfn-ec2-instance-ssmassociations-associationparameters-value - Value []string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_AssociationParameter) AWSCloudFormationType() string { - return "AWS::EC2::Instance.AssociationParameter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_blockdevicemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_blockdevicemapping.go deleted file mode 100644 index a2e727a4ad..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_blockdevicemapping.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEC2Instance_BlockDeviceMapping AWS CloudFormation Resource (AWS::EC2::Instance.BlockDeviceMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html -type AWSEC2Instance_BlockDeviceMapping struct { - - // DeviceName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-devicename - DeviceName string `json:"DeviceName,omitempty"` - - // Ebs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-ebs - Ebs *AWSEC2Instance_Ebs `json:"Ebs,omitempty"` - - // NoDevice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-nodevice - NoDevice *AWSEC2Instance_NoDevice `json:"NoDevice,omitempty"` - - // VirtualName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-mapping.html#cfn-ec2-blockdev-mapping-virtualname - VirtualName string `json:"VirtualName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_BlockDeviceMapping) AWSCloudFormationType() string { - return "AWS::EC2::Instance.BlockDeviceMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ebs.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ebs.go deleted file mode 100644 index f2e7e9abd7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ebs.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSEC2Instance_Ebs AWS CloudFormation Resource (AWS::EC2::Instance.Ebs) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html -type AWSEC2Instance_Ebs struct { - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-deleteontermination - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-iops - Iops int `json:"Iops,omitempty"` - - // SnapshotId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-snapshotid - SnapshotId string `json:"SnapshotId,omitempty"` - - // VolumeSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-volumesize - VolumeSize int `json:"VolumeSize,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-blockdev-template.html#cfn-ec2-blockdev-template-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_Ebs) AWSCloudFormationType() string { - return "AWS::EC2::Instance.Ebs" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_elasticgpuspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_elasticgpuspecification.go deleted file mode 100644 index 893a48cd0e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_elasticgpuspecification.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2Instance_ElasticGpuSpecification AWS CloudFormation Resource (AWS::EC2::Instance.ElasticGpuSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticgpuspecification.html -type AWSEC2Instance_ElasticGpuSpecification struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-elasticgpuspecification.html#cfn-ec2-instance-elasticgpuspecification-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_ElasticGpuSpecification) AWSCloudFormationType() string { - return "AWS::EC2::Instance.ElasticGpuSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_instanceipv6address.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_instanceipv6address.go deleted file mode 100644 index 9540847143..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_instanceipv6address.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2Instance_InstanceIpv6Address AWS CloudFormation Resource (AWS::EC2::Instance.InstanceIpv6Address) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html -type AWSEC2Instance_InstanceIpv6Address struct { - - // Ipv6Address AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-instanceipv6address.html#cfn-ec2-instance-instanceipv6address-ipv6address - Ipv6Address string `json:"Ipv6Address,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_InstanceIpv6Address) AWSCloudFormationType() string { - return "AWS::EC2::Instance.InstanceIpv6Address" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_networkinterface.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_networkinterface.go deleted file mode 100644 index 0ebfc6968e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_networkinterface.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSEC2Instance_NetworkInterface AWS CloudFormation Resource (AWS::EC2::Instance.NetworkInterface) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html -type AWSEC2Instance_NetworkInterface struct { - - // AssociatePublicIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-associatepubip - AssociatePublicIpAddress bool `json:"AssociatePublicIpAddress,omitempty"` - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-delete - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-description - Description string `json:"Description,omitempty"` - - // DeviceIndex AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-deviceindex - DeviceIndex string `json:"DeviceIndex,omitempty"` - - // GroupSet AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-groupset - GroupSet []string `json:"GroupSet,omitempty"` - - // Ipv6AddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#cfn-ec2-instance-networkinterface-ipv6addresscount - Ipv6AddressCount int `json:"Ipv6AddressCount,omitempty"` - - // Ipv6Addresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#cfn-ec2-instance-networkinterface-ipv6addresses - Ipv6Addresses []AWSEC2Instance_InstanceIpv6Address `json:"Ipv6Addresses,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-network-iface - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` - - // PrivateIpAddresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-privateipaddresses - PrivateIpAddresses []AWSEC2Instance_PrivateIpAddressSpecification `json:"PrivateIpAddresses,omitempty"` - - // SecondaryPrivateIpAddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-secondprivateip - SecondaryPrivateIpAddressCount int `json:"SecondaryPrivateIpAddressCount,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-iface-embedded.html#aws-properties-ec2-network-iface-embedded-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_NetworkInterface) AWSCloudFormationType() string { - return "AWS::EC2::Instance.NetworkInterface" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_nodevice.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_nodevice.go deleted file mode 100644 index 83e8a00b0c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_nodevice.go +++ /dev/null @@ -1,11 +0,0 @@ -package cloudformation - -// AWSEC2Instance_NoDevice AWS CloudFormation Resource (AWS::EC2::Instance.NoDevice) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-nodevice.html -type AWSEC2Instance_NoDevice struct { -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_NoDevice) AWSCloudFormationType() string { - return "AWS::EC2::Instance.NoDevice" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_privateipaddressspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_privateipaddressspecification.go deleted file mode 100644 index 60e9f3e16e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_privateipaddressspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2Instance_PrivateIpAddressSpecification AWS CloudFormation Resource (AWS::EC2::Instance.PrivateIpAddressSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html -type AWSEC2Instance_PrivateIpAddressSpecification struct { - - // Primary AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary - Primary bool `json:"Primary,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_PrivateIpAddressSpecification) AWSCloudFormationType() string { - return "AWS::EC2::Instance.PrivateIpAddressSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ssmassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ssmassociation.go deleted file mode 100644 index 4dc82484a1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_ssmassociation.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2Instance_SsmAssociation AWS CloudFormation Resource (AWS::EC2::Instance.SsmAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html -type AWSEC2Instance_SsmAssociation struct { - - // AssociationParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html#cfn-ec2-instance-ssmassociations-associationparameters - AssociationParameters []AWSEC2Instance_AssociationParameter `json:"AssociationParameters,omitempty"` - - // DocumentName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-instance-ssmassociations.html#cfn-ec2-instance-ssmassociations-documentname - DocumentName string `json:"DocumentName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_SsmAssociation) AWSCloudFormationType() string { - return "AWS::EC2::Instance.SsmAssociation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_volume.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_volume.go deleted file mode 100644 index ea5a399b08..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-instance_volume.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2Instance_Volume AWS CloudFormation Resource (AWS::EC2::Instance.Volume) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html -type AWSEC2Instance_Volume struct { - - // Device AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html#cfn-ec2-mountpoint-device - Device string `json:"Device,omitempty"` - - // VolumeId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-mount-point.html#cfn-ec2-mountpoint-volumeid - VolumeId string `json:"VolumeId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Instance_Volume) AWSCloudFormationType() string { - return "AWS::EC2::Instance.Volume" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-internetgateway.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-internetgateway.go deleted file mode 100644 index ac083042b0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-internetgateway.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2InternetGateway AWS CloudFormation Resource (AWS::EC2::InternetGateway) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html -type AWSEC2InternetGateway struct { - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internetgateway.html#cfn-ec2-internetgateway-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2InternetGateway) AWSCloudFormationType() string { - return "AWS::EC2::InternetGateway" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2InternetGateway) MarshalJSON() ([]byte, error) { - type Properties AWSEC2InternetGateway - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2InternetGateway) UnmarshalJSON(b []byte) error { - type Properties AWSEC2InternetGateway - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2InternetGateway(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2InternetGatewayResources retrieves all AWSEC2InternetGateway items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2InternetGatewayResources() map[string]AWSEC2InternetGateway { - results := map[string]AWSEC2InternetGateway{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2InternetGateway: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::InternetGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2InternetGateway - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2InternetGatewayWithName retrieves all AWSEC2InternetGateway items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2InternetGatewayWithName(name string) (AWSEC2InternetGateway, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2InternetGateway: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::InternetGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2InternetGateway - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2InternetGateway{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-natgateway.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-natgateway.go deleted file mode 100644 index b416b519e3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-natgateway.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NatGateway AWS CloudFormation Resource (AWS::EC2::NatGateway) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html -type AWSEC2NatGateway struct { - - // AllocationId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-allocationid - AllocationId string `json:"AllocationId,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-subnetid - SubnetId string `json:"SubnetId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-natgateway.html#cfn-ec2-natgateway-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NatGateway) AWSCloudFormationType() string { - return "AWS::EC2::NatGateway" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NatGateway) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NatGateway - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NatGateway) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NatGateway - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NatGateway(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NatGatewayResources retrieves all AWSEC2NatGateway items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NatGatewayResources() map[string]AWSEC2NatGateway { - results := map[string]AWSEC2NatGateway{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NatGateway: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NatGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NatGateway - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NatGatewayWithName retrieves all AWSEC2NatGateway items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NatGatewayWithName(name string) (AWSEC2NatGateway, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NatGateway: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NatGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NatGateway - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NatGateway{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkacl.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkacl.go deleted file mode 100644 index 9b3bdf0c71..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkacl.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NetworkAcl AWS CloudFormation Resource (AWS::EC2::NetworkAcl) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html -type AWSEC2NetworkAcl struct { - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl.html#cfn-ec2-networkacl-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkAcl) AWSCloudFormationType() string { - return "AWS::EC2::NetworkAcl" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NetworkAcl) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NetworkAcl - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NetworkAcl) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NetworkAcl - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NetworkAcl(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NetworkAclResources retrieves all AWSEC2NetworkAcl items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NetworkAclResources() map[string]AWSEC2NetworkAcl { - results := map[string]AWSEC2NetworkAcl{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NetworkAcl: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkAcl" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkAcl - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NetworkAclWithName retrieves all AWSEC2NetworkAcl items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NetworkAclWithName(name string) (AWSEC2NetworkAcl, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NetworkAcl: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkAcl" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkAcl - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NetworkAcl{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry.go deleted file mode 100644 index 2170e60607..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NetworkAclEntry AWS CloudFormation Resource (AWS::EC2::NetworkAclEntry) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html -type AWSEC2NetworkAclEntry struct { - - // CidrBlock AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-cidrblock - CidrBlock string `json:"CidrBlock,omitempty"` - - // Egress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-egress - Egress bool `json:"Egress,omitempty"` - - // Icmp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-icmp - Icmp *AWSEC2NetworkAclEntry_Icmp `json:"Icmp,omitempty"` - - // Ipv6CidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ipv6cidrblock - Ipv6CidrBlock string `json:"Ipv6CidrBlock,omitempty"` - - // NetworkAclId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-networkaclid - NetworkAclId string `json:"NetworkAclId,omitempty"` - - // PortRange AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-portrange - PortRange *AWSEC2NetworkAclEntry_PortRange `json:"PortRange,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-protocol - Protocol int `json:"Protocol,omitempty"` - - // RuleAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-ruleaction - RuleAction string `json:"RuleAction,omitempty"` - - // RuleNumber AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-acl-entry.html#cfn-ec2-networkaclentry-rulenumber - RuleNumber int `json:"RuleNumber,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkAclEntry) AWSCloudFormationType() string { - return "AWS::EC2::NetworkAclEntry" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NetworkAclEntry) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NetworkAclEntry - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NetworkAclEntry) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NetworkAclEntry - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NetworkAclEntry(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NetworkAclEntryResources retrieves all AWSEC2NetworkAclEntry items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NetworkAclEntryResources() map[string]AWSEC2NetworkAclEntry { - results := map[string]AWSEC2NetworkAclEntry{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NetworkAclEntry: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkAclEntry" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkAclEntry - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NetworkAclEntryWithName retrieves all AWSEC2NetworkAclEntry items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NetworkAclEntryWithName(name string) (AWSEC2NetworkAclEntry, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NetworkAclEntry: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkAclEntry" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkAclEntry - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NetworkAclEntry{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_icmp.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_icmp.go deleted file mode 100644 index 99e386f7bf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_icmp.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2NetworkAclEntry_Icmp AWS CloudFormation Resource (AWS::EC2::NetworkAclEntry.Icmp) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html -type AWSEC2NetworkAclEntry_Icmp struct { - - // Code AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html#cfn-ec2-networkaclentry-icmp-code - Code int `json:"Code,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-icmp.html#cfn-ec2-networkaclentry-icmp-type - Type int `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkAclEntry_Icmp) AWSCloudFormationType() string { - return "AWS::EC2::NetworkAclEntry.Icmp" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_portrange.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_portrange.go deleted file mode 100644 index ec5f33247d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkaclentry_portrange.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2NetworkAclEntry_PortRange AWS CloudFormation Resource (AWS::EC2::NetworkAclEntry.PortRange) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html -type AWSEC2NetworkAclEntry_PortRange struct { - - // From AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html#cfn-ec2-networkaclentry-portrange-from - From int `json:"From,omitempty"` - - // To AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkaclentry-portrange.html#cfn-ec2-networkaclentry-portrange-to - To int `json:"To,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkAclEntry_PortRange) AWSCloudFormationType() string { - return "AWS::EC2::NetworkAclEntry.PortRange" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface.go deleted file mode 100644 index fa0b03d5d8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NetworkInterface AWS CloudFormation Resource (AWS::EC2::NetworkInterface) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html -type AWSEC2NetworkInterface struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-description - Description string `json:"Description,omitempty"` - - // GroupSet AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-groupset - GroupSet []string `json:"GroupSet,omitempty"` - - // InterfaceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-interfacetype - InterfaceType string `json:"InterfaceType,omitempty"` - - // Ipv6AddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresscount - Ipv6AddressCount int `json:"Ipv6AddressCount,omitempty"` - - // Ipv6Addresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-ec2-networkinterface-ipv6addresses - Ipv6Addresses *AWSEC2NetworkInterface_InstanceIpv6Address `json:"Ipv6Addresses,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` - - // PrivateIpAddresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-privateipaddresses - PrivateIpAddresses []AWSEC2NetworkInterface_PrivateIpAddressSpecification `json:"PrivateIpAddresses,omitempty"` - - // SecondaryPrivateIpAddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-secondaryprivateipcount - SecondaryPrivateIpAddressCount int `json:"SecondaryPrivateIpAddressCount,omitempty"` - - // SourceDestCheck AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-sourcedestcheck - SourceDestCheck bool `json:"SourceDestCheck,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-subnetid - SubnetId string `json:"SubnetId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface.html#cfn-awsec2networkinterface-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkInterface) AWSCloudFormationType() string { - return "AWS::EC2::NetworkInterface" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NetworkInterface) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NetworkInterface - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NetworkInterface) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NetworkInterface - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NetworkInterface(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NetworkInterfaceResources retrieves all AWSEC2NetworkInterface items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NetworkInterfaceResources() map[string]AWSEC2NetworkInterface { - results := map[string]AWSEC2NetworkInterface{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NetworkInterface: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterface" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterface - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NetworkInterfaceWithName retrieves all AWSEC2NetworkInterface items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NetworkInterfaceWithName(name string) (AWSEC2NetworkInterface, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NetworkInterface: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterface" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterface - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NetworkInterface{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_instanceipv6address.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_instanceipv6address.go deleted file mode 100644 index 1d7c07da09..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_instanceipv6address.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2NetworkInterface_InstanceIpv6Address AWS CloudFormation Resource (AWS::EC2::NetworkInterface.InstanceIpv6Address) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkinterface-instanceipv6address.html -type AWSEC2NetworkInterface_InstanceIpv6Address struct { - - // Ipv6Address AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-networkinterface-instanceipv6address.html#cfn-ec2-networkinterface-instanceipv6address-ipv6address - Ipv6Address string `json:"Ipv6Address,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkInterface_InstanceIpv6Address) AWSCloudFormationType() string { - return "AWS::EC2::NetworkInterface.InstanceIpv6Address" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_privateipaddressspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_privateipaddressspecification.go deleted file mode 100644 index ae9d2f451f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterface_privateipaddressspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2NetworkInterface_PrivateIpAddressSpecification AWS CloudFormation Resource (AWS::EC2::NetworkInterface.PrivateIpAddressSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html -type AWSEC2NetworkInterface_PrivateIpAddressSpecification struct { - - // Primary AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary - Primary bool `json:"Primary,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkInterface_PrivateIpAddressSpecification) AWSCloudFormationType() string { - return "AWS::EC2::NetworkInterface.PrivateIpAddressSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfaceattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfaceattachment.go deleted file mode 100644 index 9ded9d8b66..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfaceattachment.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NetworkInterfaceAttachment AWS CloudFormation Resource (AWS::EC2::NetworkInterfaceAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html -type AWSEC2NetworkInterfaceAttachment struct { - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deleteonterm - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // DeviceIndex AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-deviceindex - DeviceIndex string `json:"DeviceIndex,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-network-interface-attachment.html#cfn-ec2-network-interface-attachment-networkinterfaceid - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkInterfaceAttachment) AWSCloudFormationType() string { - return "AWS::EC2::NetworkInterfaceAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NetworkInterfaceAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NetworkInterfaceAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NetworkInterfaceAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NetworkInterfaceAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NetworkInterfaceAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NetworkInterfaceAttachmentResources retrieves all AWSEC2NetworkInterfaceAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NetworkInterfaceAttachmentResources() map[string]AWSEC2NetworkInterfaceAttachment { - results := map[string]AWSEC2NetworkInterfaceAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NetworkInterfaceAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterfaceAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterfaceAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NetworkInterfaceAttachmentWithName retrieves all AWSEC2NetworkInterfaceAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NetworkInterfaceAttachmentWithName(name string) (AWSEC2NetworkInterfaceAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NetworkInterfaceAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterfaceAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterfaceAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NetworkInterfaceAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfacepermission.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfacepermission.go deleted file mode 100644 index a04fa1efac..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-networkinterfacepermission.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2NetworkInterfacePermission AWS CloudFormation Resource (AWS::EC2::NetworkInterfacePermission) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html -type AWSEC2NetworkInterfacePermission struct { - - // AwsAccountId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-awsaccountid - AwsAccountId string `json:"AwsAccountId,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-networkinterfaceid - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` - - // Permission AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-networkinterfacepermission.html#cfn-ec2-networkinterfacepermission-permission - Permission string `json:"Permission,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2NetworkInterfacePermission) AWSCloudFormationType() string { - return "AWS::EC2::NetworkInterfacePermission" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2NetworkInterfacePermission) MarshalJSON() ([]byte, error) { - type Properties AWSEC2NetworkInterfacePermission - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2NetworkInterfacePermission) UnmarshalJSON(b []byte) error { - type Properties AWSEC2NetworkInterfacePermission - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2NetworkInterfacePermission(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2NetworkInterfacePermissionResources retrieves all AWSEC2NetworkInterfacePermission items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2NetworkInterfacePermissionResources() map[string]AWSEC2NetworkInterfacePermission { - results := map[string]AWSEC2NetworkInterfacePermission{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2NetworkInterfacePermission: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterfacePermission" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterfacePermission - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2NetworkInterfacePermissionWithName retrieves all AWSEC2NetworkInterfacePermission items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2NetworkInterfacePermissionWithName(name string) (AWSEC2NetworkInterfacePermission, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2NetworkInterfacePermission: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::NetworkInterfacePermission" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2NetworkInterfacePermission - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2NetworkInterfacePermission{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-placementgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-placementgroup.go deleted file mode 100644 index 1c5144d7a2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-placementgroup.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2PlacementGroup AWS CloudFormation Resource (AWS::EC2::PlacementGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html -type AWSEC2PlacementGroup struct { - - // Strategy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-placementgroup.html#cfn-ec2-placementgroup-strategy - Strategy string `json:"Strategy,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2PlacementGroup) AWSCloudFormationType() string { - return "AWS::EC2::PlacementGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2PlacementGroup) MarshalJSON() ([]byte, error) { - type Properties AWSEC2PlacementGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2PlacementGroup) UnmarshalJSON(b []byte) error { - type Properties AWSEC2PlacementGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2PlacementGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2PlacementGroupResources retrieves all AWSEC2PlacementGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2PlacementGroupResources() map[string]AWSEC2PlacementGroup { - results := map[string]AWSEC2PlacementGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2PlacementGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::PlacementGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2PlacementGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2PlacementGroupWithName retrieves all AWSEC2PlacementGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2PlacementGroupWithName(name string) (AWSEC2PlacementGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2PlacementGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::PlacementGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2PlacementGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2PlacementGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-route.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-route.go deleted file mode 100644 index 20ea56f44a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-route.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2Route AWS CloudFormation Resource (AWS::EC2::Route) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html -type AWSEC2Route struct { - - // DestinationCidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationcidrblock - DestinationCidrBlock string `json:"DestinationCidrBlock,omitempty"` - - // DestinationIpv6CidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-destinationipv6cidrblock - DestinationIpv6CidrBlock string `json:"DestinationIpv6CidrBlock,omitempty"` - - // EgressOnlyInternetGatewayId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-egressonlyinternetgatewayid - EgressOnlyInternetGatewayId string `json:"EgressOnlyInternetGatewayId,omitempty"` - - // GatewayId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-gatewayid - GatewayId string `json:"GatewayId,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // NatGatewayId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-natgatewayid - NatGatewayId string `json:"NatGatewayId,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-networkinterfaceid - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` - - // RouteTableId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-routetableid - RouteTableId string `json:"RouteTableId,omitempty"` - - // VpcPeeringConnectionId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route.html#cfn-ec2-route-vpcpeeringconnectionid - VpcPeeringConnectionId string `json:"VpcPeeringConnectionId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Route) AWSCloudFormationType() string { - return "AWS::EC2::Route" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2Route) MarshalJSON() ([]byte, error) { - type Properties AWSEC2Route - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2Route) UnmarshalJSON(b []byte) error { - type Properties AWSEC2Route - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2Route(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2RouteResources retrieves all AWSEC2Route items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2RouteResources() map[string]AWSEC2Route { - results := map[string]AWSEC2Route{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2Route: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Route" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Route - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2RouteWithName retrieves all AWSEC2Route items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2RouteWithName(name string) (AWSEC2Route, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2Route: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Route" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Route - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2Route{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-routetable.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-routetable.go deleted file mode 100644 index 0631257de8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-routetable.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2RouteTable AWS CloudFormation Resource (AWS::EC2::RouteTable) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html -type AWSEC2RouteTable struct { - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-route-table.html#cfn-ec2-routetable-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2RouteTable) AWSCloudFormationType() string { - return "AWS::EC2::RouteTable" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2RouteTable) MarshalJSON() ([]byte, error) { - type Properties AWSEC2RouteTable - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2RouteTable) UnmarshalJSON(b []byte) error { - type Properties AWSEC2RouteTable - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2RouteTable(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2RouteTableResources retrieves all AWSEC2RouteTable items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2RouteTableResources() map[string]AWSEC2RouteTable { - results := map[string]AWSEC2RouteTable{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2RouteTable: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::RouteTable" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2RouteTable - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2RouteTableWithName retrieves all AWSEC2RouteTable items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2RouteTableWithName(name string) (AWSEC2RouteTable, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2RouteTable: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::RouteTable" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2RouteTable - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2RouteTable{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup.go deleted file mode 100644 index 882da21a4d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SecurityGroup AWS CloudFormation Resource (AWS::EC2::SecurityGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html -type AWSEC2SecurityGroup struct { - - // GroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupdescription - GroupDescription string `json:"GroupDescription,omitempty"` - - // GroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-groupname - GroupName string `json:"GroupName,omitempty"` - - // SecurityGroupEgress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupegress - SecurityGroupEgress []AWSEC2SecurityGroup_Egress `json:"SecurityGroupEgress,omitempty"` - - // SecurityGroupIngress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-securitygroupingress - SecurityGroupIngress []AWSEC2SecurityGroup_Ingress `json:"SecurityGroupIngress,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group.html#cfn-ec2-securitygroup-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SecurityGroup) AWSCloudFormationType() string { - return "AWS::EC2::SecurityGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SecurityGroup) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SecurityGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SecurityGroup) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SecurityGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SecurityGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SecurityGroupResources retrieves all AWSEC2SecurityGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SecurityGroupResources() map[string]AWSEC2SecurityGroup { - results := map[string]AWSEC2SecurityGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SecurityGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SecurityGroupWithName retrieves all AWSEC2SecurityGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SecurityGroupWithName(name string) (AWSEC2SecurityGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SecurityGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SecurityGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_egress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_egress.go deleted file mode 100644 index 1a30ab439d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_egress.go +++ /dev/null @@ -1,51 +0,0 @@ -package cloudformation - -// AWSEC2SecurityGroup_Egress AWS CloudFormation Resource (AWS::EC2::SecurityGroup.Egress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html -type AWSEC2SecurityGroup_Egress struct { - - // CidrIp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidrip - CidrIp string `json:"CidrIp,omitempty"` - - // CidrIpv6 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidripv6 - CidrIpv6 string `json:"CidrIpv6,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-description - Description string `json:"Description,omitempty"` - - // DestinationPrefixListId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-destinationprefixlistid - DestinationPrefixListId string `json:"DestinationPrefixListId,omitempty"` - - // DestinationSecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-destsecgroupid - DestinationSecurityGroupId string `json:"DestinationSecurityGroupId,omitempty"` - - // FromPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-fromport - FromPort int `json:"FromPort,omitempty"` - - // IpProtocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-ipprotocol - IpProtocol string `json:"IpProtocol,omitempty"` - - // ToPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-toport - ToPort int `json:"ToPort,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SecurityGroup_Egress) AWSCloudFormationType() string { - return "AWS::EC2::SecurityGroup.Egress" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_ingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_ingress.go deleted file mode 100644 index f6d2c2ca04..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroup_ingress.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSEC2SecurityGroup_Ingress AWS CloudFormation Resource (AWS::EC2::SecurityGroup.Ingress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html -type AWSEC2SecurityGroup_Ingress struct { - - // CidrIp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidrip - CidrIp string `json:"CidrIp,omitempty"` - - // CidrIpv6 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-cidripv6 - CidrIpv6 string `json:"CidrIpv6,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-description - Description string `json:"Description,omitempty"` - - // FromPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-fromport - FromPort int `json:"FromPort,omitempty"` - - // IpProtocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-ipprotocol - IpProtocol string `json:"IpProtocol,omitempty"` - - // SourceSecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupid - SourceSecurityGroupId string `json:"SourceSecurityGroupId,omitempty"` - - // SourceSecurityGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupname - SourceSecurityGroupName string `json:"SourceSecurityGroupName,omitempty"` - - // SourceSecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-sourcesecuritygroupownerid - SourceSecurityGroupOwnerId string `json:"SourceSecurityGroupOwnerId,omitempty"` - - // ToPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-rule.html#cfn-ec2-security-group-rule-toport - ToPort int `json:"ToPort,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SecurityGroup_Ingress) AWSCloudFormationType() string { - return "AWS::EC2::SecurityGroup.Ingress" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupegress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupegress.go deleted file mode 100644 index 2f50ba602c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupegress.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SecurityGroupEgress AWS CloudFormation Resource (AWS::EC2::SecurityGroupEgress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html -type AWSEC2SecurityGroupEgress struct { - - // CidrIp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidrip - CidrIp string `json:"CidrIp,omitempty"` - - // CidrIpv6 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-cidripv6 - CidrIpv6 string `json:"CidrIpv6,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-description - Description string `json:"Description,omitempty"` - - // DestinationPrefixListId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationprefixlistid - DestinationPrefixListId string `json:"DestinationPrefixListId,omitempty"` - - // DestinationSecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-destinationsecuritygroupid - DestinationSecurityGroupId string `json:"DestinationSecurityGroupId,omitempty"` - - // FromPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-fromport - FromPort int `json:"FromPort,omitempty"` - - // GroupId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-groupid - GroupId string `json:"GroupId,omitempty"` - - // IpProtocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-ipprotocol - IpProtocol string `json:"IpProtocol,omitempty"` - - // ToPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-security-group-egress.html#cfn-ec2-securitygroupegress-toport - ToPort int `json:"ToPort,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SecurityGroupEgress) AWSCloudFormationType() string { - return "AWS::EC2::SecurityGroupEgress" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SecurityGroupEgress) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SecurityGroupEgress - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SecurityGroupEgress) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SecurityGroupEgress - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SecurityGroupEgress(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SecurityGroupEgressResources retrieves all AWSEC2SecurityGroupEgress items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SecurityGroupEgressResources() map[string]AWSEC2SecurityGroupEgress { - results := map[string]AWSEC2SecurityGroupEgress{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SecurityGroupEgress: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroupEgress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroupEgress - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SecurityGroupEgressWithName retrieves all AWSEC2SecurityGroupEgress items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SecurityGroupEgressWithName(name string) (AWSEC2SecurityGroupEgress, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SecurityGroupEgress: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroupEgress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroupEgress - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SecurityGroupEgress{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupingress.go deleted file mode 100644 index f8407f50d6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-securitygroupingress.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SecurityGroupIngress AWS CloudFormation Resource (AWS::EC2::SecurityGroupIngress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html -type AWSEC2SecurityGroupIngress struct { - - // CidrIp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidrip - CidrIp string `json:"CidrIp,omitempty"` - - // CidrIpv6 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-cidripv6 - CidrIpv6 string `json:"CidrIpv6,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-description - Description string `json:"Description,omitempty"` - - // FromPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-fromport - FromPort int `json:"FromPort,omitempty"` - - // GroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupid - GroupId string `json:"GroupId,omitempty"` - - // GroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-groupname - GroupName string `json:"GroupName,omitempty"` - - // IpProtocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-ipprotocol - IpProtocol string `json:"IpProtocol,omitempty"` - - // SourceSecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupid - SourceSecurityGroupId string `json:"SourceSecurityGroupId,omitempty"` - - // SourceSecurityGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupname - SourceSecurityGroupName string `json:"SourceSecurityGroupName,omitempty"` - - // SourceSecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-sourcesecuritygroupownerid - SourceSecurityGroupOwnerId string `json:"SourceSecurityGroupOwnerId,omitempty"` - - // ToPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html#cfn-ec2-security-group-ingress-toport - ToPort int `json:"ToPort,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SecurityGroupIngress) AWSCloudFormationType() string { - return "AWS::EC2::SecurityGroupIngress" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SecurityGroupIngress) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SecurityGroupIngress - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SecurityGroupIngress) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SecurityGroupIngress - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SecurityGroupIngress(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SecurityGroupIngressResources retrieves all AWSEC2SecurityGroupIngress items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SecurityGroupIngressResources() map[string]AWSEC2SecurityGroupIngress { - results := map[string]AWSEC2SecurityGroupIngress{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SecurityGroupIngressWithName retrieves all AWSEC2SecurityGroupIngress items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SecurityGroupIngressWithName(name string) (AWSEC2SecurityGroupIngress, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SecurityGroupIngress{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet.go deleted file mode 100644 index cfe8862554..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SpotFleet AWS CloudFormation Resource (AWS::EC2::SpotFleet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html -type AWSEC2SpotFleet struct { - - // SpotFleetRequestConfigData AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-spotfleet.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata - SpotFleetRequestConfigData *AWSEC2SpotFleet_SpotFleetRequestConfigData `json:"SpotFleetRequestConfigData,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SpotFleet) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SpotFleet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SpotFleet) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SpotFleet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SpotFleet(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SpotFleetResources retrieves all AWSEC2SpotFleet items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SpotFleetResources() map[string]AWSEC2SpotFleet { - results := map[string]AWSEC2SpotFleet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SpotFleet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SpotFleet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SpotFleet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SpotFleetWithName retrieves all AWSEC2SpotFleet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SpotFleetWithName(name string) (AWSEC2SpotFleet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SpotFleet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SpotFleet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SpotFleet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SpotFleet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_blockdevicemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_blockdevicemapping.go deleted file mode 100644 index 30f32fb03a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_blockdevicemapping.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_BlockDeviceMapping AWS CloudFormation Resource (AWS::EC2::SpotFleet.BlockDeviceMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html -type AWSEC2SpotFleet_BlockDeviceMapping struct { - - // DeviceName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-devicename - DeviceName string `json:"DeviceName,omitempty"` - - // Ebs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-ebs - Ebs *AWSEC2SpotFleet_EbsBlockDevice `json:"Ebs,omitempty"` - - // NoDevice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-nodevice - NoDevice string `json:"NoDevice,omitempty"` - - // VirtualName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings.html#cfn-ec2-spotfleet-blockdevicemapping-virtualname - VirtualName string `json:"VirtualName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_BlockDeviceMapping) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.BlockDeviceMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_ebsblockdevice.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_ebsblockdevice.go deleted file mode 100644 index 5251560fc2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_ebsblockdevice.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_EbsBlockDevice AWS CloudFormation Resource (AWS::EC2::SpotFleet.EbsBlockDevice) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html -type AWSEC2SpotFleet_EbsBlockDevice struct { - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-deleteontermination - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-iops - Iops int `json:"Iops,omitempty"` - - // SnapshotId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-snapshotid - SnapshotId string `json:"SnapshotId,omitempty"` - - // VolumeSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-volumesize - VolumeSize int `json:"VolumeSize,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-blockdevicemappings-ebs.html#cfn-ec2-spotfleet-ebsblockdevice-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_EbsBlockDevice) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.EbsBlockDevice" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_groupidentifier.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_groupidentifier.go deleted file mode 100644 index be177fe558..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_groupidentifier.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_GroupIdentifier AWS CloudFormation Resource (AWS::EC2::SpotFleet.GroupIdentifier) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html -type AWSEC2SpotFleet_GroupIdentifier struct { - - // GroupId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html#cfn-ec2-spotfleet-groupidentifier-groupid - GroupId string `json:"GroupId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_GroupIdentifier) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.GroupIdentifier" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_iaminstanceprofilespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_iaminstanceprofilespecification.go deleted file mode 100644 index 7fc2daf9fe..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_iaminstanceprofilespecification.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_IamInstanceProfileSpecification AWS CloudFormation Resource (AWS::EC2::SpotFleet.IamInstanceProfileSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-iaminstanceprofile.html -type AWSEC2SpotFleet_IamInstanceProfileSpecification struct { - - // Arn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-iaminstanceprofile.html#cfn-ec2-spotfleet-iaminstanceprofilespecification-arn - Arn string `json:"Arn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_IamInstanceProfileSpecification) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.IamInstanceProfileSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instanceipv6address.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instanceipv6address.go deleted file mode 100644 index 85f4676552..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instanceipv6address.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_InstanceIpv6Address AWS CloudFormation Resource (AWS::EC2::SpotFleet.InstanceIpv6Address) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-instanceipv6address.html -type AWSEC2SpotFleet_InstanceIpv6Address struct { - - // Ipv6Address AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-instanceipv6address.html#cfn-ec2-spotfleet-instanceipv6address-ipv6address - Ipv6Address string `json:"Ipv6Address,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_InstanceIpv6Address) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.InstanceIpv6Address" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instancenetworkinterfacespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instancenetworkinterfacespecification.go deleted file mode 100644 index 2f86c7af4c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_instancenetworkinterfacespecification.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_InstanceNetworkInterfaceSpecification AWS CloudFormation Resource (AWS::EC2::SpotFleet.InstanceNetworkInterfaceSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html -type AWSEC2SpotFleet_InstanceNetworkInterfaceSpecification struct { - - // AssociatePublicIpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-associatepublicipaddress - AssociatePublicIpAddress bool `json:"AssociatePublicIpAddress,omitempty"` - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-deleteontermination - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-description - Description string `json:"Description,omitempty"` - - // DeviceIndex AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-deviceindex - DeviceIndex int `json:"DeviceIndex,omitempty"` - - // Groups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-groups - Groups []string `json:"Groups,omitempty"` - - // Ipv6AddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-ipv6addresscount - Ipv6AddressCount int `json:"Ipv6AddressCount,omitempty"` - - // Ipv6Addresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-ipv6addresses - Ipv6Addresses []AWSEC2SpotFleet_InstanceIpv6Address `json:"Ipv6Addresses,omitempty"` - - // NetworkInterfaceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-networkinterfaceid - NetworkInterfaceId string `json:"NetworkInterfaceId,omitempty"` - - // PrivateIpAddresses AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-privateipaddresses - PrivateIpAddresses []AWSEC2SpotFleet_PrivateIpAddressSpecification `json:"PrivateIpAddresses,omitempty"` - - // SecondaryPrivateIpAddressCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-secondaryprivateipaddresscount - SecondaryPrivateIpAddressCount int `json:"SecondaryPrivateIpAddressCount,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces.html#cfn-ec2-spotfleet-instancenetworkinterfacespecification-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_InstanceNetworkInterfaceSpecification) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.InstanceNetworkInterfaceSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_privateipaddressspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_privateipaddressspecification.go deleted file mode 100644 index b232be7dde..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_privateipaddressspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_PrivateIpAddressSpecification AWS CloudFormation Resource (AWS::EC2::SpotFleet.PrivateIpAddressSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html -type AWSEC2SpotFleet_PrivateIpAddressSpecification struct { - - // Primary AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html#cfn-ec2-spotfleet-privateipaddressspecification-primary - Primary bool `json:"Primary,omitempty"` - - // PrivateIpAddress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-networkinterfaces-privateipaddresses.html#cfn-ec2-spotfleet-privateipaddressspecification-privateipaddress - PrivateIpAddress string `json:"PrivateIpAddress,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_PrivateIpAddressSpecification) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.PrivateIpAddressSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetlaunchspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetlaunchspecification.go deleted file mode 100644 index 82e4049573..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetlaunchspecification.go +++ /dev/null @@ -1,91 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_SpotFleetLaunchSpecification AWS CloudFormation Resource (AWS::EC2::SpotFleet.SpotFleetLaunchSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html -type AWSEC2SpotFleet_SpotFleetLaunchSpecification struct { - - // BlockDeviceMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-blockdevicemappings - BlockDeviceMappings []AWSEC2SpotFleet_BlockDeviceMapping `json:"BlockDeviceMappings,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` - - // IamInstanceProfile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-iaminstanceprofile - IamInstanceProfile *AWSEC2SpotFleet_IamInstanceProfileSpecification `json:"IamInstanceProfile,omitempty"` - - // ImageId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-imageid - ImageId string `json:"ImageId,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // KernelId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-kernelid - KernelId string `json:"KernelId,omitempty"` - - // KeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-keyname - KeyName string `json:"KeyName,omitempty"` - - // Monitoring AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-monitoring - Monitoring *AWSEC2SpotFleet_SpotFleetMonitoring `json:"Monitoring,omitempty"` - - // NetworkInterfaces AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-networkinterfaces - NetworkInterfaces []AWSEC2SpotFleet_InstanceNetworkInterfaceSpecification `json:"NetworkInterfaces,omitempty"` - - // Placement AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-placement - Placement *AWSEC2SpotFleet_SpotPlacement `json:"Placement,omitempty"` - - // RamdiskId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-ramdiskid - RamdiskId string `json:"RamdiskId,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-securitygroups - SecurityGroups []AWSEC2SpotFleet_GroupIdentifier `json:"SecurityGroups,omitempty"` - - // SpotPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-spotprice - SpotPrice string `json:"SpotPrice,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-subnetid - SubnetId string `json:"SubnetId,omitempty"` - - // UserData AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-userdata - UserData string `json:"UserData,omitempty"` - - // WeightedCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications.html#cfn-ec2-spotfleet-spotfleetlaunchspecification-weightedcapacity - WeightedCapacity float64 `json:"WeightedCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_SpotFleetLaunchSpecification) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.SpotFleetLaunchSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetmonitoring.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetmonitoring.go deleted file mode 100644 index 0989ca6d59..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetmonitoring.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_SpotFleetMonitoring AWS CloudFormation Resource (AWS::EC2::SpotFleet.SpotFleetMonitoring) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-monitoring.html -type AWSEC2SpotFleet_SpotFleetMonitoring struct { - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-monitoring.html#cfn-ec2-spotfleet-spotfleetmonitoring-enabled - Enabled bool `json:"Enabled,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_SpotFleetMonitoring) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.SpotFleetMonitoring" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetrequestconfigdata.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetrequestconfigdata.go deleted file mode 100644 index 169c5927d6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotfleetrequestconfigdata.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_SpotFleetRequestConfigData AWS CloudFormation Resource (AWS::EC2::SpotFleet.SpotFleetRequestConfigData) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html -type AWSEC2SpotFleet_SpotFleetRequestConfigData struct { - - // AllocationStrategy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-allocationstrategy - AllocationStrategy string `json:"AllocationStrategy,omitempty"` - - // ExcessCapacityTerminationPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-excesscapacityterminationpolicy - ExcessCapacityTerminationPolicy string `json:"ExcessCapacityTerminationPolicy,omitempty"` - - // IamFleetRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-iamfleetrole - IamFleetRole string `json:"IamFleetRole,omitempty"` - - // LaunchSpecifications AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications - LaunchSpecifications []AWSEC2SpotFleet_SpotFleetLaunchSpecification `json:"LaunchSpecifications,omitempty"` - - // ReplaceUnhealthyInstances AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-replaceunhealthyinstances - ReplaceUnhealthyInstances bool `json:"ReplaceUnhealthyInstances,omitempty"` - - // SpotPrice AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-spotprice - SpotPrice string `json:"SpotPrice,omitempty"` - - // TargetCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-targetcapacity - TargetCapacity int `json:"TargetCapacity,omitempty"` - - // TerminateInstancesWithExpiration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-terminateinstanceswithexpiration - TerminateInstancesWithExpiration bool `json:"TerminateInstancesWithExpiration,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-type - Type string `json:"Type,omitempty"` - - // ValidFrom AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-validfrom - ValidFrom string `json:"ValidFrom,omitempty"` - - // ValidUntil AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata.html#cfn-ec2-spotfleet-spotfleetrequestconfigdata-validuntil - ValidUntil string `json:"ValidUntil,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_SpotFleetRequestConfigData) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.SpotFleetRequestConfigData" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotplacement.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotplacement.go deleted file mode 100644 index 56d1f33e73..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-spotfleet_spotplacement.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2SpotFleet_SpotPlacement AWS CloudFormation Resource (AWS::EC2::SpotFleet.SpotPlacement) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html -type AWSEC2SpotFleet_SpotPlacement struct { - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // GroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-placement.html#cfn-ec2-spotfleet-spotplacement-groupname - GroupName string `json:"GroupName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SpotFleet_SpotPlacement) AWSCloudFormationType() string { - return "AWS::EC2::SpotFleet.SpotPlacement" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnet.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnet.go deleted file mode 100644 index 499f1caccd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnet.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2Subnet AWS CloudFormation Resource (AWS::EC2::Subnet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html -type AWSEC2Subnet struct { - - // AssignIpv6AddressOnCreation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-assignipv6addressoncreation - AssignIpv6AddressOnCreation bool `json:"AssignIpv6AddressOnCreation,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // CidrBlock AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-cidrblock - CidrBlock string `json:"CidrBlock,omitempty"` - - // Ipv6CidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-ipv6cidrblock - Ipv6CidrBlock string `json:"Ipv6CidrBlock,omitempty"` - - // MapPublicIpOnLaunch AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-mappubliciponlaunch - MapPublicIpOnLaunch bool `json:"MapPublicIpOnLaunch,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-awsec2subnet-prop-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Subnet) AWSCloudFormationType() string { - return "AWS::EC2::Subnet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2Subnet) MarshalJSON() ([]byte, error) { - type Properties AWSEC2Subnet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2Subnet) UnmarshalJSON(b []byte) error { - type Properties AWSEC2Subnet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2Subnet(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SubnetResources retrieves all AWSEC2Subnet items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SubnetResources() map[string]AWSEC2Subnet { - results := map[string]AWSEC2Subnet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2Subnet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Subnet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Subnet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SubnetWithName retrieves all AWSEC2Subnet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SubnetWithName(name string) (AWSEC2Subnet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2Subnet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Subnet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Subnet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2Subnet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetcidrblock.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetcidrblock.go deleted file mode 100644 index d66ca0de67..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetcidrblock.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SubnetCidrBlock AWS CloudFormation Resource (AWS::EC2::SubnetCidrBlock) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html -type AWSEC2SubnetCidrBlock struct { - - // Ipv6CidrBlock AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-ipv6cidrblock - Ipv6CidrBlock string `json:"Ipv6CidrBlock,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnetcidrblock.html#cfn-ec2-subnetcidrblock-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SubnetCidrBlock) AWSCloudFormationType() string { - return "AWS::EC2::SubnetCidrBlock" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SubnetCidrBlock) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SubnetCidrBlock - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SubnetCidrBlock) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SubnetCidrBlock - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SubnetCidrBlock(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SubnetCidrBlockResources retrieves all AWSEC2SubnetCidrBlock items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SubnetCidrBlockResources() map[string]AWSEC2SubnetCidrBlock { - results := map[string]AWSEC2SubnetCidrBlock{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SubnetCidrBlock: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetCidrBlock" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetCidrBlock - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SubnetCidrBlockWithName retrieves all AWSEC2SubnetCidrBlock items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SubnetCidrBlockWithName(name string) (AWSEC2SubnetCidrBlock, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SubnetCidrBlock: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetCidrBlock" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetCidrBlock - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SubnetCidrBlock{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetnetworkaclassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetnetworkaclassociation.go deleted file mode 100644 index 8328707755..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetnetworkaclassociation.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SubnetNetworkAclAssociation AWS CloudFormation Resource (AWS::EC2::SubnetNetworkAclAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html -type AWSEC2SubnetNetworkAclAssociation struct { - - // NetworkAclId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-networkaclid - NetworkAclId string `json:"NetworkAclId,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-network-acl-assoc.html#cfn-ec2-subnetnetworkaclassociation-associationid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SubnetNetworkAclAssociation) AWSCloudFormationType() string { - return "AWS::EC2::SubnetNetworkAclAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SubnetNetworkAclAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SubnetNetworkAclAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SubnetNetworkAclAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SubnetNetworkAclAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SubnetNetworkAclAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SubnetNetworkAclAssociationResources retrieves all AWSEC2SubnetNetworkAclAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SubnetNetworkAclAssociationResources() map[string]AWSEC2SubnetNetworkAclAssociation { - results := map[string]AWSEC2SubnetNetworkAclAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SubnetNetworkAclAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetNetworkAclAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetNetworkAclAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SubnetNetworkAclAssociationWithName retrieves all AWSEC2SubnetNetworkAclAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SubnetNetworkAclAssociationWithName(name string) (AWSEC2SubnetNetworkAclAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SubnetNetworkAclAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetNetworkAclAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetNetworkAclAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SubnetNetworkAclAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetroutetableassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetroutetableassociation.go deleted file mode 100644 index 0daa72a50d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-subnetroutetableassociation.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2SubnetRouteTableAssociation AWS CloudFormation Resource (AWS::EC2::SubnetRouteTableAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html -type AWSEC2SubnetRouteTableAssociation struct { - - // RouteTableId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-routetableid - RouteTableId string `json:"RouteTableId,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet-route-table-assoc.html#cfn-ec2-subnetroutetableassociation-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2SubnetRouteTableAssociation) AWSCloudFormationType() string { - return "AWS::EC2::SubnetRouteTableAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2SubnetRouteTableAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2SubnetRouteTableAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2SubnetRouteTableAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2SubnetRouteTableAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2SubnetRouteTableAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2SubnetRouteTableAssociationResources retrieves all AWSEC2SubnetRouteTableAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2SubnetRouteTableAssociationResources() map[string]AWSEC2SubnetRouteTableAssociation { - results := map[string]AWSEC2SubnetRouteTableAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2SubnetRouteTableAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetRouteTableAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetRouteTableAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2SubnetRouteTableAssociationWithName retrieves all AWSEC2SubnetRouteTableAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2SubnetRouteTableAssociationWithName(name string) (AWSEC2SubnetRouteTableAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2SubnetRouteTableAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::SubnetRouteTableAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2SubnetRouteTableAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2SubnetRouteTableAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-trunkinterfaceassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-trunkinterfaceassociation.go deleted file mode 100644 index 238cce04fb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-trunkinterfaceassociation.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2TrunkInterfaceAssociation AWS CloudFormation Resource (AWS::EC2::TrunkInterfaceAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trunkinterfaceassociation.html -type AWSEC2TrunkInterfaceAssociation struct { - - // BranchInterfaceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trunkinterfaceassociation.html#cfn-ec2-trunkinterfaceassociation-branchinterfaceid - BranchInterfaceId string `json:"BranchInterfaceId,omitempty"` - - // GREKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trunkinterfaceassociation.html#cfn-ec2-trunkinterfaceassociation-grekey - GREKey int `json:"GREKey,omitempty"` - - // TrunkInterfaceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trunkinterfaceassociation.html#cfn-ec2-trunkinterfaceassociation-trunkinterfaceid - TrunkInterfaceId string `json:"TrunkInterfaceId,omitempty"` - - // VLANId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-trunkinterfaceassociation.html#cfn-ec2-trunkinterfaceassociation-vlanid - VLANId int `json:"VLANId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2TrunkInterfaceAssociation) AWSCloudFormationType() string { - return "AWS::EC2::TrunkInterfaceAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2TrunkInterfaceAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2TrunkInterfaceAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2TrunkInterfaceAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2TrunkInterfaceAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2TrunkInterfaceAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2TrunkInterfaceAssociationResources retrieves all AWSEC2TrunkInterfaceAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2TrunkInterfaceAssociationResources() map[string]AWSEC2TrunkInterfaceAssociation { - results := map[string]AWSEC2TrunkInterfaceAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2TrunkInterfaceAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::TrunkInterfaceAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2TrunkInterfaceAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2TrunkInterfaceAssociationWithName retrieves all AWSEC2TrunkInterfaceAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2TrunkInterfaceAssociationWithName(name string) (AWSEC2TrunkInterfaceAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2TrunkInterfaceAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::TrunkInterfaceAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2TrunkInterfaceAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2TrunkInterfaceAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volume.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volume.go deleted file mode 100644 index 5170cde5cd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volume.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2Volume AWS CloudFormation Resource (AWS::EC2::Volume) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html -type AWSEC2Volume struct { - - // AutoEnableIO AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-autoenableio - AutoEnableIO bool `json:"AutoEnableIO,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-iops - Iops int `json:"Iops,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // Size AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-size - Size int `json:"Size,omitempty"` - - // SnapshotId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-snapshotid - SnapshotId string `json:"SnapshotId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-tags - Tags []Tag `json:"Tags,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volume.html#cfn-ec2-ebs-volume-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2Volume) AWSCloudFormationType() string { - return "AWS::EC2::Volume" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2Volume) MarshalJSON() ([]byte, error) { - type Properties AWSEC2Volume - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2Volume) UnmarshalJSON(b []byte) error { - type Properties AWSEC2Volume - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2Volume(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VolumeResources retrieves all AWSEC2Volume items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VolumeResources() map[string]AWSEC2Volume { - results := map[string]AWSEC2Volume{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2Volume: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Volume" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Volume - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VolumeWithName retrieves all AWSEC2Volume items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VolumeWithName(name string) (AWSEC2Volume, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2Volume: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::Volume" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2Volume - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2Volume{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volumeattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volumeattachment.go deleted file mode 100644 index 62a882a6e6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-volumeattachment.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VolumeAttachment AWS CloudFormation Resource (AWS::EC2::VolumeAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html -type AWSEC2VolumeAttachment struct { - - // Device AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-device - Device string `json:"Device,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // VolumeId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-ebs-volumeattachment.html#cfn-ec2-ebs-volumeattachment-volumeid - VolumeId string `json:"VolumeId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VolumeAttachment) AWSCloudFormationType() string { - return "AWS::EC2::VolumeAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VolumeAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VolumeAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VolumeAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VolumeAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VolumeAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VolumeAttachmentResources retrieves all AWSEC2VolumeAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VolumeAttachmentResources() map[string]AWSEC2VolumeAttachment { - results := map[string]AWSEC2VolumeAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VolumeAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VolumeAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VolumeAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VolumeAttachmentWithName retrieves all AWSEC2VolumeAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VolumeAttachmentWithName(name string) (AWSEC2VolumeAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VolumeAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VolumeAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VolumeAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VolumeAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpc.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpc.go deleted file mode 100644 index 8d6245de2f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpc.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPC AWS CloudFormation Resource (AWS::EC2::VPC) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html -type AWSEC2VPC struct { - - // CidrBlock AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-cidrblock - CidrBlock string `json:"CidrBlock,omitempty"` - - // EnableDnsHostnames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsHostnames - EnableDnsHostnames bool `json:"EnableDnsHostnames,omitempty"` - - // EnableDnsSupport AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-EnableDnsSupport - EnableDnsSupport bool `json:"EnableDnsSupport,omitempty"` - - // InstanceTenancy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-instancetenancy - InstanceTenancy string `json:"InstanceTenancy,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc.html#cfn-aws-ec2-vpc-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPC) AWSCloudFormationType() string { - return "AWS::EC2::VPC" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPC) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPC - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPC) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPC - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPC(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCResources retrieves all AWSEC2VPC items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCResources() map[string]AWSEC2VPC { - results := map[string]AWSEC2VPC{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPC: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPC" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPC - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCWithName retrieves all AWSEC2VPC items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCWithName(name string) (AWSEC2VPC, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPC: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPC" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPC - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPC{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpccidrblock.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpccidrblock.go deleted file mode 100644 index 2b58ea009b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpccidrblock.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPCCidrBlock AWS CloudFormation Resource (AWS::EC2::VPCCidrBlock) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html -type AWSEC2VPCCidrBlock struct { - - // AmazonProvidedIpv6CidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-amazonprovidedipv6cidrblock - AmazonProvidedIpv6CidrBlock bool `json:"AmazonProvidedIpv6CidrBlock,omitempty"` - - // CidrBlock AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-cidrblock - CidrBlock string `json:"CidrBlock,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpccidrblock.html#cfn-ec2-vpccidrblock-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPCCidrBlock) AWSCloudFormationType() string { - return "AWS::EC2::VPCCidrBlock" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPCCidrBlock) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPCCidrBlock - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPCCidrBlock) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPCCidrBlock - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPCCidrBlock(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCCidrBlockResources retrieves all AWSEC2VPCCidrBlock items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCCidrBlockResources() map[string]AWSEC2VPCCidrBlock { - results := map[string]AWSEC2VPCCidrBlock{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPCCidrBlock: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCCidrBlock" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCCidrBlock - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCCidrBlockWithName retrieves all AWSEC2VPCCidrBlock items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCCidrBlockWithName(name string) (AWSEC2VPCCidrBlock, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPCCidrBlock: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCCidrBlock" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCCidrBlock - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPCCidrBlock{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcdhcpoptionsassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcdhcpoptionsassociation.go deleted file mode 100644 index 5b26a28b48..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcdhcpoptionsassociation.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPCDHCPOptionsAssociation AWS CloudFormation Resource (AWS::EC2::VPCDHCPOptionsAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html -type AWSEC2VPCDHCPOptionsAssociation struct { - - // DhcpOptionsId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-dhcpoptionsid - DhcpOptionsId string `json:"DhcpOptionsId,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-dhcp-options-assoc.html#cfn-ec2-vpcdhcpoptionsassociation-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPCDHCPOptionsAssociation) AWSCloudFormationType() string { - return "AWS::EC2::VPCDHCPOptionsAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPCDHCPOptionsAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPCDHCPOptionsAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPCDHCPOptionsAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPCDHCPOptionsAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPCDHCPOptionsAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCDHCPOptionsAssociationResources retrieves all AWSEC2VPCDHCPOptionsAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCDHCPOptionsAssociationResources() map[string]AWSEC2VPCDHCPOptionsAssociation { - results := map[string]AWSEC2VPCDHCPOptionsAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPCDHCPOptionsAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCDHCPOptionsAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCDHCPOptionsAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCDHCPOptionsAssociationWithName retrieves all AWSEC2VPCDHCPOptionsAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCDHCPOptionsAssociationWithName(name string) (AWSEC2VPCDHCPOptionsAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPCDHCPOptionsAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCDHCPOptionsAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCDHCPOptionsAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPCDHCPOptionsAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcendpoint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcendpoint.go deleted file mode 100644 index 7bdec43e80..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcendpoint.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPCEndpoint AWS CloudFormation Resource (AWS::EC2::VPCEndpoint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html -type AWSEC2VPCEndpoint struct { - - // PolicyDocument AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // RouteTableIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-routetableids - RouteTableIds []string `json:"RouteTableIds,omitempty"` - - // ServiceName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-servicename - ServiceName string `json:"ServiceName,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpoint.html#cfn-ec2-vpcendpoint-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPCEndpoint) AWSCloudFormationType() string { - return "AWS::EC2::VPCEndpoint" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPCEndpoint) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPCEndpoint - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPCEndpoint) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPCEndpoint - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPCEndpoint(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCEndpointResources retrieves all AWSEC2VPCEndpoint items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCEndpointResources() map[string]AWSEC2VPCEndpoint { - results := map[string]AWSEC2VPCEndpoint{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPCEndpoint: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCEndpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCEndpoint - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCEndpointWithName retrieves all AWSEC2VPCEndpoint items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCEndpointWithName(name string) (AWSEC2VPCEndpoint, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPCEndpoint: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCEndpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCEndpoint - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPCEndpoint{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcgatewayattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcgatewayattachment.go deleted file mode 100644 index ee3f3d1215..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcgatewayattachment.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPCGatewayAttachment AWS CloudFormation Resource (AWS::EC2::VPCGatewayAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html -type AWSEC2VPCGatewayAttachment struct { - - // InternetGatewayId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-internetgatewayid - InternetGatewayId string `json:"InternetGatewayId,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpcid - VpcId string `json:"VpcId,omitempty"` - - // VpnGatewayId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpc-gateway-attachment.html#cfn-ec2-vpcgatewayattachment-vpngatewayid - VpnGatewayId string `json:"VpnGatewayId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPCGatewayAttachment) AWSCloudFormationType() string { - return "AWS::EC2::VPCGatewayAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPCGatewayAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPCGatewayAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPCGatewayAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPCGatewayAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPCGatewayAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCGatewayAttachmentResources retrieves all AWSEC2VPCGatewayAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCGatewayAttachmentResources() map[string]AWSEC2VPCGatewayAttachment { - results := map[string]AWSEC2VPCGatewayAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPCGatewayAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCGatewayAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCGatewayAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCGatewayAttachmentWithName retrieves all AWSEC2VPCGatewayAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCGatewayAttachmentWithName(name string) (AWSEC2VPCGatewayAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPCGatewayAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCGatewayAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCGatewayAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPCGatewayAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcpeeringconnection.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcpeeringconnection.go deleted file mode 100644 index ddce8f7ce2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpcpeeringconnection.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPCPeeringConnection AWS CloudFormation Resource (AWS::EC2::VPCPeeringConnection) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html -type AWSEC2VPCPeeringConnection struct { - - // PeerOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerownerid - PeerOwnerId string `json:"PeerOwnerId,omitempty"` - - // PeerRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peerrolearn - PeerRoleArn string `json:"PeerRoleArn,omitempty"` - - // PeerVpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-peervpcid - PeerVpcId string `json:"PeerVpcId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcpeeringconnection.html#cfn-ec2-vpcpeeringconnection-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPCPeeringConnection) AWSCloudFormationType() string { - return "AWS::EC2::VPCPeeringConnection" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPCPeeringConnection) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPCPeeringConnection - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPCPeeringConnection) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPCPeeringConnection - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPCPeeringConnection(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPCPeeringConnectionResources retrieves all AWSEC2VPCPeeringConnection items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPCPeeringConnectionResources() map[string]AWSEC2VPCPeeringConnection { - results := map[string]AWSEC2VPCPeeringConnection{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPCPeeringConnection: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCPeeringConnection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCPeeringConnection - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPCPeeringConnectionWithName retrieves all AWSEC2VPCPeeringConnection items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPCPeeringConnectionWithName(name string) (AWSEC2VPCPeeringConnection, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPCPeeringConnection: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPCPeeringConnection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPCPeeringConnection - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPCPeeringConnection{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection.go deleted file mode 100644 index e06095cd61..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPNConnection AWS CloudFormation Resource (AWS::EC2::VPNConnection) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html -type AWSEC2VPNConnection struct { - - // CustomerGatewayId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-customergatewayid - CustomerGatewayId string `json:"CustomerGatewayId,omitempty"` - - // StaticRoutesOnly AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-StaticRoutesOnly - StaticRoutesOnly bool `json:"StaticRoutesOnly,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-tags - Tags []Tag `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-type - Type string `json:"Type,omitempty"` - - // VpnGatewayId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpngatewayid - VpnGatewayId string `json:"VpnGatewayId,omitempty"` - - // VpnTunnelOptionsSpecifications AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection.html#cfn-ec2-vpnconnection-vpntunneloptionsspecifications - VpnTunnelOptionsSpecifications []AWSEC2VPNConnection_VpnTunnelOptionsSpecification `json:"VpnTunnelOptionsSpecifications,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPNConnection) AWSCloudFormationType() string { - return "AWS::EC2::VPNConnection" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPNConnection) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPNConnection - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPNConnection) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPNConnection - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPNConnection(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPNConnectionResources retrieves all AWSEC2VPNConnection items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPNConnectionResources() map[string]AWSEC2VPNConnection { - results := map[string]AWSEC2VPNConnection{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPNConnection: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNConnection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNConnection - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPNConnectionWithName retrieves all AWSEC2VPNConnection items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPNConnectionWithName(name string) (AWSEC2VPNConnection, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPNConnection: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNConnection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNConnection - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPNConnection{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection_vpntunneloptionsspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection_vpntunneloptionsspecification.go deleted file mode 100644 index 347237d0d9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnection_vpntunneloptionsspecification.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEC2VPNConnection_VpnTunnelOptionsSpecification AWS CloudFormation Resource (AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html -type AWSEC2VPNConnection_VpnTunnelOptionsSpecification struct { - - // PreSharedKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html#cfn-ec2-vpnconnection-vpntunneloptionsspecification-presharedkey - PreSharedKey string `json:"PreSharedKey,omitempty"` - - // TunnelInsideCidr AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-vpnconnection-vpntunneloptionsspecification.html#cfn-ec2-vpnconnection-vpntunneloptionsspecification-tunnelinsidecidr - TunnelInsideCidr string `json:"TunnelInsideCidr,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPNConnection_VpnTunnelOptionsSpecification) AWSCloudFormationType() string { - return "AWS::EC2::VPNConnection.VpnTunnelOptionsSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnectionroute.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnectionroute.go deleted file mode 100644 index 1577677215..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpnconnectionroute.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPNConnectionRoute AWS CloudFormation Resource (AWS::EC2::VPNConnectionRoute) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html -type AWSEC2VPNConnectionRoute struct { - - // DestinationCidrBlock AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-cidrblock - DestinationCidrBlock string `json:"DestinationCidrBlock,omitempty"` - - // VpnConnectionId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-connection-route.html#cfn-ec2-vpnconnectionroute-connectionid - VpnConnectionId string `json:"VpnConnectionId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPNConnectionRoute) AWSCloudFormationType() string { - return "AWS::EC2::VPNConnectionRoute" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPNConnectionRoute) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPNConnectionRoute - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPNConnectionRoute) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPNConnectionRoute - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPNConnectionRoute(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPNConnectionRouteResources retrieves all AWSEC2VPNConnectionRoute items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPNConnectionRouteResources() map[string]AWSEC2VPNConnectionRoute { - results := map[string]AWSEC2VPNConnectionRoute{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPNConnectionRoute: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNConnectionRoute" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNConnectionRoute - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPNConnectionRouteWithName retrieves all AWSEC2VPNConnectionRoute items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPNConnectionRouteWithName(name string) (AWSEC2VPNConnectionRoute, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPNConnectionRoute: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNConnectionRoute" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNConnectionRoute - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPNConnectionRoute{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngateway.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngateway.go deleted file mode 100644 index cdfe65ac2b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngateway.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPNGateway AWS CloudFormation Resource (AWS::EC2::VPNGateway) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html -type AWSEC2VPNGateway struct { - - // AmazonSideAsn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-amazonsideasn - AmazonSideAsn int64 `json:"AmazonSideAsn,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-tags - Tags []Tag `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gateway.html#cfn-ec2-vpngateway-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPNGateway) AWSCloudFormationType() string { - return "AWS::EC2::VPNGateway" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPNGateway) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPNGateway - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPNGateway) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPNGateway - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPNGateway(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPNGatewayResources retrieves all AWSEC2VPNGateway items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPNGatewayResources() map[string]AWSEC2VPNGateway { - results := map[string]AWSEC2VPNGateway{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPNGateway: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNGateway - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPNGatewayWithName retrieves all AWSEC2VPNGateway items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPNGatewayWithName(name string) (AWSEC2VPNGateway, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPNGateway: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNGateway" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNGateway - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPNGateway{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngatewayroutepropagation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngatewayroutepropagation.go deleted file mode 100644 index 38b4f93fd4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ec2-vpngatewayroutepropagation.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEC2VPNGatewayRoutePropagation AWS CloudFormation Resource (AWS::EC2::VPNGatewayRoutePropagation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html -type AWSEC2VPNGatewayRoutePropagation struct { - - // RouteTableIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-routetableids - RouteTableIds []string `json:"RouteTableIds,omitempty"` - - // VpnGatewayId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpn-gatewayrouteprop.html#cfn-ec2-vpngatewayrouteprop-vpngatewayid - VpnGatewayId string `json:"VpnGatewayId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEC2VPNGatewayRoutePropagation) AWSCloudFormationType() string { - return "AWS::EC2::VPNGatewayRoutePropagation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEC2VPNGatewayRoutePropagation) MarshalJSON() ([]byte, error) { - type Properties AWSEC2VPNGatewayRoutePropagation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEC2VPNGatewayRoutePropagation) UnmarshalJSON(b []byte) error { - type Properties AWSEC2VPNGatewayRoutePropagation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEC2VPNGatewayRoutePropagation(*res.Properties) - } - - return nil -} - -// GetAllAWSEC2VPNGatewayRoutePropagationResources retrieves all AWSEC2VPNGatewayRoutePropagation items from an AWS CloudFormation template -func (t *Template) GetAllAWSEC2VPNGatewayRoutePropagationResources() map[string]AWSEC2VPNGatewayRoutePropagation { - results := map[string]AWSEC2VPNGatewayRoutePropagation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEC2VPNGatewayRoutePropagation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNGatewayRoutePropagation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNGatewayRoutePropagation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEC2VPNGatewayRoutePropagationWithName retrieves all AWSEC2VPNGatewayRoutePropagation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEC2VPNGatewayRoutePropagationWithName(name string) (AWSEC2VPNGatewayRoutePropagation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEC2VPNGatewayRoutePropagation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EC2::VPNGatewayRoutePropagation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEC2VPNGatewayRoutePropagation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEC2VPNGatewayRoutePropagation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecr-repository.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecr-repository.go deleted file mode 100644 index c5343e4b6e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecr-repository.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSECRRepository AWS CloudFormation Resource (AWS::ECR::Repository) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html -type AWSECRRepository struct { - - // RepositoryName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositoryname - RepositoryName string `json:"RepositoryName,omitempty"` - - // RepositoryPolicyText AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecr-repository.html#cfn-ecr-repository-repositorypolicytext - RepositoryPolicyText interface{} `json:"RepositoryPolicyText,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECRRepository) AWSCloudFormationType() string { - return "AWS::ECR::Repository" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSECRRepository) MarshalJSON() ([]byte, error) { - type Properties AWSECRRepository - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSECRRepository) UnmarshalJSON(b []byte) error { - type Properties AWSECRRepository - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSECRRepository(*res.Properties) - } - - return nil -} - -// GetAllAWSECRRepositoryResources retrieves all AWSECRRepository items from an AWS CloudFormation template -func (t *Template) GetAllAWSECRRepositoryResources() map[string]AWSECRRepository { - results := map[string]AWSECRRepository{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSECRRepository: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECR::Repository" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECRRepository - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSECRRepositoryWithName retrieves all AWSECRRepository items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSECRRepositoryWithName(name string) (AWSECRRepository, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSECRRepository: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECR::Repository" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECRRepository - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSECRRepository{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-cluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-cluster.go deleted file mode 100644 index 227abb3dfd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-cluster.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSECSCluster AWS CloudFormation Resource (AWS::ECS::Cluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-cluster.html -type AWSECSCluster struct { - - // ClusterName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-cluster.html#cfn-ecs-cluster-clustername - ClusterName string `json:"ClusterName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSCluster) AWSCloudFormationType() string { - return "AWS::ECS::Cluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSECSCluster) MarshalJSON() ([]byte, error) { - type Properties AWSECSCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSECSCluster) UnmarshalJSON(b []byte) error { - type Properties AWSECSCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSECSCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSECSClusterResources retrieves all AWSECSCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSECSClusterResources() map[string]AWSECSCluster { - results := map[string]AWSECSCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSECSCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSECSClusterWithName retrieves all AWSECSCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSECSClusterWithName(name string) (AWSECSCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSECSCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSECSCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service.go deleted file mode 100644 index e5f872466a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSECSService AWS CloudFormation Resource (AWS::ECS::Service) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html -type AWSECSService struct { - - // Cluster AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-cluster - Cluster string `json:"Cluster,omitempty"` - - // DeploymentConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-deploymentconfiguration - DeploymentConfiguration *AWSECSService_DeploymentConfiguration `json:"DeploymentConfiguration,omitempty"` - - // DesiredCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-desiredcount - DesiredCount int `json:"DesiredCount,omitempty"` - - // LoadBalancers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-loadbalancers - LoadBalancers []AWSECSService_LoadBalancer `json:"LoadBalancers,omitempty"` - - // PlacementConstraints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-placementconstraints - PlacementConstraints []AWSECSService_PlacementConstraint `json:"PlacementConstraints,omitempty"` - - // PlacementStrategies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-placementstrategies - PlacementStrategies []AWSECSService_PlacementStrategy `json:"PlacementStrategies,omitempty"` - - // Role AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-role - Role string `json:"Role,omitempty"` - - // ServiceName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-servicename - ServiceName string `json:"ServiceName,omitempty"` - - // TaskDefinition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-service.html#cfn-ecs-service-taskdefinition - TaskDefinition string `json:"TaskDefinition,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSService) AWSCloudFormationType() string { - return "AWS::ECS::Service" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSECSService) MarshalJSON() ([]byte, error) { - type Properties AWSECSService - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSECSService) UnmarshalJSON(b []byte) error { - type Properties AWSECSService - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSECSService(*res.Properties) - } - - return nil -} - -// GetAllAWSECSServiceResources retrieves all AWSECSService items from an AWS CloudFormation template -func (t *Template) GetAllAWSECSServiceResources() map[string]AWSECSService { - results := map[string]AWSECSService{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSECSService: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::Service" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSService - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSECSServiceWithName retrieves all AWSECSService items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSECSServiceWithName(name string) (AWSECSService, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSECSService: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::Service" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSService - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSECSService{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_deploymentconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_deploymentconfiguration.go deleted file mode 100644 index 785399069d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_deploymentconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSService_DeploymentConfiguration AWS CloudFormation Resource (AWS::ECS::Service.DeploymentConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html -type AWSECSService_DeploymentConfiguration struct { - - // MaximumPercent AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html#cfn-ecs-service-deploymentconfiguration-maximumpercent - MaximumPercent int `json:"MaximumPercent,omitempty"` - - // MinimumHealthyPercent AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-deploymentconfiguration.html#cfn-ecs-service-deploymentconfiguration-minimumhealthypercent - MinimumHealthyPercent int `json:"MinimumHealthyPercent,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSService_DeploymentConfiguration) AWSCloudFormationType() string { - return "AWS::ECS::Service.DeploymentConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_loadbalancer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_loadbalancer.go deleted file mode 100644 index 80b9f0f0d1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_loadbalancer.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSECSService_LoadBalancer AWS CloudFormation Resource (AWS::ECS::Service.LoadBalancer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html -type AWSECSService_LoadBalancer struct { - - // ContainerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html#cfn-ecs-service-loadbalancers-containername - ContainerName string `json:"ContainerName,omitempty"` - - // ContainerPort AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html#cfn-ecs-service-loadbalancers-containerport - ContainerPort int `json:"ContainerPort,omitempty"` - - // LoadBalancerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html#cfn-ecs-service-loadbalancers-loadbalancername - LoadBalancerName string `json:"LoadBalancerName,omitempty"` - - // TargetGroupArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-loadbalancers.html#cfn-ecs-service-loadbalancers-targetgrouparn - TargetGroupArn string `json:"TargetGroupArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSService_LoadBalancer) AWSCloudFormationType() string { - return "AWS::ECS::Service.LoadBalancer" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementconstraint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementconstraint.go deleted file mode 100644 index 2be8f0e313..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementconstraint.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSService_PlacementConstraint AWS CloudFormation Resource (AWS::ECS::Service.PlacementConstraint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementconstraint.html -type AWSECSService_PlacementConstraint struct { - - // Expression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementconstraint.html#cfn-ecs-service-placementconstraint-expression - Expression string `json:"Expression,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementconstraint.html#cfn-ecs-service-placementconstraint-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSService_PlacementConstraint) AWSCloudFormationType() string { - return "AWS::ECS::Service.PlacementConstraint" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementstrategy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementstrategy.go deleted file mode 100644 index 3c31865668..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-service_placementstrategy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSService_PlacementStrategy AWS CloudFormation Resource (AWS::ECS::Service.PlacementStrategy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementstrategy.html -type AWSECSService_PlacementStrategy struct { - - // Field AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementstrategy.html#cfn-ecs-service-placementstrategy-field - Field string `json:"Field,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-service-placementstrategy.html#cfn-ecs-service-placementstrategy-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSService_PlacementStrategy) AWSCloudFormationType() string { - return "AWS::ECS::Service.PlacementStrategy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition.go deleted file mode 100644 index ee2ee00b3f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSECSTaskDefinition AWS CloudFormation Resource (AWS::ECS::TaskDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html -type AWSECSTaskDefinition struct { - - // ContainerDefinitions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-containerdefinitions - ContainerDefinitions []AWSECSTaskDefinition_ContainerDefinition `json:"ContainerDefinitions,omitempty"` - - // Family AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-family - Family string `json:"Family,omitempty"` - - // NetworkMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-networkmode - NetworkMode string `json:"NetworkMode,omitempty"` - - // PlacementConstraints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-placementconstraints - PlacementConstraints []AWSECSTaskDefinition_TaskDefinitionPlacementConstraint `json:"PlacementConstraints,omitempty"` - - // TaskRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-taskrolearn - TaskRoleArn string `json:"TaskRoleArn,omitempty"` - - // Volumes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ecs-taskdefinition.html#cfn-ecs-taskdefinition-volumes - Volumes []AWSECSTaskDefinition_Volume `json:"Volumes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSECSTaskDefinition) MarshalJSON() ([]byte, error) { - type Properties AWSECSTaskDefinition - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSECSTaskDefinition) UnmarshalJSON(b []byte) error { - type Properties AWSECSTaskDefinition - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSECSTaskDefinition(*res.Properties) - } - - return nil -} - -// GetAllAWSECSTaskDefinitionResources retrieves all AWSECSTaskDefinition items from an AWS CloudFormation template -func (t *Template) GetAllAWSECSTaskDefinitionResources() map[string]AWSECSTaskDefinition { - results := map[string]AWSECSTaskDefinition{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSECSTaskDefinition: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::TaskDefinition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSTaskDefinition - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSECSTaskDefinitionWithName retrieves all AWSECSTaskDefinition items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSECSTaskDefinitionWithName(name string) (AWSECSTaskDefinition, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSECSTaskDefinition: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ECS::TaskDefinition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSECSTaskDefinition - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSECSTaskDefinition{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_containerdefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_containerdefinition.go deleted file mode 100644 index 0368a0d828..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_containerdefinition.go +++ /dev/null @@ -1,141 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_ContainerDefinition AWS CloudFormation Resource (AWS::ECS::TaskDefinition.ContainerDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html -type AWSECSTaskDefinition_ContainerDefinition struct { - - // Command AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-command - Command []string `json:"Command,omitempty"` - - // Cpu AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-cpu - Cpu int `json:"Cpu,omitempty"` - - // DisableNetworking AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-disablenetworking - DisableNetworking bool `json:"DisableNetworking,omitempty"` - - // DnsSearchDomains AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-dnssearchdomains - DnsSearchDomains []string `json:"DnsSearchDomains,omitempty"` - - // DnsServers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-dnsservers - DnsServers []string `json:"DnsServers,omitempty"` - - // DockerLabels AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-dockerlabels - DockerLabels map[string]string `json:"DockerLabels,omitempty"` - - // DockerSecurityOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-dockersecurityoptions - DockerSecurityOptions []string `json:"DockerSecurityOptions,omitempty"` - - // EntryPoint AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-entrypoint - EntryPoint []string `json:"EntryPoint,omitempty"` - - // Environment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-environment - Environment []AWSECSTaskDefinition_KeyValuePair `json:"Environment,omitempty"` - - // Essential AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-essential - Essential bool `json:"Essential,omitempty"` - - // ExtraHosts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-extrahosts - ExtraHosts []AWSECSTaskDefinition_HostEntry `json:"ExtraHosts,omitempty"` - - // Hostname AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-hostname - Hostname string `json:"Hostname,omitempty"` - - // Image AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-image - Image string `json:"Image,omitempty"` - - // Links AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-links - Links []string `json:"Links,omitempty"` - - // LogConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-logconfiguration - LogConfiguration *AWSECSTaskDefinition_LogConfiguration `json:"LogConfiguration,omitempty"` - - // Memory AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-memory - Memory int `json:"Memory,omitempty"` - - // MemoryReservation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-memoryreservation - MemoryReservation int `json:"MemoryReservation,omitempty"` - - // MountPoints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-mountpoints - MountPoints []AWSECSTaskDefinition_MountPoint `json:"MountPoints,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-name - Name string `json:"Name,omitempty"` - - // PortMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-portmappings - PortMappings []AWSECSTaskDefinition_PortMapping `json:"PortMappings,omitempty"` - - // Privileged AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-privileged - Privileged bool `json:"Privileged,omitempty"` - - // ReadonlyRootFilesystem AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-readonlyrootfilesystem - ReadonlyRootFilesystem bool `json:"ReadonlyRootFilesystem,omitempty"` - - // Ulimits AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-ulimits - Ulimits []AWSECSTaskDefinition_Ulimit `json:"Ulimits,omitempty"` - - // User AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-user - User string `json:"User,omitempty"` - - // VolumesFrom AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-volumesfrom - VolumesFrom []AWSECSTaskDefinition_VolumeFrom `json:"VolumesFrom,omitempty"` - - // WorkingDirectory AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions.html#cfn-ecs-taskdefinition-containerdefinition-workingdirectory - WorkingDirectory string `json:"WorkingDirectory,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_ContainerDefinition) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.ContainerDefinition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostentry.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostentry.go deleted file mode 100644 index 6ce10d61de..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostentry.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_HostEntry AWS CloudFormation Resource (AWS::ECS::TaskDefinition.HostEntry) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-hostentry.html -type AWSECSTaskDefinition_HostEntry struct { - - // Hostname AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-hostentry.html#cfn-ecs-taskdefinition-containerdefinition-hostentry-hostname - Hostname string `json:"Hostname,omitempty"` - - // IpAddress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-hostentry.html#cfn-ecs-taskdefinition-containerdefinition-hostentry-ipaddress - IpAddress string `json:"IpAddress,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_HostEntry) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.HostEntry" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostvolumeproperties.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostvolumeproperties.go deleted file mode 100644 index 0badcd2b1a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_hostvolumeproperties.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_HostVolumeProperties AWS CloudFormation Resource (AWS::ECS::TaskDefinition.HostVolumeProperties) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes-host.html -type AWSECSTaskDefinition_HostVolumeProperties struct { - - // SourcePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes-host.html#cfn-ecs-taskdefinition-volumes-host-sourcepath - SourcePath string `json:"SourcePath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_HostVolumeProperties) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.HostVolumeProperties" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_keyvaluepair.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_keyvaluepair.go deleted file mode 100644 index 5d216e2158..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_keyvaluepair.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_KeyValuePair AWS CloudFormation Resource (AWS::ECS::TaskDefinition.KeyValuePair) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-environment.html -type AWSECSTaskDefinition_KeyValuePair struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-environment.html#cfn-ecs-taskdefinition-containerdefinition-environment-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-environment.html#cfn-ecs-taskdefinition-containerdefinition-environment-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_KeyValuePair) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.KeyValuePair" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_logconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_logconfiguration.go deleted file mode 100644 index 7579f2825c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_logconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_LogConfiguration AWS CloudFormation Resource (AWS::ECS::TaskDefinition.LogConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-logconfiguration.html -type AWSECSTaskDefinition_LogConfiguration struct { - - // LogDriver AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-logconfiguration.html#cfn-ecs-taskdefinition-containerdefinition-logconfiguration-logdriver - LogDriver string `json:"LogDriver,omitempty"` - - // Options AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-logconfiguration.html#cfn-ecs-taskdefinition-containerdefinition-logconfiguration-options - Options map[string]string `json:"Options,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_LogConfiguration) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.LogConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_mountpoint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_mountpoint.go deleted file mode 100644 index e447bceea1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_mountpoint.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_MountPoint AWS CloudFormation Resource (AWS::ECS::TaskDefinition.MountPoint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-mountpoints.html -type AWSECSTaskDefinition_MountPoint struct { - - // ContainerPath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-mountpoints.html#cfn-ecs-taskdefinition-containerdefinition-mountpoints-containerpath - ContainerPath string `json:"ContainerPath,omitempty"` - - // ReadOnly AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-mountpoints.html#cfn-ecs-taskdefinition-containerdefinition-mountpoints-readonly - ReadOnly bool `json:"ReadOnly,omitempty"` - - // SourceVolume AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-mountpoints.html#cfn-ecs-taskdefinition-containerdefinition-mountpoints-sourcevolume - SourceVolume string `json:"SourceVolume,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_MountPoint) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.MountPoint" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_portmapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_portmapping.go deleted file mode 100644 index 5452b10ddd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_portmapping.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_PortMapping AWS CloudFormation Resource (AWS::ECS::TaskDefinition.PortMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html -type AWSECSTaskDefinition_PortMapping struct { - - // ContainerPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html#cfn-ecs-taskdefinition-containerdefinition-portmappings-containerport - ContainerPort int `json:"ContainerPort,omitempty"` - - // HostPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html#cfn-ecs-taskdefinition-containerdefinition-portmappings-readonly - HostPort int `json:"HostPort,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-portmappings.html#cfn-ecs-taskdefinition-containerdefinition-portmappings-sourcevolume - Protocol string `json:"Protocol,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_PortMapping) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.PortMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_taskdefinitionplacementconstraint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_taskdefinitionplacementconstraint.go deleted file mode 100644 index 504755041c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_taskdefinitionplacementconstraint.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_TaskDefinitionPlacementConstraint AWS CloudFormation Resource (AWS::ECS::TaskDefinition.TaskDefinitionPlacementConstraint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html -type AWSECSTaskDefinition_TaskDefinitionPlacementConstraint struct { - - // Expression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html#cfn-ecs-taskdefinition-taskdefinitionplacementconstraint-expression - Expression string `json:"Expression,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-taskdefinitionplacementconstraint.html#cfn-ecs-taskdefinition-taskdefinitionplacementconstraint-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_TaskDefinitionPlacementConstraint) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.TaskDefinitionPlacementConstraint" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_ulimit.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_ulimit.go deleted file mode 100644 index 312be33a0c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_ulimit.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_Ulimit AWS CloudFormation Resource (AWS::ECS::TaskDefinition.Ulimit) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-ulimit.html -type AWSECSTaskDefinition_Ulimit struct { - - // HardLimit AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-ulimit.html#cfn-ecs-taskdefinition-containerdefinition-ulimit-hardlimit - HardLimit int `json:"HardLimit,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-ulimit.html#cfn-ecs-taskdefinition-containerdefinition-ulimit-name - Name string `json:"Name,omitempty"` - - // SoftLimit AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-ulimit.html#cfn-ecs-taskdefinition-containerdefinition-ulimit-softlimit - SoftLimit int `json:"SoftLimit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_Ulimit) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.Ulimit" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volume.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volume.go deleted file mode 100644 index 903269d937..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volume.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_Volume AWS CloudFormation Resource (AWS::ECS::TaskDefinition.Volume) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes.html -type AWSECSTaskDefinition_Volume struct { - - // Host AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes.html#cfn-ecs-taskdefinition-volumes-host - Host *AWSECSTaskDefinition_HostVolumeProperties `json:"Host,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-volumes.html#cfn-ecs-taskdefinition-volumes-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_Volume) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.Volume" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volumefrom.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volumefrom.go deleted file mode 100644 index 36499016dc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ecs-taskdefinition_volumefrom.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSECSTaskDefinition_VolumeFrom AWS CloudFormation Resource (AWS::ECS::TaskDefinition.VolumeFrom) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-volumesfrom.html -type AWSECSTaskDefinition_VolumeFrom struct { - - // ReadOnly AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-volumesfrom.html#cfn-ecs-taskdefinition-containerdefinition-volumesfrom-readonly - ReadOnly bool `json:"ReadOnly,omitempty"` - - // SourceContainer AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-containerdefinitions-volumesfrom.html#cfn-ecs-taskdefinition-containerdefinition-volumesfrom-sourcecontainer - SourceContainer string `json:"SourceContainer,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSECSTaskDefinition_VolumeFrom) AWSCloudFormationType() string { - return "AWS::ECS::TaskDefinition.VolumeFrom" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem.go deleted file mode 100644 index 8d8ccb01c2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEFSFileSystem AWS CloudFormation Resource (AWS::EFS::FileSystem) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html -type AWSEFSFileSystem struct { - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // FileSystemTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-filesystemtags - FileSystemTags []AWSEFSFileSystem_ElasticFileSystemTag `json:"FileSystemTags,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // PerformanceMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-filesystem.html#cfn-efs-filesystem-performancemode - PerformanceMode string `json:"PerformanceMode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEFSFileSystem) AWSCloudFormationType() string { - return "AWS::EFS::FileSystem" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEFSFileSystem) MarshalJSON() ([]byte, error) { - type Properties AWSEFSFileSystem - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEFSFileSystem) UnmarshalJSON(b []byte) error { - type Properties AWSEFSFileSystem - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEFSFileSystem(*res.Properties) - } - - return nil -} - -// GetAllAWSEFSFileSystemResources retrieves all AWSEFSFileSystem items from an AWS CloudFormation template -func (t *Template) GetAllAWSEFSFileSystemResources() map[string]AWSEFSFileSystem { - results := map[string]AWSEFSFileSystem{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEFSFileSystem: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EFS::FileSystem" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEFSFileSystem - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEFSFileSystemWithName retrieves all AWSEFSFileSystem items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEFSFileSystemWithName(name string) (AWSEFSFileSystem, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEFSFileSystem: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EFS::FileSystem" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEFSFileSystem - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEFSFileSystem{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem_elasticfilesystemtag.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem_elasticfilesystemtag.go deleted file mode 100644 index 4421b17dae..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-filesystem_elasticfilesystemtag.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEFSFileSystem_ElasticFileSystemTag AWS CloudFormation Resource (AWS::EFS::FileSystem.ElasticFileSystemTag) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-filesystemtags.html -type AWSEFSFileSystem_ElasticFileSystemTag struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-filesystemtags.html#cfn-efs-filesystem-filesystemtags-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-efs-filesystem-filesystemtags.html#cfn-efs-filesystem-filesystemtags-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEFSFileSystem_ElasticFileSystemTag) AWSCloudFormationType() string { - return "AWS::EFS::FileSystem.ElasticFileSystemTag" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-mounttarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-mounttarget.go deleted file mode 100644 index ac14214fff..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-efs-mounttarget.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEFSMountTarget AWS CloudFormation Resource (AWS::EFS::MountTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html -type AWSEFSMountTarget struct { - - // FileSystemId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-filesystemid - FileSystemId string `json:"FileSystemId,omitempty"` - - // IpAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-ipaddress - IpAddress string `json:"IpAddress,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-securitygroups - SecurityGroups []string `json:"SecurityGroups,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-mounttarget.html#cfn-efs-mounttarget-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEFSMountTarget) AWSCloudFormationType() string { - return "AWS::EFS::MountTarget" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEFSMountTarget) MarshalJSON() ([]byte, error) { - type Properties AWSEFSMountTarget - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEFSMountTarget) UnmarshalJSON(b []byte) error { - type Properties AWSEFSMountTarget - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEFSMountTarget(*res.Properties) - } - - return nil -} - -// GetAllAWSEFSMountTargetResources retrieves all AWSEFSMountTarget items from an AWS CloudFormation template -func (t *Template) GetAllAWSEFSMountTargetResources() map[string]AWSEFSMountTarget { - results := map[string]AWSEFSMountTarget{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEFSMountTarget: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EFS::MountTarget" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEFSMountTarget - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEFSMountTargetWithName retrieves all AWSEFSMountTarget items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEFSMountTargetWithName(name string) (AWSEFSMountTarget, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEFSMountTarget: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EFS::MountTarget" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEFSMountTarget - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEFSMountTarget{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-cachecluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-cachecluster.go deleted file mode 100644 index d76defd63b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-cachecluster.go +++ /dev/null @@ -1,210 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheCacheCluster AWS CloudFormation Resource (AWS::ElastiCache::CacheCluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html -type AWSElastiCacheCacheCluster struct { - - // AZMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-azmode - AZMode string `json:"AZMode,omitempty"` - - // AutoMinorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-autominorversionupgrade - AutoMinorVersionUpgrade bool `json:"AutoMinorVersionUpgrade,omitempty"` - - // CacheNodeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-cachenodetype - CacheNodeType string `json:"CacheNodeType,omitempty"` - - // CacheParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-cacheparametergroupname - CacheParameterGroupName string `json:"CacheParameterGroupName,omitempty"` - - // CacheSecurityGroupNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-cachesecuritygroupnames - CacheSecurityGroupNames []string `json:"CacheSecurityGroupNames,omitempty"` - - // CacheSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-cachesubnetgroupname - CacheSubnetGroupName string `json:"CacheSubnetGroupName,omitempty"` - - // ClusterName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-clustername - ClusterName string `json:"ClusterName,omitempty"` - - // Engine AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-engine - Engine string `json:"Engine,omitempty"` - - // EngineVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-engineversion - EngineVersion string `json:"EngineVersion,omitempty"` - - // NotificationTopicArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-notificationtopicarn - NotificationTopicArn string `json:"NotificationTopicArn,omitempty"` - - // NumCacheNodes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-numcachenodes - NumCacheNodes int `json:"NumCacheNodes,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-port - Port int `json:"Port,omitempty"` - - // PreferredAvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-preferredavailabilityzone - PreferredAvailabilityZone string `json:"PreferredAvailabilityZone,omitempty"` - - // PreferredAvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-preferredavailabilityzones - PreferredAvailabilityZones []string `json:"PreferredAvailabilityZones,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // SnapshotArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-snapshotarns - SnapshotArns []string `json:"SnapshotArns,omitempty"` - - // SnapshotName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-snapshotname - SnapshotName string `json:"SnapshotName,omitempty"` - - // SnapshotRetentionLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-snapshotretentionlimit - SnapshotRetentionLimit int `json:"SnapshotRetentionLimit,omitempty"` - - // SnapshotWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-snapshotwindow - SnapshotWindow string `json:"SnapshotWindow,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcSecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-cache-cluster.html#cfn-elasticache-cachecluster-vpcsecuritygroupids - VpcSecurityGroupIds []string `json:"VpcSecurityGroupIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheCacheCluster) AWSCloudFormationType() string { - return "AWS::ElastiCache::CacheCluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheCacheCluster) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheCacheCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheCacheCluster) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheCacheCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheCacheCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheCacheClusterResources retrieves all AWSElastiCacheCacheCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheCacheClusterResources() map[string]AWSElastiCacheCacheCluster { - results := map[string]AWSElastiCacheCacheCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheCacheCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::CacheCluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheCacheCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheCacheClusterWithName retrieves all AWSElastiCacheCacheCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheCacheClusterWithName(name string) (AWSElastiCacheCacheCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheCacheCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::CacheCluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheCacheCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheCacheCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-parametergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-parametergroup.go deleted file mode 100644 index bd13890651..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-parametergroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheParameterGroup AWS CloudFormation Resource (AWS::ElastiCache::ParameterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-parameter-group.html -type AWSElastiCacheParameterGroup struct { - - // CacheParameterGroupFamily AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-parameter-group.html#cfn-elasticache-parametergroup-cacheparametergroupfamily - CacheParameterGroupFamily string `json:"CacheParameterGroupFamily,omitempty"` - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-parameter-group.html#cfn-elasticache-parametergroup-description - Description string `json:"Description,omitempty"` - - // Properties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-parameter-group.html#cfn-elasticache-parametergroup-properties - Properties map[string]string `json:"Properties,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheParameterGroup) AWSCloudFormationType() string { - return "AWS::ElastiCache::ParameterGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheParameterGroup) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheParameterGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheParameterGroup) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheParameterGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheParameterGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheParameterGroupResources retrieves all AWSElastiCacheParameterGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]AWSElastiCacheParameterGroup { - results := map[string]AWSElastiCacheParameterGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheParameterGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::ParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheParameterGroupWithName retrieves all AWSElastiCacheParameterGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheParameterGroupWithName(name string) (AWSElastiCacheParameterGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheParameterGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::ParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheParameterGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup.go deleted file mode 100644 index 89735c84f6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup.go +++ /dev/null @@ -1,235 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheReplicationGroup AWS CloudFormation Resource (AWS::ElastiCache::ReplicationGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html -type AWSElastiCacheReplicationGroup struct { - - // AutoMinorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-autominorversionupgrade - AutoMinorVersionUpgrade bool `json:"AutoMinorVersionUpgrade,omitempty"` - - // AutomaticFailoverEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-automaticfailoverenabled - AutomaticFailoverEnabled bool `json:"AutomaticFailoverEnabled,omitempty"` - - // CacheNodeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachenodetype - CacheNodeType string `json:"CacheNodeType,omitempty"` - - // CacheParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cacheparametergroupname - CacheParameterGroupName string `json:"CacheParameterGroupName,omitempty"` - - // CacheSecurityGroupNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachesecuritygroupnames - CacheSecurityGroupNames []string `json:"CacheSecurityGroupNames,omitempty"` - - // CacheSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-cachesubnetgroupname - CacheSubnetGroupName string `json:"CacheSubnetGroupName,omitempty"` - - // Engine AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-engine - Engine string `json:"Engine,omitempty"` - - // EngineVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-engineversion - EngineVersion string `json:"EngineVersion,omitempty"` - - // NodeGroupConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-nodegroupconfiguration - NodeGroupConfiguration []AWSElastiCacheReplicationGroup_NodeGroupConfiguration `json:"NodeGroupConfiguration,omitempty"` - - // NotificationTopicArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-notificationtopicarn - NotificationTopicArn string `json:"NotificationTopicArn,omitempty"` - - // NumCacheClusters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-numcacheclusters - NumCacheClusters int `json:"NumCacheClusters,omitempty"` - - // NumNodeGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-numnodegroups - NumNodeGroups int `json:"NumNodeGroups,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-port - Port int `json:"Port,omitempty"` - - // PreferredCacheClusterAZs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-preferredcacheclusterazs - PreferredCacheClusterAZs []string `json:"PreferredCacheClusterAZs,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // PrimaryClusterId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-primaryclusterid - PrimaryClusterId string `json:"PrimaryClusterId,omitempty"` - - // ReplicasPerNodeGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicaspernodegroup - ReplicasPerNodeGroup int `json:"ReplicasPerNodeGroup,omitempty"` - - // ReplicationGroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicationgroupdescription - ReplicationGroupDescription string `json:"ReplicationGroupDescription,omitempty"` - - // ReplicationGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-replicationgroupid - ReplicationGroupId string `json:"ReplicationGroupId,omitempty"` - - // SecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SnapshotArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotarns - SnapshotArns []string `json:"SnapshotArns,omitempty"` - - // SnapshotName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotname - SnapshotName string `json:"SnapshotName,omitempty"` - - // SnapshotRetentionLimit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotretentionlimit - SnapshotRetentionLimit int `json:"SnapshotRetentionLimit,omitempty"` - - // SnapshotWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshotwindow - SnapshotWindow string `json:"SnapshotWindow,omitempty"` - - // SnapshottingClusterId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-snapshottingclusterid - SnapshottingClusterId string `json:"SnapshottingClusterId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticache-replicationgroup.html#cfn-elasticache-replicationgroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheReplicationGroup) AWSCloudFormationType() string { - return "AWS::ElastiCache::ReplicationGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheReplicationGroup) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheReplicationGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheReplicationGroup) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheReplicationGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheReplicationGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheReplicationGroupResources retrieves all AWSElastiCacheReplicationGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheReplicationGroupResources() map[string]AWSElastiCacheReplicationGroup { - results := map[string]AWSElastiCacheReplicationGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheReplicationGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::ReplicationGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheReplicationGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheReplicationGroupWithName retrieves all AWSElastiCacheReplicationGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheReplicationGroupWithName(name string) (AWSElastiCacheReplicationGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheReplicationGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::ReplicationGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheReplicationGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheReplicationGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup_nodegroupconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup_nodegroupconfiguration.go deleted file mode 100644 index 35c192070a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-replicationgroup_nodegroupconfiguration.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSElastiCacheReplicationGroup_NodeGroupConfiguration AWS CloudFormation Resource (AWS::ElastiCache::ReplicationGroup.NodeGroupConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html -type AWSElastiCacheReplicationGroup_NodeGroupConfiguration struct { - - // PrimaryAvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-primaryavailabilityzone - PrimaryAvailabilityZone string `json:"PrimaryAvailabilityZone,omitempty"` - - // ReplicaAvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-replicaavailabilityzones - ReplicaAvailabilityZones []string `json:"ReplicaAvailabilityZones,omitempty"` - - // ReplicaCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-replicacount - ReplicaCount int `json:"ReplicaCount,omitempty"` - - // Slots AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-replicationgroup-nodegroupconfiguration.html#cfn-elasticache-replicationgroup-nodegroupconfiguration-slots - Slots string `json:"Slots,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheReplicationGroup_NodeGroupConfiguration) AWSCloudFormationType() string { - return "AWS::ElastiCache::ReplicationGroup.NodeGroupConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroup.go deleted file mode 100644 index ae28fd2192..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroup.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheSecurityGroup AWS CloudFormation Resource (AWS::ElastiCache::SecurityGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group.html -type AWSElastiCacheSecurityGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group.html#cfn-elasticache-securitygroup-description - Description string `json:"Description,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheSecurityGroup) AWSCloudFormationType() string { - return "AWS::ElastiCache::SecurityGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheSecurityGroup) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheSecurityGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheSecurityGroup) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheSecurityGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheSecurityGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheSecurityGroupResources retrieves all AWSElastiCacheSecurityGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheSecurityGroupResources() map[string]AWSElastiCacheSecurityGroup { - results := map[string]AWSElastiCacheSecurityGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheSecurityGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheSecurityGroupWithName retrieves all AWSElastiCacheSecurityGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheSecurityGroupWithName(name string) (AWSElastiCacheSecurityGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheSecurityGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheSecurityGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroupingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroupingress.go deleted file mode 100644 index 3d33ab9bf8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-securitygroupingress.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheSecurityGroupIngress AWS CloudFormation Resource (AWS::ElastiCache::SecurityGroupIngress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html -type AWSElastiCacheSecurityGroupIngress struct { - - // CacheSecurityGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html#cfn-elasticache-securitygroupingress-cachesecuritygroupname - CacheSecurityGroupName string `json:"CacheSecurityGroupName,omitempty"` - - // EC2SecurityGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html#cfn-elasticache-securitygroupingress-ec2securitygroupname - EC2SecurityGroupName string `json:"EC2SecurityGroupName,omitempty"` - - // EC2SecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-security-group-ingress.html#cfn-elasticache-securitygroupingress-ec2securitygroupownerid - EC2SecurityGroupOwnerId string `json:"EC2SecurityGroupOwnerId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheSecurityGroupIngress) AWSCloudFormationType() string { - return "AWS::ElastiCache::SecurityGroupIngress" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheSecurityGroupIngress) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheSecurityGroupIngress - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheSecurityGroupIngress) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheSecurityGroupIngress - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheSecurityGroupIngress(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheSecurityGroupIngressResources retrieves all AWSElastiCacheSecurityGroupIngress items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheSecurityGroupIngressResources() map[string]AWSElastiCacheSecurityGroupIngress { - results := map[string]AWSElastiCacheSecurityGroupIngress{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheSecurityGroupIngressWithName retrieves all AWSElastiCacheSecurityGroupIngress items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheSecurityGroupIngressWithName(name string) (AWSElastiCacheSecurityGroupIngress, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheSecurityGroupIngress{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-subnetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-subnetgroup.go deleted file mode 100644 index b49d80e6f0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticache-subnetgroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElastiCacheSubnetGroup AWS CloudFormation Resource (AWS::ElastiCache::SubnetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html -type AWSElastiCacheSubnetGroup struct { - - // CacheSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-cachesubnetgroupname - CacheSubnetGroupName string `json:"CacheSubnetGroupName,omitempty"` - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-description - Description string `json:"Description,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticache-subnetgroup.html#cfn-elasticache-subnetgroup-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElastiCacheSubnetGroup) AWSCloudFormationType() string { - return "AWS::ElastiCache::SubnetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElastiCacheSubnetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSElastiCacheSubnetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElastiCacheSubnetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSElastiCacheSubnetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElastiCacheSubnetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSElastiCacheSubnetGroupResources retrieves all AWSElastiCacheSubnetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSElastiCacheSubnetGroupResources() map[string]AWSElastiCacheSubnetGroup { - results := map[string]AWSElastiCacheSubnetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElastiCacheSubnetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElastiCacheSubnetGroupWithName retrieves all AWSElastiCacheSubnetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElastiCacheSubnetGroupWithName(name string) (AWSElastiCacheSubnetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElastiCacheSubnetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElastiCache::SubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElastiCacheSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElastiCacheSubnetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application.go deleted file mode 100644 index 62be14cbb5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticBeanstalkApplication AWS CloudFormation Resource (AWS::ElasticBeanstalk::Application) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk.html -type AWSElasticBeanstalkApplication struct { - - // ApplicationName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk.html#cfn-elasticbeanstalk-application-name - ApplicationName string `json:"ApplicationName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk.html#cfn-elasticbeanstalk-application-description - Description string `json:"Description,omitempty"` - - // ResourceLifecycleConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk.html#cfn-elasticbeanstalk-application-resourcelifecycleconfig - ResourceLifecycleConfig *AWSElasticBeanstalkApplication_ApplicationResourceLifecycleConfig `json:"ResourceLifecycleConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplication) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Application" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticBeanstalkApplication) MarshalJSON() ([]byte, error) { - type Properties AWSElasticBeanstalkApplication - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticBeanstalkApplication) UnmarshalJSON(b []byte) error { - type Properties AWSElasticBeanstalkApplication - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticBeanstalkApplication(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticBeanstalkApplicationResources retrieves all AWSElasticBeanstalkApplication items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticBeanstalkApplicationResources() map[string]AWSElasticBeanstalkApplication { - results := map[string]AWSElasticBeanstalkApplication{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticBeanstalkApplication: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkApplication - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticBeanstalkApplicationWithName retrieves all AWSElasticBeanstalkApplication items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticBeanstalkApplicationWithName(name string) (AWSElasticBeanstalkApplication, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticBeanstalkApplication: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkApplication - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticBeanstalkApplication{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationresourcelifecycleconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationresourcelifecycleconfig.go deleted file mode 100644 index cc276ecd51..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationresourcelifecycleconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkApplication_ApplicationResourceLifecycleConfig AWS CloudFormation Resource (AWS::ElasticBeanstalk::Application.ApplicationResourceLifecycleConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationresourcelifecycleconfig.html -type AWSElasticBeanstalkApplication_ApplicationResourceLifecycleConfig struct { - - // ServiceRole AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationresourcelifecycleconfig.html#cfn-elasticbeanstalk-application-applicationresourcelifecycleconfig-servicerole - ServiceRole string `json:"ServiceRole,omitempty"` - - // VersionLifecycleConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationresourcelifecycleconfig.html#cfn-elasticbeanstalk-application-applicationresourcelifecycleconfig-versionlifecycleconfig - VersionLifecycleConfig *AWSElasticBeanstalkApplication_ApplicationVersionLifecycleConfig `json:"VersionLifecycleConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplication_ApplicationResourceLifecycleConfig) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Application.ApplicationResourceLifecycleConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationversionlifecycleconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationversionlifecycleconfig.go deleted file mode 100644 index 53cff7b4cd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_applicationversionlifecycleconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkApplication_ApplicationVersionLifecycleConfig AWS CloudFormation Resource (AWS::ElasticBeanstalk::Application.ApplicationVersionLifecycleConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationversionlifecycleconfig.html -type AWSElasticBeanstalkApplication_ApplicationVersionLifecycleConfig struct { - - // MaxAgeRule AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationversionlifecycleconfig.html#cfn-elasticbeanstalk-application-applicationversionlifecycleconfig-maxagerule - MaxAgeRule *AWSElasticBeanstalkApplication_MaxAgeRule `json:"MaxAgeRule,omitempty"` - - // MaxCountRule AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-applicationversionlifecycleconfig.html#cfn-elasticbeanstalk-application-applicationversionlifecycleconfig-maxcountrule - MaxCountRule *AWSElasticBeanstalkApplication_MaxCountRule `json:"MaxCountRule,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplication_ApplicationVersionLifecycleConfig) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Application.ApplicationVersionLifecycleConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxagerule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxagerule.go deleted file mode 100644 index d38ca2cdcc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxagerule.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkApplication_MaxAgeRule AWS CloudFormation Resource (AWS::ElasticBeanstalk::Application.MaxAgeRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxagerule.html -type AWSElasticBeanstalkApplication_MaxAgeRule struct { - - // DeleteSourceFromS3 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxagerule.html#cfn-elasticbeanstalk-application-maxagerule-deletesourcefroms3 - DeleteSourceFromS3 bool `json:"DeleteSourceFromS3,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxagerule.html#cfn-elasticbeanstalk-application-maxagerule-enabled - Enabled bool `json:"Enabled,omitempty"` - - // MaxAgeInDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxagerule.html#cfn-elasticbeanstalk-application-maxagerule-maxageindays - MaxAgeInDays int `json:"MaxAgeInDays,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplication_MaxAgeRule) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Application.MaxAgeRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxcountrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxcountrule.go deleted file mode 100644 index e99dea3a24..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-application_maxcountrule.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkApplication_MaxCountRule AWS CloudFormation Resource (AWS::ElasticBeanstalk::Application.MaxCountRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html -type AWSElasticBeanstalkApplication_MaxCountRule struct { - - // DeleteSourceFromS3 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-deletesourcefroms3 - DeleteSourceFromS3 bool `json:"DeleteSourceFromS3,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-enabled - Enabled bool `json:"Enabled,omitempty"` - - // MaxCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-maxcount - MaxCount int `json:"MaxCount,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplication_MaxCountRule) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Application.MaxCountRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion.go deleted file mode 100644 index 9e1b15e981..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticBeanstalkApplicationVersion AWS CloudFormation Resource (AWS::ElasticBeanstalk::ApplicationVersion) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html -type AWSElasticBeanstalkApplicationVersion struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-description - Description string `json:"Description,omitempty"` - - // SourceBundle AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-sourcebundle - SourceBundle *AWSElasticBeanstalkApplicationVersion_SourceBundle `json:"SourceBundle,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplicationVersion) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::ApplicationVersion" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticBeanstalkApplicationVersion) MarshalJSON() ([]byte, error) { - type Properties AWSElasticBeanstalkApplicationVersion - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticBeanstalkApplicationVersion) UnmarshalJSON(b []byte) error { - type Properties AWSElasticBeanstalkApplicationVersion - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticBeanstalkApplicationVersion(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticBeanstalkApplicationVersionResources retrieves all AWSElasticBeanstalkApplicationVersion items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticBeanstalkApplicationVersionResources() map[string]AWSElasticBeanstalkApplicationVersion { - results := map[string]AWSElasticBeanstalkApplicationVersion{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticBeanstalkApplicationVersion: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::ApplicationVersion" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkApplicationVersion - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticBeanstalkApplicationVersionWithName retrieves all AWSElasticBeanstalkApplicationVersion items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticBeanstalkApplicationVersionWithName(name string) (AWSElasticBeanstalkApplicationVersion, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticBeanstalkApplicationVersion: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::ApplicationVersion" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkApplicationVersion - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticBeanstalkApplicationVersion{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion_sourcebundle.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion_sourcebundle.go deleted file mode 100644 index 538ed72005..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-applicationversion_sourcebundle.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkApplicationVersion_SourceBundle AWS CloudFormation Resource (AWS::ElasticBeanstalk::ApplicationVersion.SourceBundle) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-sourcebundle.html -type AWSElasticBeanstalkApplicationVersion_SourceBundle struct { - - // S3Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-sourcebundle.html#cfn-beanstalk-sourcebundle-s3bucket - S3Bucket string `json:"S3Bucket,omitempty"` - - // S3Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-sourcebundle.html#cfn-beanstalk-sourcebundle-s3key - S3Key string `json:"S3Key,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkApplicationVersion_SourceBundle) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::ApplicationVersion.SourceBundle" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate.go deleted file mode 100644 index 55e1ad8282..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticBeanstalkConfigurationTemplate AWS CloudFormation Resource (AWS::ElasticBeanstalk::ConfigurationTemplate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html -type AWSElasticBeanstalkConfigurationTemplate struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-description - Description string `json:"Description,omitempty"` - - // EnvironmentId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-environmentid - EnvironmentId string `json:"EnvironmentId,omitempty"` - - // OptionSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-optionsettings - OptionSettings []AWSElasticBeanstalkConfigurationTemplate_ConfigurationOptionSetting `json:"OptionSettings,omitempty"` - - // PlatformArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-platformarn - PlatformArn string `json:"PlatformArn,omitempty"` - - // SolutionStackName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-solutionstackname - SolutionStackName string `json:"SolutionStackName,omitempty"` - - // SourceConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-beanstalk-configurationtemplate.html#cfn-elasticbeanstalk-configurationtemplate-sourceconfiguration - SourceConfiguration *AWSElasticBeanstalkConfigurationTemplate_SourceConfiguration `json:"SourceConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkConfigurationTemplate) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::ConfigurationTemplate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticBeanstalkConfigurationTemplate) MarshalJSON() ([]byte, error) { - type Properties AWSElasticBeanstalkConfigurationTemplate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticBeanstalkConfigurationTemplate) UnmarshalJSON(b []byte) error { - type Properties AWSElasticBeanstalkConfigurationTemplate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticBeanstalkConfigurationTemplate(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticBeanstalkConfigurationTemplateResources retrieves all AWSElasticBeanstalkConfigurationTemplate items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticBeanstalkConfigurationTemplateResources() map[string]AWSElasticBeanstalkConfigurationTemplate { - results := map[string]AWSElasticBeanstalkConfigurationTemplate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticBeanstalkConfigurationTemplate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::ConfigurationTemplate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkConfigurationTemplate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticBeanstalkConfigurationTemplateWithName retrieves all AWSElasticBeanstalkConfigurationTemplate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticBeanstalkConfigurationTemplateWithName(name string) (AWSElasticBeanstalkConfigurationTemplate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticBeanstalkConfigurationTemplate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::ConfigurationTemplate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkConfigurationTemplate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticBeanstalkConfigurationTemplate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_configurationoptionsetting.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_configurationoptionsetting.go deleted file mode 100644 index 05b6bf2bf3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_configurationoptionsetting.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkConfigurationTemplate_ConfigurationOptionSetting AWS CloudFormation Resource (AWS::ElasticBeanstalk::ConfigurationTemplate.ConfigurationOptionSetting) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html -type AWSElasticBeanstalkConfigurationTemplate_ConfigurationOptionSetting struct { - - // Namespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-namespace - Namespace string `json:"Namespace,omitempty"` - - // OptionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-optionname - OptionName string `json:"OptionName,omitempty"` - - // ResourceName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-elasticbeanstalk-configurationtemplate-configurationoptionsetting-resourcename - ResourceName string `json:"ResourceName,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkConfigurationTemplate_ConfigurationOptionSetting) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::ConfigurationTemplate.ConfigurationOptionSetting" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_sourceconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_sourceconfiguration.go deleted file mode 100644 index 04b3803d16..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-configurationtemplate_sourceconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkConfigurationTemplate_SourceConfiguration AWS CloudFormation Resource (AWS::ElasticBeanstalk::ConfigurationTemplate.SourceConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-configurationtemplate-sourceconfiguration.html -type AWSElasticBeanstalkConfigurationTemplate_SourceConfiguration struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-configurationtemplate-sourceconfiguration.html#cfn-beanstalk-configurationtemplate-sourceconfiguration-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // TemplateName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-configurationtemplate-sourceconfiguration.html#cfn-beanstalk-configurationtemplate-sourceconfiguration-templatename - TemplateName string `json:"TemplateName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkConfigurationTemplate_SourceConfiguration) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::ConfigurationTemplate.SourceConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment.go deleted file mode 100644 index ea77b57767..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticBeanstalkEnvironment AWS CloudFormation Resource (AWS::ElasticBeanstalk::Environment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html -type AWSElasticBeanstalkEnvironment struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // CNAMEPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-cnameprefix - CNAMEPrefix string `json:"CNAMEPrefix,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-description - Description string `json:"Description,omitempty"` - - // EnvironmentName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-name - EnvironmentName string `json:"EnvironmentName,omitempty"` - - // OptionSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-optionsettings - OptionSettings []AWSElasticBeanstalkEnvironment_OptionSetting `json:"OptionSettings,omitempty"` - - // PlatformArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-platformarn - PlatformArn string `json:"PlatformArn,omitempty"` - - // SolutionStackName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-solutionstackname - SolutionStackName string `json:"SolutionStackName,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-elasticbeanstalk-environment-tags - Tags []Tag `json:"Tags,omitempty"` - - // TemplateName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-templatename - TemplateName string `json:"TemplateName,omitempty"` - - // Tier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-tier - Tier *AWSElasticBeanstalkEnvironment_Tier `json:"Tier,omitempty"` - - // VersionLabel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment.html#cfn-beanstalk-environment-versionlabel - VersionLabel string `json:"VersionLabel,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkEnvironment) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Environment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticBeanstalkEnvironment) MarshalJSON() ([]byte, error) { - type Properties AWSElasticBeanstalkEnvironment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticBeanstalkEnvironment) UnmarshalJSON(b []byte) error { - type Properties AWSElasticBeanstalkEnvironment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticBeanstalkEnvironment(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticBeanstalkEnvironmentResources retrieves all AWSElasticBeanstalkEnvironment items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticBeanstalkEnvironmentResources() map[string]AWSElasticBeanstalkEnvironment { - results := map[string]AWSElasticBeanstalkEnvironment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticBeanstalkEnvironment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::Environment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkEnvironment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticBeanstalkEnvironmentWithName retrieves all AWSElasticBeanstalkEnvironment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticBeanstalkEnvironmentWithName(name string) (AWSElasticBeanstalkEnvironment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticBeanstalkEnvironment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticBeanstalk::Environment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticBeanstalkEnvironment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticBeanstalkEnvironment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_optionsetting.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_optionsetting.go deleted file mode 100644 index 8079af730c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_optionsetting.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkEnvironment_OptionSetting AWS CloudFormation Resource (AWS::ElasticBeanstalk::Environment.OptionSetting) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html -type AWSElasticBeanstalkEnvironment_OptionSetting struct { - - // Namespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-namespace - Namespace string `json:"Namespace,omitempty"` - - // OptionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-optionname - OptionName string `json:"OptionName,omitempty"` - - // ResourceName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-elasticbeanstalk-environment-optionsetting-resourcename - ResourceName string `json:"ResourceName,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-option-settings.html#cfn-beanstalk-optionsettings-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkEnvironment_OptionSetting) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Environment.OptionSetting" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_tier.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_tier.go deleted file mode 100644 index 87d7fcb0b8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticbeanstalk-environment_tier.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSElasticBeanstalkEnvironment_Tier AWS CloudFormation Resource (AWS::ElasticBeanstalk::Environment.Tier) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment-tier.html -type AWSElasticBeanstalkEnvironment_Tier struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment-tier.html#cfn-beanstalk-env-tier-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment-tier.html#cfn-beanstalk-env-tier-type - Type string `json:"Type,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-environment-tier.html#cfn-beanstalk-env-tier-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticBeanstalkEnvironment_Tier) AWSCloudFormationType() string { - return "AWS::ElasticBeanstalk::Environment.Tier" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer.go deleted file mode 100644 index 73bbed492e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingLoadBalancer AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html -type AWSElasticLoadBalancingLoadBalancer struct { - - // AccessLoggingPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-accessloggingpolicy - AccessLoggingPolicy *AWSElasticLoadBalancingLoadBalancer_AccessLoggingPolicy `json:"AccessLoggingPolicy,omitempty"` - - // AppCookieStickinessPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-appcookiestickinesspolicy - AppCookieStickinessPolicy []AWSElasticLoadBalancingLoadBalancer_AppCookieStickinessPolicy `json:"AppCookieStickinessPolicy,omitempty"` - - // AvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-availabilityzones - AvailabilityZones []string `json:"AvailabilityZones,omitempty"` - - // ConnectionDrainingPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectiondrainingpolicy - ConnectionDrainingPolicy *AWSElasticLoadBalancingLoadBalancer_ConnectionDrainingPolicy `json:"ConnectionDrainingPolicy,omitempty"` - - // ConnectionSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-connectionsettings - ConnectionSettings *AWSElasticLoadBalancingLoadBalancer_ConnectionSettings `json:"ConnectionSettings,omitempty"` - - // CrossZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-crosszone - CrossZone bool `json:"CrossZone,omitempty"` - - // HealthCheck AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-healthcheck - HealthCheck *AWSElasticLoadBalancingLoadBalancer_HealthCheck `json:"HealthCheck,omitempty"` - - // Instances AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-instances - Instances []string `json:"Instances,omitempty"` - - // LBCookieStickinessPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-lbcookiestickinesspolicy - LBCookieStickinessPolicy []AWSElasticLoadBalancingLoadBalancer_LBCookieStickinessPolicy `json:"LBCookieStickinessPolicy,omitempty"` - - // Listeners AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-listeners - Listeners []AWSElasticLoadBalancingLoadBalancer_Listeners `json:"Listeners,omitempty"` - - // LoadBalancerName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-elbname - LoadBalancerName string `json:"LoadBalancerName,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-policies - Policies []AWSElasticLoadBalancingLoadBalancer_Policies `json:"Policies,omitempty"` - - // Scheme AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-scheme - Scheme string `json:"Scheme,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-securitygroups - SecurityGroups []string `json:"SecurityGroups,omitempty"` - - // Subnets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-ec2-elb-subnets - Subnets []string `json:"Subnets,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb.html#cfn-elasticloadbalancing-loadbalancer-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingLoadBalancer) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingLoadBalancer - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingLoadBalancer) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingLoadBalancer - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingLoadBalancer(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingLoadBalancerResources retrieves all AWSElasticLoadBalancingLoadBalancer items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingLoadBalancerResources() map[string]AWSElasticLoadBalancingLoadBalancer { - results := map[string]AWSElasticLoadBalancingLoadBalancer{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingLoadBalancer: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancing::LoadBalancer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingLoadBalancer - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingLoadBalancerWithName retrieves all AWSElasticLoadBalancingLoadBalancer items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingLoadBalancerWithName(name string) (AWSElasticLoadBalancingLoadBalancer, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingLoadBalancer: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancing::LoadBalancer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingLoadBalancer - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingLoadBalancer{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_accessloggingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_accessloggingpolicy.go deleted file mode 100644 index fade970f39..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_accessloggingpolicy.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_AccessLoggingPolicy AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html -type AWSElasticLoadBalancingLoadBalancer_AccessLoggingPolicy struct { - - // EmitInterval AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-emitinterval - EmitInterval int `json:"EmitInterval,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-enabled - Enabled bool `json:"Enabled,omitempty"` - - // S3BucketName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketname - S3BucketName string `json:"S3BucketName,omitempty"` - - // S3BucketPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-accessloggingpolicy.html#cfn-elb-accessloggingpolicy-s3bucketprefix - S3BucketPrefix string `json:"S3BucketPrefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_AccessLoggingPolicy) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.AccessLoggingPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_appcookiestickinesspolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_appcookiestickinesspolicy.go deleted file mode 100644 index b09daef02a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_appcookiestickinesspolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_AppCookieStickinessPolicy AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html -type AWSElasticLoadBalancingLoadBalancer_AppCookieStickinessPolicy struct { - - // CookieName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-cookiename - CookieName string `json:"CookieName,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-AppCookieStickinessPolicy.html#cfn-elb-appcookiestickinesspolicy-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_AppCookieStickinessPolicy) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.AppCookieStickinessPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectiondrainingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectiondrainingpolicy.go deleted file mode 100644 index d3c3acbff7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectiondrainingpolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_ConnectionDrainingPolicy AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html -type AWSElasticLoadBalancingLoadBalancer_ConnectionDrainingPolicy struct { - - // Enabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-enabled - Enabled bool `json:"Enabled,omitempty"` - - // Timeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectiondrainingpolicy.html#cfn-elb-connectiondrainingpolicy-timeout - Timeout int `json:"Timeout,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_ConnectionDrainingPolicy) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.ConnectionDrainingPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectionsettings.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectionsettings.go deleted file mode 100644 index b1e6b03d39..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_connectionsettings.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_ConnectionSettings AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectionsettings.html -type AWSElasticLoadBalancingLoadBalancer_ConnectionSettings struct { - - // IdleTimeout AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-connectionsettings.html#cfn-elb-connectionsettings-idletimeout - IdleTimeout int `json:"IdleTimeout,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_ConnectionSettings) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.ConnectionSettings" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_healthcheck.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_healthcheck.go deleted file mode 100644 index 65cac4cfcb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_healthcheck.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_HealthCheck AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html -type AWSElasticLoadBalancingLoadBalancer_HealthCheck struct { - - // HealthyThreshold AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-healthythreshold - HealthyThreshold string `json:"HealthyThreshold,omitempty"` - - // Interval AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-interval - Interval string `json:"Interval,omitempty"` - - // Target AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-target - Target string `json:"Target,omitempty"` - - // Timeout AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-timeout - Timeout string `json:"Timeout,omitempty"` - - // UnhealthyThreshold AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-health-check.html#cfn-elb-healthcheck-unhealthythreshold - UnhealthyThreshold string `json:"UnhealthyThreshold,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_HealthCheck) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.HealthCheck" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_lbcookiestickinesspolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_lbcookiestickinesspolicy.go deleted file mode 100644 index 51a2860545..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_lbcookiestickinesspolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_LBCookieStickinessPolicy AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html -type AWSElasticLoadBalancingLoadBalancer_LBCookieStickinessPolicy struct { - - // CookieExpirationPeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-cookieexpirationperiod - CookieExpirationPeriod string `json:"CookieExpirationPeriod,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-LBCookieStickinessPolicy.html#cfn-elb-lbcookiestickinesspolicy-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_LBCookieStickinessPolicy) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.LBCookieStickinessPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_listeners.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_listeners.go deleted file mode 100644 index 09b70901e9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_listeners.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_Listeners AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.Listeners) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html -type AWSElasticLoadBalancingLoadBalancer_Listeners struct { - - // InstancePort AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceport - InstancePort string `json:"InstancePort,omitempty"` - - // InstanceProtocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-instanceprotocol - InstanceProtocol string `json:"InstanceProtocol,omitempty"` - - // LoadBalancerPort AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-loadbalancerport - LoadBalancerPort string `json:"LoadBalancerPort,omitempty"` - - // PolicyNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-policynames - PolicyNames []string `json:"PolicyNames,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-protocol - Protocol string `json:"Protocol,omitempty"` - - // SSLCertificateId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-listener.html#cfn-ec2-elb-listener-sslcertificateid - SSLCertificateId string `json:"SSLCertificateId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_Listeners) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.Listeners" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_policies.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_policies.go deleted file mode 100644 index 3590c56fd8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancing-loadbalancer_policies.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingLoadBalancer_Policies AWS CloudFormation Resource (AWS::ElasticLoadBalancing::LoadBalancer.Policies) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html -type AWSElasticLoadBalancingLoadBalancer_Policies struct { - - // Attributes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes - Attributes []interface{} `json:"Attributes,omitempty"` - - // InstancePorts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports - InstancePorts []string `json:"InstancePorts,omitempty"` - - // LoadBalancerPorts AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports - LoadBalancerPorts []string `json:"LoadBalancerPorts,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname - PolicyName string `json:"PolicyName,omitempty"` - - // PolicyType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype - PolicyType string `json:"PolicyType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingLoadBalancer_Policies) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancing::LoadBalancer.Policies" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener.go deleted file mode 100644 index 43f8b21476..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingV2Listener AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::Listener) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html -type AWSElasticLoadBalancingV2Listener struct { - - // Certificates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-certificates - Certificates []AWSElasticLoadBalancingV2Listener_Certificate `json:"Certificates,omitempty"` - - // DefaultActions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-defaultactions - DefaultActions []AWSElasticLoadBalancingV2Listener_Action `json:"DefaultActions,omitempty"` - - // LoadBalancerArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-loadbalancerarn - LoadBalancerArn string `json:"LoadBalancerArn,omitempty"` - - // Port AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-port - Port int `json:"Port,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-protocol - Protocol string `json:"Protocol,omitempty"` - - // SslPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listener.html#cfn-elasticloadbalancingv2-listener-sslpolicy - SslPolicy string `json:"SslPolicy,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2Listener) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::Listener" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingV2Listener) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingV2Listener - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingV2Listener) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingV2Listener - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingV2Listener(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingV2ListenerResources retrieves all AWSElasticLoadBalancingV2Listener items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingV2ListenerResources() map[string]AWSElasticLoadBalancingV2Listener { - results := map[string]AWSElasticLoadBalancingV2Listener{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2Listener: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::Listener" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2Listener - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingV2ListenerWithName retrieves all AWSElasticLoadBalancingV2Listener items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingV2ListenerWithName(name string) (AWSElasticLoadBalancingV2Listener, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2Listener: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::Listener" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2Listener - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingV2Listener{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_action.go deleted file mode 100644 index e90aa58261..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_action.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2Listener_Action AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::Listener.Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-defaultactions.html -type AWSElasticLoadBalancingV2Listener_Action struct { - - // TargetGroupArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-defaultactions.html#cfn-elasticloadbalancingv2-listener-defaultactions-targetgrouparn - TargetGroupArn string `json:"TargetGroupArn,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-defaultactions.html#cfn-elasticloadbalancingv2-listener-defaultactions-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2Listener_Action) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::Listener.Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_certificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_certificate.go deleted file mode 100644 index b7b3351d96..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listener_certificate.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2Listener_Certificate AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::Listener.Certificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-certificates.html -type AWSElasticLoadBalancingV2Listener_Certificate struct { - - // CertificateArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-certificates.html#cfn-elasticloadbalancingv2-listener-certificates-certificatearn - CertificateArn string `json:"CertificateArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2Listener_Certificate) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::Listener.Certificate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate.go deleted file mode 100644 index 25772c288d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingV2ListenerCertificate AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::ListenerCertificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenercertificate.html -type AWSElasticLoadBalancingV2ListenerCertificate struct { - - // Certificates AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenercertificate.html#cfn-elasticloadbalancingv2-listenercertificate-certificates - Certificates []AWSElasticLoadBalancingV2ListenerCertificate_Certificate `json:"Certificates,omitempty"` - - // ListenerArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenercertificate.html#cfn-elasticloadbalancingv2-listenercertificate-listenerarn - ListenerArn string `json:"ListenerArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2ListenerCertificate) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::ListenerCertificate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingV2ListenerCertificate) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingV2ListenerCertificate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingV2ListenerCertificate) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingV2ListenerCertificate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingV2ListenerCertificate(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingV2ListenerCertificateResources retrieves all AWSElasticLoadBalancingV2ListenerCertificate items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingV2ListenerCertificateResources() map[string]AWSElasticLoadBalancingV2ListenerCertificate { - results := map[string]AWSElasticLoadBalancingV2ListenerCertificate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2ListenerCertificate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::ListenerCertificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2ListenerCertificate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingV2ListenerCertificateWithName retrieves all AWSElasticLoadBalancingV2ListenerCertificate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingV2ListenerCertificateWithName(name string) (AWSElasticLoadBalancingV2ListenerCertificate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2ListenerCertificate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::ListenerCertificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2ListenerCertificate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingV2ListenerCertificate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate_certificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate_certificate.go deleted file mode 100644 index c64b2196df..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenercertificate_certificate.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2ListenerCertificate_Certificate AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::ListenerCertificate.Certificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-certificates.html -type AWSElasticLoadBalancingV2ListenerCertificate_Certificate struct { - - // CertificateArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listener-certificates.html#cfn-elasticloadbalancingv2-listener-certificates-certificatearn - CertificateArn string `json:"CertificateArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2ListenerCertificate_Certificate) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::ListenerCertificate.Certificate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule.go deleted file mode 100644 index 0d5bb899c8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingV2ListenerRule AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::ListenerRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html -type AWSElasticLoadBalancingV2ListenerRule struct { - - // Actions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html#cfn-elasticloadbalancingv2-listenerrule-actions - Actions []AWSElasticLoadBalancingV2ListenerRule_Action `json:"Actions,omitempty"` - - // Conditions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html#cfn-elasticloadbalancingv2-listenerrule-conditions - Conditions []AWSElasticLoadBalancingV2ListenerRule_RuleCondition `json:"Conditions,omitempty"` - - // ListenerArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html#cfn-elasticloadbalancingv2-listenerrule-listenerarn - ListenerArn string `json:"ListenerArn,omitempty"` - - // Priority AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-listenerrule.html#cfn-elasticloadbalancingv2-listenerrule-priority - Priority int `json:"Priority,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2ListenerRule) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::ListenerRule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingV2ListenerRule) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingV2ListenerRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingV2ListenerRule) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingV2ListenerRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingV2ListenerRule(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingV2ListenerRuleResources retrieves all AWSElasticLoadBalancingV2ListenerRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingV2ListenerRuleResources() map[string]AWSElasticLoadBalancingV2ListenerRule { - results := map[string]AWSElasticLoadBalancingV2ListenerRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2ListenerRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::ListenerRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2ListenerRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingV2ListenerRuleWithName retrieves all AWSElasticLoadBalancingV2ListenerRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingV2ListenerRuleWithName(name string) (AWSElasticLoadBalancingV2ListenerRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2ListenerRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::ListenerRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2ListenerRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingV2ListenerRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_action.go deleted file mode 100644 index ac9bbd5817..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_action.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2ListenerRule_Action AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::ListenerRule.Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-actions.html -type AWSElasticLoadBalancingV2ListenerRule_Action struct { - - // TargetGroupArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-actions.html#cfn-elasticloadbalancingv2-listener-actions-targetgrouparn - TargetGroupArn string `json:"TargetGroupArn,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-actions.html#cfn-elasticloadbalancingv2-listener-actions-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2ListenerRule_Action) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::ListenerRule.Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_rulecondition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_rulecondition.go deleted file mode 100644 index 0354e6d4bf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-listenerrule_rulecondition.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2ListenerRule_RuleCondition AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::ListenerRule.RuleCondition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-conditions.html -type AWSElasticLoadBalancingV2ListenerRule_RuleCondition struct { - - // Field AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-conditions.html#cfn-elasticloadbalancingv2-listenerrule-conditions-field - Field string `json:"Field,omitempty"` - - // Values AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-listenerrule-conditions.html#cfn-elasticloadbalancingv2-listenerrule-conditions-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2ListenerRule_RuleCondition) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::ListenerRule.RuleCondition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer.go deleted file mode 100644 index 5e942390d4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingV2LoadBalancer AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::LoadBalancer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html -type AWSElasticLoadBalancingV2LoadBalancer struct { - - // IpAddressType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-ipaddresstype - IpAddressType string `json:"IpAddressType,omitempty"` - - // LoadBalancerAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-loadbalancerattributes - LoadBalancerAttributes []AWSElasticLoadBalancingV2LoadBalancer_LoadBalancerAttribute `json:"LoadBalancerAttributes,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-name - Name string `json:"Name,omitempty"` - - // Scheme AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-scheme - Scheme string `json:"Scheme,omitempty"` - - // SecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-securitygroups - SecurityGroups []string `json:"SecurityGroups,omitempty"` - - // SubnetMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-subnetmappings - SubnetMappings []AWSElasticLoadBalancingV2LoadBalancer_SubnetMapping `json:"SubnetMappings,omitempty"` - - // Subnets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-subnets - Subnets []string `json:"Subnets,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-tags - Tags []Tag `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-loadbalancer.html#cfn-elasticloadbalancingv2-loadbalancer-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2LoadBalancer) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::LoadBalancer" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingV2LoadBalancer) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingV2LoadBalancer - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingV2LoadBalancer) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingV2LoadBalancer - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingV2LoadBalancer(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingV2LoadBalancerResources retrieves all AWSElasticLoadBalancingV2LoadBalancer items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingV2LoadBalancerResources() map[string]AWSElasticLoadBalancingV2LoadBalancer { - results := map[string]AWSElasticLoadBalancingV2LoadBalancer{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2LoadBalancer: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::LoadBalancer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2LoadBalancer - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingV2LoadBalancerWithName retrieves all AWSElasticLoadBalancingV2LoadBalancer items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingV2LoadBalancerWithName(name string) (AWSElasticLoadBalancingV2LoadBalancer, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2LoadBalancer: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::LoadBalancer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2LoadBalancer - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingV2LoadBalancer{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_loadbalancerattribute.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_loadbalancerattribute.go deleted file mode 100644 index 4c8c596981..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_loadbalancerattribute.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2LoadBalancer_LoadBalancerAttribute AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::LoadBalancer.LoadBalancerAttribute) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-loadbalancerattributes.html -type AWSElasticLoadBalancingV2LoadBalancer_LoadBalancerAttribute struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-loadbalancerattributes.html#cfn-elasticloadbalancingv2-loadbalancer-loadbalancerattributes-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-loadbalancerattributes.html#cfn-elasticloadbalancingv2-loadbalancer-loadbalancerattributes-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2LoadBalancer_LoadBalancerAttribute) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::LoadBalancer.LoadBalancerAttribute" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_subnetmapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_subnetmapping.go deleted file mode 100644 index fd5294d9da..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-loadbalancer_subnetmapping.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2LoadBalancer_SubnetMapping AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::LoadBalancer.SubnetMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html -type AWSElasticLoadBalancingV2LoadBalancer_SubnetMapping struct { - - // AllocationId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html#cfn-elasticloadbalancingv2-loadbalancer-subnetmapping-allocationid - AllocationId string `json:"AllocationId,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-loadbalancer-subnetmapping.html#cfn-elasticloadbalancingv2-loadbalancer-subnetmapping-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2LoadBalancer_SubnetMapping) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::LoadBalancer.SubnetMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup.go deleted file mode 100644 index 3d96d72c13..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticLoadBalancingV2TargetGroup AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::TargetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html -type AWSElasticLoadBalancingV2TargetGroup struct { - - // HealthCheckIntervalSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthcheckintervalseconds - HealthCheckIntervalSeconds int `json:"HealthCheckIntervalSeconds,omitempty"` - - // HealthCheckPath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthcheckpath - HealthCheckPath string `json:"HealthCheckPath,omitempty"` - - // HealthCheckPort AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthcheckport - HealthCheckPort string `json:"HealthCheckPort,omitempty"` - - // HealthCheckProtocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthcheckprotocol - HealthCheckProtocol string `json:"HealthCheckProtocol,omitempty"` - - // HealthCheckTimeoutSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthchecktimeoutseconds - HealthCheckTimeoutSeconds int `json:"HealthCheckTimeoutSeconds,omitempty"` - - // HealthyThresholdCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-healthythresholdcount - HealthyThresholdCount int `json:"HealthyThresholdCount,omitempty"` - - // Matcher AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-matcher - Matcher *AWSElasticLoadBalancingV2TargetGroup_Matcher `json:"Matcher,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-name - Name string `json:"Name,omitempty"` - - // Port AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-port - Port int `json:"Port,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-protocol - Protocol string `json:"Protocol,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-tags - Tags []Tag `json:"Tags,omitempty"` - - // TargetGroupAttributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-targetgroupattributes - TargetGroupAttributes []AWSElasticLoadBalancingV2TargetGroup_TargetGroupAttribute `json:"TargetGroupAttributes,omitempty"` - - // TargetType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-targettype - TargetType string `json:"TargetType,omitempty"` - - // Targets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-targets - Targets []AWSElasticLoadBalancingV2TargetGroup_TargetDescription `json:"Targets,omitempty"` - - // UnhealthyThresholdCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-unhealthythresholdcount - UnhealthyThresholdCount int `json:"UnhealthyThresholdCount,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticloadbalancingv2-targetgroup.html#cfn-elasticloadbalancingv2-targetgroup-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2TargetGroup) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::TargetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticLoadBalancingV2TargetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSElasticLoadBalancingV2TargetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticLoadBalancingV2TargetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSElasticLoadBalancingV2TargetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticLoadBalancingV2TargetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticLoadBalancingV2TargetGroupResources retrieves all AWSElasticLoadBalancingV2TargetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticLoadBalancingV2TargetGroupResources() map[string]AWSElasticLoadBalancingV2TargetGroup { - results := map[string]AWSElasticLoadBalancingV2TargetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2TargetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::TargetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2TargetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticLoadBalancingV2TargetGroupWithName retrieves all AWSElasticLoadBalancingV2TargetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticLoadBalancingV2TargetGroupWithName(name string) (AWSElasticLoadBalancingV2TargetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticLoadBalancingV2TargetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::ElasticLoadBalancingV2::TargetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticLoadBalancingV2TargetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticLoadBalancingV2TargetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_matcher.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_matcher.go deleted file mode 100644 index a4c709e6bb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_matcher.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2TargetGroup_Matcher AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::TargetGroup.Matcher) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-matcher.html -type AWSElasticLoadBalancingV2TargetGroup_Matcher struct { - - // HttpCode AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-matcher.html#cfn-elasticloadbalancingv2-targetgroup-matcher-httpcode - HttpCode string `json:"HttpCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2TargetGroup_Matcher) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::TargetGroup.Matcher" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetdescription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetdescription.go deleted file mode 100644 index 0f659c025e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetdescription.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2TargetGroup_TargetDescription AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::TargetGroup.TargetDescription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetdescription.html -type AWSElasticLoadBalancingV2TargetGroup_TargetDescription struct { - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetdescription.html#cfn-elasticloadbalancingv2-targetgroup-targetdescription-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetdescription.html#cfn-elasticloadbalancingv2-targetgroup-targetdescription-id - Id string `json:"Id,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetdescription.html#cfn-elasticloadbalancingv2-targetgroup-targetdescription-port - Port int `json:"Port,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2TargetGroup_TargetDescription) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::TargetGroup.TargetDescription" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetgroupattribute.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetgroupattribute.go deleted file mode 100644 index 7b04252f71..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticloadbalancingv2-targetgroup_targetgroupattribute.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSElasticLoadBalancingV2TargetGroup_TargetGroupAttribute AWS CloudFormation Resource (AWS::ElasticLoadBalancingV2::TargetGroup.TargetGroupAttribute) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetgroupattribute.html -type AWSElasticLoadBalancingV2TargetGroup_TargetGroupAttribute struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetgroupattribute.html#cfn-elasticloadbalancingv2-targetgroup-targetgroupattribute-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticloadbalancingv2-targetgroup-targetgroupattribute.html#cfn-elasticloadbalancingv2-targetgroup-targetgroupattribute-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticLoadBalancingV2TargetGroup_TargetGroupAttribute) AWSCloudFormationType() string { - return "AWS::ElasticLoadBalancingV2::TargetGroup.TargetGroupAttribute" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain.go deleted file mode 100644 index c70063d03a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain.go +++ /dev/null @@ -1,145 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSElasticsearchDomain AWS CloudFormation Resource (AWS::Elasticsearch::Domain) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html -type AWSElasticsearchDomain struct { - - // AccessPolicies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-accesspolicies - AccessPolicies interface{} `json:"AccessPolicies,omitempty"` - - // AdvancedOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-advancedoptions - AdvancedOptions map[string]string `json:"AdvancedOptions,omitempty"` - - // DomainName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-domainname - DomainName string `json:"DomainName,omitempty"` - - // EBSOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-ebsoptions - EBSOptions *AWSElasticsearchDomain_EBSOptions `json:"EBSOptions,omitempty"` - - // ElasticsearchClusterConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-elasticsearchclusterconfig - ElasticsearchClusterConfig *AWSElasticsearchDomain_ElasticsearchClusterConfig `json:"ElasticsearchClusterConfig,omitempty"` - - // ElasticsearchVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-elasticsearchversion - ElasticsearchVersion string `json:"ElasticsearchVersion,omitempty"` - - // SnapshotOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-snapshotoptions - SnapshotOptions *AWSElasticsearchDomain_SnapshotOptions `json:"SnapshotOptions,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticsearch-domain.html#cfn-elasticsearch-domain-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticsearchDomain) AWSCloudFormationType() string { - return "AWS::Elasticsearch::Domain" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSElasticsearchDomain) MarshalJSON() ([]byte, error) { - type Properties AWSElasticsearchDomain - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSElasticsearchDomain) UnmarshalJSON(b []byte) error { - type Properties AWSElasticsearchDomain - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSElasticsearchDomain(*res.Properties) - } - - return nil -} - -// GetAllAWSElasticsearchDomainResources retrieves all AWSElasticsearchDomain items from an AWS CloudFormation template -func (t *Template) GetAllAWSElasticsearchDomainResources() map[string]AWSElasticsearchDomain { - results := map[string]AWSElasticsearchDomain{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSElasticsearchDomain: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Elasticsearch::Domain" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticsearchDomain - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSElasticsearchDomainWithName retrieves all AWSElasticsearchDomain items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSElasticsearchDomainWithName(name string) (AWSElasticsearchDomain, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSElasticsearchDomain: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Elasticsearch::Domain" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSElasticsearchDomain - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSElasticsearchDomain{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_ebsoptions.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_ebsoptions.go deleted file mode 100644 index 9f82863443..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_ebsoptions.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSElasticsearchDomain_EBSOptions AWS CloudFormation Resource (AWS::Elasticsearch::Domain.EBSOptions) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-ebsoptions.html -type AWSElasticsearchDomain_EBSOptions struct { - - // EBSEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-ebsoptions.html#cfn-elasticsearch-domain-ebsoptions-ebsenabled - EBSEnabled bool `json:"EBSEnabled,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-ebsoptions.html#cfn-elasticsearch-domain-ebsoptions-iops - Iops int `json:"Iops,omitempty"` - - // VolumeSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-ebsoptions.html#cfn-elasticsearch-domain-ebsoptions-volumesize - VolumeSize int `json:"VolumeSize,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-ebsoptions.html#cfn-elasticsearch-domain-ebsoptions-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticsearchDomain_EBSOptions) AWSCloudFormationType() string { - return "AWS::Elasticsearch::Domain.EBSOptions" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_elasticsearchclusterconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_elasticsearchclusterconfig.go deleted file mode 100644 index b20cc89882..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_elasticsearchclusterconfig.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSElasticsearchDomain_ElasticsearchClusterConfig AWS CloudFormation Resource (AWS::Elasticsearch::Domain.ElasticsearchClusterConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html -type AWSElasticsearchDomain_ElasticsearchClusterConfig struct { - - // DedicatedMasterCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-dedicatedmastercount - DedicatedMasterCount int `json:"DedicatedMasterCount,omitempty"` - - // DedicatedMasterEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-dedicatedmasterenabled - DedicatedMasterEnabled bool `json:"DedicatedMasterEnabled,omitempty"` - - // DedicatedMasterType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-dedicatedmastertype - DedicatedMasterType string `json:"DedicatedMasterType,omitempty"` - - // InstanceCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-instancecount - InstanceCount int `json:"InstanceCount,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-instnacetype - InstanceType string `json:"InstanceType,omitempty"` - - // ZoneAwarenessEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-elasticsearchclusterconfig.html#cfn-elasticsearch-domain-elasticseachclusterconfig-zoneawarenessenabled - ZoneAwarenessEnabled bool `json:"ZoneAwarenessEnabled,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticsearchDomain_ElasticsearchClusterConfig) AWSCloudFormationType() string { - return "AWS::Elasticsearch::Domain.ElasticsearchClusterConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_snapshotoptions.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_snapshotoptions.go deleted file mode 100644 index 5ea4554fce..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-elasticsearch-domain_snapshotoptions.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSElasticsearchDomain_SnapshotOptions AWS CloudFormation Resource (AWS::Elasticsearch::Domain.SnapshotOptions) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-snapshotoptions.html -type AWSElasticsearchDomain_SnapshotOptions struct { - - // AutomatedSnapshotStartHour AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticsearch-domain-snapshotoptions.html#cfn-elasticsearch-domain-snapshotoptions-automatedsnapshotstarthour - AutomatedSnapshotStartHour int `json:"AutomatedSnapshotStartHour,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSElasticsearchDomain_SnapshotOptions) AWSCloudFormationType() string { - return "AWS::Elasticsearch::Domain.SnapshotOptions" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster.go deleted file mode 100644 index 48518fbaf4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEMRCluster AWS CloudFormation Resource (AWS::EMR::Cluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html -type AWSEMRCluster struct { - - // AdditionalInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-additionalinfo - AdditionalInfo interface{} `json:"AdditionalInfo,omitempty"` - - // Applications AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-applications - Applications []AWSEMRCluster_Application `json:"Applications,omitempty"` - - // AutoScalingRole AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-autoscalingrole - AutoScalingRole string `json:"AutoScalingRole,omitempty"` - - // BootstrapActions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-bootstrapactions - BootstrapActions []AWSEMRCluster_BootstrapActionConfig `json:"BootstrapActions,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-configurations - Configurations []AWSEMRCluster_Configuration `json:"Configurations,omitempty"` - - // CustomAmiId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-customamiid - CustomAmiId string `json:"CustomAmiId,omitempty"` - - // Instances AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-instances - Instances *AWSEMRCluster_JobFlowInstancesConfig `json:"Instances,omitempty"` - - // JobFlowRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-jobflowrole - JobFlowRole string `json:"JobFlowRole,omitempty"` - - // LogUri AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-loguri - LogUri string `json:"LogUri,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-name - Name string `json:"Name,omitempty"` - - // ReleaseLabel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-releaselabel - ReleaseLabel string `json:"ReleaseLabel,omitempty"` - - // ScaleDownBehavior AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-scaledownbehavior - ScaleDownBehavior string `json:"ScaleDownBehavior,omitempty"` - - // SecurityConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-securityconfiguration - SecurityConfiguration string `json:"SecurityConfiguration,omitempty"` - - // ServiceRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-servicerole - ServiceRole string `json:"ServiceRole,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-tags - Tags []Tag `json:"Tags,omitempty"` - - // VisibleToAllUsers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-cluster.html#cfn-elasticmapreduce-cluster-visibletoallusers - VisibleToAllUsers bool `json:"VisibleToAllUsers,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster) AWSCloudFormationType() string { - return "AWS::EMR::Cluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEMRCluster) MarshalJSON() ([]byte, error) { - type Properties AWSEMRCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEMRCluster) UnmarshalJSON(b []byte) error { - type Properties AWSEMRCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEMRCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSEMRClusterResources retrieves all AWSEMRCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSEMRClusterResources() map[string]AWSEMRCluster { - results := map[string]AWSEMRCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEMRCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEMRClusterWithName retrieves all AWSEMRCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEMRClusterWithName(name string) (AWSEMRCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEMRCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEMRCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_application.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_application.go deleted file mode 100644 index b5807665fa..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_application.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEMRCluster_Application AWS CloudFormation Resource (AWS::EMR::Cluster.Application) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-application.html -type AWSEMRCluster_Application struct { - - // AdditionalInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-application.html#cfn-elasticmapreduce-cluster-application-additionalinfo - AdditionalInfo map[string]string `json:"AdditionalInfo,omitempty"` - - // Args AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-application.html#cfn-elasticmapreduce-cluster-application-args - Args []string `json:"Args,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-application.html#cfn-elasticmapreduce-cluster-application-name - Name string `json:"Name,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-application.html#cfn-elasticmapreduce-cluster-application-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_Application) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.Application" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_autoscalingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_autoscalingpolicy.go deleted file mode 100644 index 20978da3b8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_autoscalingpolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_AutoScalingPolicy AWS CloudFormation Resource (AWS::EMR::Cluster.AutoScalingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-autoscalingpolicy.html -type AWSEMRCluster_AutoScalingPolicy struct { - - // Constraints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-autoscalingpolicy.html#cfn-elasticmapreduce-cluster-autoscalingpolicy-constraints - Constraints *AWSEMRCluster_ScalingConstraints `json:"Constraints,omitempty"` - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-autoscalingpolicy.html#cfn-elasticmapreduce-cluster-autoscalingpolicy-rules - Rules []AWSEMRCluster_ScalingRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_AutoScalingPolicy) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.AutoScalingPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_bootstrapactionconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_bootstrapactionconfig.go deleted file mode 100644 index 6fab14e941..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_bootstrapactionconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_BootstrapActionConfig AWS CloudFormation Resource (AWS::EMR::Cluster.BootstrapActionConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-bootstrapactionconfig.html -type AWSEMRCluster_BootstrapActionConfig struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-bootstrapactionconfig.html#cfn-elasticmapreduce-cluster-bootstrapactionconfig-name - Name string `json:"Name,omitempty"` - - // ScriptBootstrapAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-bootstrapactionconfig.html#cfn-elasticmapreduce-cluster-bootstrapactionconfig-scriptbootstrapaction - ScriptBootstrapAction *AWSEMRCluster_ScriptBootstrapActionConfig `json:"ScriptBootstrapAction,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_BootstrapActionConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.BootstrapActionConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_cloudwatchalarmdefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_cloudwatchalarmdefinition.go deleted file mode 100644 index eaf4552b1b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_cloudwatchalarmdefinition.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSEMRCluster_CloudWatchAlarmDefinition AWS CloudFormation Resource (AWS::EMR::Cluster.CloudWatchAlarmDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html -type AWSEMRCluster_CloudWatchAlarmDefinition struct { - - // ComparisonOperator AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-comparisonoperator - ComparisonOperator string `json:"ComparisonOperator,omitempty"` - - // Dimensions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-dimensions - Dimensions []AWSEMRCluster_MetricDimension `json:"Dimensions,omitempty"` - - // EvaluationPeriods AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-evaluationperiods - EvaluationPeriods int `json:"EvaluationPeriods,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-metricname - MetricName string `json:"MetricName,omitempty"` - - // Namespace AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-namespace - Namespace string `json:"Namespace,omitempty"` - - // Period AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-period - Period int `json:"Period,omitempty"` - - // Statistic AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-statistic - Statistic string `json:"Statistic,omitempty"` - - // Threshold AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-threshold - Threshold float64 `json:"Threshold,omitempty"` - - // Unit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-cluster-cloudwatchalarmdefinition-unit - Unit string `json:"Unit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_CloudWatchAlarmDefinition) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.CloudWatchAlarmDefinition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_configuration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_configuration.go deleted file mode 100644 index 221b0cb695..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_configuration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRCluster_Configuration AWS CloudFormation Resource (AWS::EMR::Cluster.Configuration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-configuration.html -type AWSEMRCluster_Configuration struct { - - // Classification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-configuration.html#cfn-elasticmapreduce-cluster-configuration-classification - Classification string `json:"Classification,omitempty"` - - // ConfigurationProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-configuration.html#cfn-elasticmapreduce-cluster-configuration-configurationproperties - ConfigurationProperties map[string]string `json:"ConfigurationProperties,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-configuration.html#cfn-elasticmapreduce-cluster-configuration-configurations - Configurations []AWSEMRCluster_Configuration `json:"Configurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_Configuration) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.Configuration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsblockdeviceconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsblockdeviceconfig.go deleted file mode 100644 index b4208b9911..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsblockdeviceconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_EbsBlockDeviceConfig AWS CloudFormation Resource (AWS::EMR::Cluster.EbsBlockDeviceConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsblockdeviceconfig.html -type AWSEMRCluster_EbsBlockDeviceConfig struct { - - // VolumeSpecification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsblockdeviceconfig.html#cfn-elasticmapreduce-cluster-ebsblockdeviceconfig-volumespecification - VolumeSpecification *AWSEMRCluster_VolumeSpecification `json:"VolumeSpecification,omitempty"` - - // VolumesPerInstance AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsblockdeviceconfig.html#cfn-elasticmapreduce-cluster-ebsblockdeviceconfig-volumesperinstance - VolumesPerInstance int `json:"VolumesPerInstance,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_EbsBlockDeviceConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.EbsBlockDeviceConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsconfiguration.go deleted file mode 100644 index 6553a14053..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_ebsconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_EbsConfiguration AWS CloudFormation Resource (AWS::EMR::Cluster.EbsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html -type AWSEMRCluster_EbsConfiguration struct { - - // EbsBlockDeviceConfigs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html#cfn-elasticmapreduce-cluster-ebsconfiguration-ebsblockdeviceconfigs - EbsBlockDeviceConfigs []AWSEMRCluster_EbsBlockDeviceConfig `json:"EbsBlockDeviceConfigs,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-ebsconfiguration.html#cfn-elasticmapreduce-cluster-ebsconfiguration-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_EbsConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.EbsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetconfig.go deleted file mode 100644 index 9ebb006cbc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetconfig.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSEMRCluster_InstanceFleetConfig AWS CloudFormation Resource (AWS::EMR::Cluster.InstanceFleetConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html -type AWSEMRCluster_InstanceFleetConfig struct { - - // InstanceTypeConfigs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html#cfn-elasticmapreduce-cluster-instancefleetconfig-instancetypeconfigs - InstanceTypeConfigs []AWSEMRCluster_InstanceTypeConfig `json:"InstanceTypeConfigs,omitempty"` - - // LaunchSpecifications AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html#cfn-elasticmapreduce-cluster-instancefleetconfig-launchspecifications - LaunchSpecifications *AWSEMRCluster_InstanceFleetProvisioningSpecifications `json:"LaunchSpecifications,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html#cfn-elasticmapreduce-cluster-instancefleetconfig-name - Name string `json:"Name,omitempty"` - - // TargetOnDemandCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html#cfn-elasticmapreduce-cluster-instancefleetconfig-targetondemandcapacity - TargetOnDemandCapacity int `json:"TargetOnDemandCapacity,omitempty"` - - // TargetSpotCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetconfig.html#cfn-elasticmapreduce-cluster-instancefleetconfig-targetspotcapacity - TargetSpotCapacity int `json:"TargetSpotCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_InstanceFleetConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.InstanceFleetConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetprovisioningspecifications.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetprovisioningspecifications.go deleted file mode 100644 index 63367ba59c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancefleetprovisioningspecifications.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEMRCluster_InstanceFleetProvisioningSpecifications AWS CloudFormation Resource (AWS::EMR::Cluster.InstanceFleetProvisioningSpecifications) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetprovisioningspecifications.html -type AWSEMRCluster_InstanceFleetProvisioningSpecifications struct { - - // SpotSpecification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancefleetprovisioningspecifications.html#cfn-elasticmapreduce-cluster-instancefleetprovisioningspecifications-spotspecification - SpotSpecification *AWSEMRCluster_SpotProvisioningSpecification `json:"SpotSpecification,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_InstanceFleetProvisioningSpecifications) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.InstanceFleetProvisioningSpecifications" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancegroupconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancegroupconfig.go deleted file mode 100644 index d63bd2dedb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancegroupconfig.go +++ /dev/null @@ -1,51 +0,0 @@ -package cloudformation - -// AWSEMRCluster_InstanceGroupConfig AWS CloudFormation Resource (AWS::EMR::Cluster.InstanceGroupConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html -type AWSEMRCluster_InstanceGroupConfig struct { - - // AutoScalingPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-autoscalingpolicy - AutoScalingPolicy *AWSEMRCluster_AutoScalingPolicy `json:"AutoScalingPolicy,omitempty"` - - // BidPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-bidprice - BidPrice string `json:"BidPrice,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-configurations - Configurations []AWSEMRCluster_Configuration `json:"Configurations,omitempty"` - - // EbsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-ebsconfiguration - EbsConfiguration *AWSEMRCluster_EbsConfiguration `json:"EbsConfiguration,omitempty"` - - // InstanceCount AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-instancecount - InstanceCount int `json:"InstanceCount,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // Market AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-market - Market string `json:"Market,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancegroupconfig.html#cfn-elasticmapreduce-cluster-instancegroupconfig-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_InstanceGroupConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.InstanceGroupConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancetypeconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancetypeconfig.go deleted file mode 100644 index 9a79cc4cf0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_instancetypeconfig.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSEMRCluster_InstanceTypeConfig AWS CloudFormation Resource (AWS::EMR::Cluster.InstanceTypeConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html -type AWSEMRCluster_InstanceTypeConfig struct { - - // BidPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-bidprice - BidPrice string `json:"BidPrice,omitempty"` - - // BidPriceAsPercentageOfOnDemandPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-bidpriceaspercentageofondemandprice - BidPriceAsPercentageOfOnDemandPrice float64 `json:"BidPriceAsPercentageOfOnDemandPrice,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-configurations - Configurations []AWSEMRCluster_Configuration `json:"Configurations,omitempty"` - - // EbsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-ebsconfiguration - EbsConfiguration *AWSEMRCluster_EbsConfiguration `json:"EbsConfiguration,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // WeightedCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-instancetypeconfig.html#cfn-elasticmapreduce-cluster-instancetypeconfig-weightedcapacity - WeightedCapacity int `json:"WeightedCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_InstanceTypeConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.InstanceTypeConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_jobflowinstancesconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_jobflowinstancesconfig.go deleted file mode 100644 index 5dc76527ae..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_jobflowinstancesconfig.go +++ /dev/null @@ -1,81 +0,0 @@ -package cloudformation - -// AWSEMRCluster_JobFlowInstancesConfig AWS CloudFormation Resource (AWS::EMR::Cluster.JobFlowInstancesConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html -type AWSEMRCluster_JobFlowInstancesConfig struct { - - // AdditionalMasterSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-additionalmastersecuritygroups - AdditionalMasterSecurityGroups []string `json:"AdditionalMasterSecurityGroups,omitempty"` - - // AdditionalSlaveSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-additionalslavesecuritygroups - AdditionalSlaveSecurityGroups []string `json:"AdditionalSlaveSecurityGroups,omitempty"` - - // CoreInstanceFleet AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-coreinstancefleet - CoreInstanceFleet *AWSEMRCluster_InstanceFleetConfig `json:"CoreInstanceFleet,omitempty"` - - // CoreInstanceGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-coreinstancegroup - CoreInstanceGroup *AWSEMRCluster_InstanceGroupConfig `json:"CoreInstanceGroup,omitempty"` - - // Ec2KeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-ec2keyname - Ec2KeyName string `json:"Ec2KeyName,omitempty"` - - // Ec2SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-ec2subnetid - Ec2SubnetId string `json:"Ec2SubnetId,omitempty"` - - // EmrManagedMasterSecurityGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-emrmanagedmastersecuritygroup - EmrManagedMasterSecurityGroup string `json:"EmrManagedMasterSecurityGroup,omitempty"` - - // EmrManagedSlaveSecurityGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-emrmanagedslavesecuritygroup - EmrManagedSlaveSecurityGroup string `json:"EmrManagedSlaveSecurityGroup,omitempty"` - - // HadoopVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-hadoopversion - HadoopVersion string `json:"HadoopVersion,omitempty"` - - // MasterInstanceFleet AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-masterinstancefleet - MasterInstanceFleet *AWSEMRCluster_InstanceFleetConfig `json:"MasterInstanceFleet,omitempty"` - - // MasterInstanceGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-masterinstancegroup - MasterInstanceGroup *AWSEMRCluster_InstanceGroupConfig `json:"MasterInstanceGroup,omitempty"` - - // Placement AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-placement - Placement *AWSEMRCluster_PlacementType `json:"Placement,omitempty"` - - // ServiceAccessSecurityGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-serviceaccesssecuritygroup - ServiceAccessSecurityGroup string `json:"ServiceAccessSecurityGroup,omitempty"` - - // TerminationProtected AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-jobflowinstancesconfig.html#cfn-elasticmapreduce-cluster-jobflowinstancesconfig-terminationprotected - TerminationProtected bool `json:"TerminationProtected,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_JobFlowInstancesConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.JobFlowInstancesConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_metricdimension.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_metricdimension.go deleted file mode 100644 index 994caaddd1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_metricdimension.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_MetricDimension AWS CloudFormation Resource (AWS::EMR::Cluster.MetricDimension) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-metricdimension.html -type AWSEMRCluster_MetricDimension struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-metricdimension.html#cfn-elasticmapreduce-cluster-metricdimension-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-metricdimension.html#cfn-elasticmapreduce-cluster-metricdimension-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_MetricDimension) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.MetricDimension" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_placementtype.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_placementtype.go deleted file mode 100644 index 21cd6a5cbc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_placementtype.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEMRCluster_PlacementType AWS CloudFormation Resource (AWS::EMR::Cluster.PlacementType) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-placementtype.html -type AWSEMRCluster_PlacementType struct { - - // AvailabilityZone AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-placementtype.html#cfn-elasticmapreduce-cluster-placementtype-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_PlacementType) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.PlacementType" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingaction.go deleted file mode 100644 index 022110c8da..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingaction.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_ScalingAction AWS CloudFormation Resource (AWS::EMR::Cluster.ScalingAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingaction.html -type AWSEMRCluster_ScalingAction struct { - - // Market AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingaction.html#cfn-elasticmapreduce-cluster-scalingaction-market - Market string `json:"Market,omitempty"` - - // SimpleScalingPolicyConfiguration AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingaction.html#cfn-elasticmapreduce-cluster-scalingaction-simplescalingpolicyconfiguration - SimpleScalingPolicyConfiguration *AWSEMRCluster_SimpleScalingPolicyConfiguration `json:"SimpleScalingPolicyConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_ScalingAction) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.ScalingAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingconstraints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingconstraints.go deleted file mode 100644 index ce81b1308e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingconstraints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_ScalingConstraints AWS CloudFormation Resource (AWS::EMR::Cluster.ScalingConstraints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingconstraints.html -type AWSEMRCluster_ScalingConstraints struct { - - // MaxCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingconstraints.html#cfn-elasticmapreduce-cluster-scalingconstraints-maxcapacity - MaxCapacity int `json:"MaxCapacity,omitempty"` - - // MinCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingconstraints.html#cfn-elasticmapreduce-cluster-scalingconstraints-mincapacity - MinCapacity int `json:"MinCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_ScalingConstraints) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.ScalingConstraints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingrule.go deleted file mode 100644 index 26633e85c5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingrule.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEMRCluster_ScalingRule AWS CloudFormation Resource (AWS::EMR::Cluster.ScalingRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingrule.html -type AWSEMRCluster_ScalingRule struct { - - // Action AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingrule.html#cfn-elasticmapreduce-cluster-scalingrule-action - Action *AWSEMRCluster_ScalingAction `json:"Action,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingrule.html#cfn-elasticmapreduce-cluster-scalingrule-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingrule.html#cfn-elasticmapreduce-cluster-scalingrule-name - Name string `json:"Name,omitempty"` - - // Trigger AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingrule.html#cfn-elasticmapreduce-cluster-scalingrule-trigger - Trigger *AWSEMRCluster_ScalingTrigger `json:"Trigger,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_ScalingRule) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.ScalingRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingtrigger.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingtrigger.go deleted file mode 100644 index 0d09c5b5b3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scalingtrigger.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEMRCluster_ScalingTrigger AWS CloudFormation Resource (AWS::EMR::Cluster.ScalingTrigger) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingtrigger.html -type AWSEMRCluster_ScalingTrigger struct { - - // CloudWatchAlarmDefinition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scalingtrigger.html#cfn-elasticmapreduce-cluster-scalingtrigger-cloudwatchalarmdefinition - CloudWatchAlarmDefinition *AWSEMRCluster_CloudWatchAlarmDefinition `json:"CloudWatchAlarmDefinition,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_ScalingTrigger) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.ScalingTrigger" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scriptbootstrapactionconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scriptbootstrapactionconfig.go deleted file mode 100644 index 0793b0909e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_scriptbootstrapactionconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRCluster_ScriptBootstrapActionConfig AWS CloudFormation Resource (AWS::EMR::Cluster.ScriptBootstrapActionConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html -type AWSEMRCluster_ScriptBootstrapActionConfig struct { - - // Args AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html#cfn-elasticmapreduce-cluster-scriptbootstrapactionconfig-args - Args []string `json:"Args,omitempty"` - - // Path AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-scriptbootstrapactionconfig.html#cfn-elasticmapreduce-cluster-scriptbootstrapactionconfig-path - Path string `json:"Path,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_ScriptBootstrapActionConfig) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.ScriptBootstrapActionConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_simplescalingpolicyconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_simplescalingpolicyconfiguration.go deleted file mode 100644 index 9dd11dae49..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_simplescalingpolicyconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRCluster_SimpleScalingPolicyConfiguration AWS CloudFormation Resource (AWS::EMR::Cluster.SimpleScalingPolicyConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-simplescalingpolicyconfiguration.html -type AWSEMRCluster_SimpleScalingPolicyConfiguration struct { - - // AdjustmentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-cluster-simplescalingpolicyconfiguration-adjustmenttype - AdjustmentType string `json:"AdjustmentType,omitempty"` - - // CoolDown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-cluster-simplescalingpolicyconfiguration-cooldown - CoolDown int `json:"CoolDown,omitempty"` - - // ScalingAdjustment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-cluster-simplescalingpolicyconfiguration-scalingadjustment - ScalingAdjustment int `json:"ScalingAdjustment,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_SimpleScalingPolicyConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.SimpleScalingPolicyConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_spotprovisioningspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_spotprovisioningspecification.go deleted file mode 100644 index a70ba797e0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_spotprovisioningspecification.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRCluster_SpotProvisioningSpecification AWS CloudFormation Resource (AWS::EMR::Cluster.SpotProvisioningSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-spotprovisioningspecification.html -type AWSEMRCluster_SpotProvisioningSpecification struct { - - // BlockDurationMinutes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-spotprovisioningspecification.html#cfn-elasticmapreduce-cluster-spotprovisioningspecification-blockdurationminutes - BlockDurationMinutes int `json:"BlockDurationMinutes,omitempty"` - - // TimeoutAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-spotprovisioningspecification.html#cfn-elasticmapreduce-cluster-spotprovisioningspecification-timeoutaction - TimeoutAction string `json:"TimeoutAction,omitempty"` - - // TimeoutDurationMinutes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-spotprovisioningspecification.html#cfn-elasticmapreduce-cluster-spotprovisioningspecification-timeoutdurationminutes - TimeoutDurationMinutes int `json:"TimeoutDurationMinutes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_SpotProvisioningSpecification) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.SpotProvisioningSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_volumespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_volumespecification.go deleted file mode 100644 index 6952dac149..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-cluster_volumespecification.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRCluster_VolumeSpecification AWS CloudFormation Resource (AWS::EMR::Cluster.VolumeSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-volumespecification.html -type AWSEMRCluster_VolumeSpecification struct { - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-volumespecification.html#cfn-elasticmapreduce-cluster-volumespecification-iops - Iops int `json:"Iops,omitempty"` - - // SizeInGB AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-volumespecification.html#cfn-elasticmapreduce-cluster-volumespecification-sizeingb - SizeInGB int `json:"SizeInGB,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-cluster-volumespecification.html#cfn-elasticmapreduce-cluster-volumespecification-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRCluster_VolumeSpecification) AWSCloudFormationType() string { - return "AWS::EMR::Cluster.VolumeSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig.go deleted file mode 100644 index 4d8a4a0c01..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEMRInstanceFleetConfig AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html -type AWSEMRInstanceFleetConfig struct { - - // ClusterId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-clusterid - ClusterId string `json:"ClusterId,omitempty"` - - // InstanceFleetType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancefleettype - InstanceFleetType string `json:"InstanceFleetType,omitempty"` - - // InstanceTypeConfigs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfigs - InstanceTypeConfigs []AWSEMRInstanceFleetConfig_InstanceTypeConfig `json:"InstanceTypeConfigs,omitempty"` - - // LaunchSpecifications AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-launchspecifications - LaunchSpecifications *AWSEMRInstanceFleetConfig_InstanceFleetProvisioningSpecifications `json:"LaunchSpecifications,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-name - Name string `json:"Name,omitempty"` - - // TargetOnDemandCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-targetondemandcapacity - TargetOnDemandCapacity int `json:"TargetOnDemandCapacity,omitempty"` - - // TargetSpotCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-elasticmapreduce-instancefleetconfig.html#cfn-elasticmapreduce-instancefleetconfig-targetspotcapacity - TargetSpotCapacity int `json:"TargetSpotCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEMRInstanceFleetConfig) MarshalJSON() ([]byte, error) { - type Properties AWSEMRInstanceFleetConfig - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEMRInstanceFleetConfig) UnmarshalJSON(b []byte) error { - type Properties AWSEMRInstanceFleetConfig - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEMRInstanceFleetConfig(*res.Properties) - } - - return nil -} - -// GetAllAWSEMRInstanceFleetConfigResources retrieves all AWSEMRInstanceFleetConfig items from an AWS CloudFormation template -func (t *Template) GetAllAWSEMRInstanceFleetConfigResources() map[string]AWSEMRInstanceFleetConfig { - results := map[string]AWSEMRInstanceFleetConfig{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEMRInstanceFleetConfig: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::InstanceFleetConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRInstanceFleetConfig - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEMRInstanceFleetConfigWithName retrieves all AWSEMRInstanceFleetConfig items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEMRInstanceFleetConfigWithName(name string) (AWSEMRInstanceFleetConfig, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEMRInstanceFleetConfig: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::InstanceFleetConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRInstanceFleetConfig - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEMRInstanceFleetConfig{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_configuration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_configuration.go deleted file mode 100644 index 7929a72d88..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_configuration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_Configuration AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.Configuration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-configuration.html -type AWSEMRInstanceFleetConfig_Configuration struct { - - // Classification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-configuration.html#cfn-elasticmapreduce-instancefleetconfig-configuration-classification - Classification string `json:"Classification,omitempty"` - - // ConfigurationProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-configuration.html#cfn-elasticmapreduce-instancefleetconfig-configuration-configurationproperties - ConfigurationProperties map[string]string `json:"ConfigurationProperties,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-configuration.html#cfn-elasticmapreduce-instancefleetconfig-configuration-configurations - Configurations []AWSEMRInstanceFleetConfig_Configuration `json:"Configurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_Configuration) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.Configuration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsblockdeviceconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsblockdeviceconfig.go deleted file mode 100644 index aa2b5839b7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsblockdeviceconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_EbsBlockDeviceConfig AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.EbsBlockDeviceConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsblockdeviceconfig.html -type AWSEMRInstanceFleetConfig_EbsBlockDeviceConfig struct { - - // VolumeSpecification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsblockdeviceconfig.html#cfn-elasticmapreduce-instancefleetconfig-ebsblockdeviceconfig-volumespecification - VolumeSpecification *AWSEMRInstanceFleetConfig_VolumeSpecification `json:"VolumeSpecification,omitempty"` - - // VolumesPerInstance AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsblockdeviceconfig.html#cfn-elasticmapreduce-instancefleetconfig-ebsblockdeviceconfig-volumesperinstance - VolumesPerInstance int `json:"VolumesPerInstance,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_EbsBlockDeviceConfig) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.EbsBlockDeviceConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsconfiguration.go deleted file mode 100644 index 4d4179e452..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_ebsconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_EbsConfiguration AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.EbsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsconfiguration.html -type AWSEMRInstanceFleetConfig_EbsConfiguration struct { - - // EbsBlockDeviceConfigs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsconfiguration.html#cfn-elasticmapreduce-instancefleetconfig-ebsconfiguration-ebsblockdeviceconfigs - EbsBlockDeviceConfigs []AWSEMRInstanceFleetConfig_EbsBlockDeviceConfig `json:"EbsBlockDeviceConfigs,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-ebsconfiguration.html#cfn-elasticmapreduce-instancefleetconfig-ebsconfiguration-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_EbsConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.EbsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancefleetprovisioningspecifications.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancefleetprovisioningspecifications.go deleted file mode 100644 index 1195bd58cb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancefleetprovisioningspecifications.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_InstanceFleetProvisioningSpecifications AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.InstanceFleetProvisioningSpecifications) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancefleetprovisioningspecifications.html -type AWSEMRInstanceFleetConfig_InstanceFleetProvisioningSpecifications struct { - - // SpotSpecification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancefleetprovisioningspecifications.html#cfn-elasticmapreduce-instancefleetconfig-instancefleetprovisioningspecifications-spotspecification - SpotSpecification *AWSEMRInstanceFleetConfig_SpotProvisioningSpecification `json:"SpotSpecification,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_InstanceFleetProvisioningSpecifications) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.InstanceFleetProvisioningSpecifications" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancetypeconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancetypeconfig.go deleted file mode 100644 index 93144b004f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_instancetypeconfig.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_InstanceTypeConfig AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.InstanceTypeConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html -type AWSEMRInstanceFleetConfig_InstanceTypeConfig struct { - - // BidPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-bidprice - BidPrice string `json:"BidPrice,omitempty"` - - // BidPriceAsPercentageOfOnDemandPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-bidpriceaspercentageofondemandprice - BidPriceAsPercentageOfOnDemandPrice float64 `json:"BidPriceAsPercentageOfOnDemandPrice,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-configurations - Configurations []AWSEMRInstanceFleetConfig_Configuration `json:"Configurations,omitempty"` - - // EbsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-ebsconfiguration - EbsConfiguration *AWSEMRInstanceFleetConfig_EbsConfiguration `json:"EbsConfiguration,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // WeightedCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-instancetypeconfig.html#cfn-elasticmapreduce-instancefleetconfig-instancetypeconfig-weightedcapacity - WeightedCapacity int `json:"WeightedCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_InstanceTypeConfig) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.InstanceTypeConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_spotprovisioningspecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_spotprovisioningspecification.go deleted file mode 100644 index 502b43c239..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_spotprovisioningspecification.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_SpotProvisioningSpecification AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.SpotProvisioningSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-spotprovisioningspecification.html -type AWSEMRInstanceFleetConfig_SpotProvisioningSpecification struct { - - // BlockDurationMinutes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-spotprovisioningspecification.html#cfn-elasticmapreduce-instancefleetconfig-spotprovisioningspecification-blockdurationminutes - BlockDurationMinutes int `json:"BlockDurationMinutes,omitempty"` - - // TimeoutAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-spotprovisioningspecification.html#cfn-elasticmapreduce-instancefleetconfig-spotprovisioningspecification-timeoutaction - TimeoutAction string `json:"TimeoutAction,omitempty"` - - // TimeoutDurationMinutes AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-spotprovisioningspecification.html#cfn-elasticmapreduce-instancefleetconfig-spotprovisioningspecification-timeoutdurationminutes - TimeoutDurationMinutes int `json:"TimeoutDurationMinutes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_SpotProvisioningSpecification) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.SpotProvisioningSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_volumespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_volumespecification.go deleted file mode 100644 index 17c43f7e33..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancefleetconfig_volumespecification.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceFleetConfig_VolumeSpecification AWS CloudFormation Resource (AWS::EMR::InstanceFleetConfig.VolumeSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-volumespecification.html -type AWSEMRInstanceFleetConfig_VolumeSpecification struct { - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-volumespecification.html#cfn-elasticmapreduce-instancefleetconfig-volumespecification-iops - Iops int `json:"Iops,omitempty"` - - // SizeInGB AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-volumespecification.html#cfn-elasticmapreduce-instancefleetconfig-volumespecification-sizeingb - SizeInGB int `json:"SizeInGB,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancefleetconfig-volumespecification.html#cfn-elasticmapreduce-instancefleetconfig-volumespecification-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceFleetConfig_VolumeSpecification) AWSCloudFormationType() string { - return "AWS::EMR::InstanceFleetConfig.VolumeSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig.go deleted file mode 100644 index cc6fef772c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEMRInstanceGroupConfig AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html -type AWSEMRInstanceGroupConfig struct { - - // AutoScalingPolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-elasticmapreduce-instancegroupconfig-autoscalingpolicy - AutoScalingPolicy *AWSEMRInstanceGroupConfig_AutoScalingPolicy `json:"AutoScalingPolicy,omitempty"` - - // BidPrice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-bidprice - BidPrice string `json:"BidPrice,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-configurations - Configurations []AWSEMRInstanceGroupConfig_Configuration `json:"Configurations,omitempty"` - - // EbsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-ebsconfiguration - EbsConfiguration *AWSEMRInstanceGroupConfig_EbsConfiguration `json:"EbsConfiguration,omitempty"` - - // InstanceCount AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfiginstancecount- - InstanceCount int `json:"InstanceCount,omitempty"` - - // InstanceRole AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-instancerole - InstanceRole string `json:"InstanceRole,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // JobFlowId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-jobflowid - JobFlowId string `json:"JobFlowId,omitempty"` - - // Market AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-market - Market string `json:"Market,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-instancegroupconfig.html#cfn-emr-instancegroupconfig-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEMRInstanceGroupConfig) MarshalJSON() ([]byte, error) { - type Properties AWSEMRInstanceGroupConfig - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEMRInstanceGroupConfig) UnmarshalJSON(b []byte) error { - type Properties AWSEMRInstanceGroupConfig - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEMRInstanceGroupConfig(*res.Properties) - } - - return nil -} - -// GetAllAWSEMRInstanceGroupConfigResources retrieves all AWSEMRInstanceGroupConfig items from an AWS CloudFormation template -func (t *Template) GetAllAWSEMRInstanceGroupConfigResources() map[string]AWSEMRInstanceGroupConfig { - results := map[string]AWSEMRInstanceGroupConfig{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEMRInstanceGroupConfig: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::InstanceGroupConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRInstanceGroupConfig - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEMRInstanceGroupConfigWithName retrieves all AWSEMRInstanceGroupConfig items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEMRInstanceGroupConfigWithName(name string) (AWSEMRInstanceGroupConfig, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEMRInstanceGroupConfig: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::InstanceGroupConfig" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRInstanceGroupConfig - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEMRInstanceGroupConfig{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_autoscalingpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_autoscalingpolicy.go deleted file mode 100644 index 333848f7c0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_autoscalingpolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_AutoScalingPolicy AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.AutoScalingPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-autoscalingpolicy.html -type AWSEMRInstanceGroupConfig_AutoScalingPolicy struct { - - // Constraints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-autoscalingpolicy.html#cfn-elasticmapreduce-instancegroupconfig-autoscalingpolicy-constraints - Constraints *AWSEMRInstanceGroupConfig_ScalingConstraints `json:"Constraints,omitempty"` - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-autoscalingpolicy.html#cfn-elasticmapreduce-instancegroupconfig-autoscalingpolicy-rules - Rules []AWSEMRInstanceGroupConfig_ScalingRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_AutoScalingPolicy) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.AutoScalingPolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_cloudwatchalarmdefinition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_cloudwatchalarmdefinition.go deleted file mode 100644 index 5ea3b4c650..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_cloudwatchalarmdefinition.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_CloudWatchAlarmDefinition AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.CloudWatchAlarmDefinition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html -type AWSEMRInstanceGroupConfig_CloudWatchAlarmDefinition struct { - - // ComparisonOperator AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-comparisonoperator - ComparisonOperator string `json:"ComparisonOperator,omitempty"` - - // Dimensions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-dimensions - Dimensions []AWSEMRInstanceGroupConfig_MetricDimension `json:"Dimensions,omitempty"` - - // EvaluationPeriods AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-evaluationperiods - EvaluationPeriods int `json:"EvaluationPeriods,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-metricname - MetricName string `json:"MetricName,omitempty"` - - // Namespace AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-namespace - Namespace string `json:"Namespace,omitempty"` - - // Period AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-period - Period int `json:"Period,omitempty"` - - // Statistic AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-statistic - Statistic string `json:"Statistic,omitempty"` - - // Threshold AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-threshold - Threshold float64 `json:"Threshold,omitempty"` - - // Unit AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition.html#cfn-elasticmapreduce-instancegroupconfig-cloudwatchalarmdefinition-unit - Unit string `json:"Unit,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_CloudWatchAlarmDefinition) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.CloudWatchAlarmDefinition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_configuration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_configuration.go deleted file mode 100644 index 09b9e52f55..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_configuration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_Configuration AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.Configuration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html -type AWSEMRInstanceGroupConfig_Configuration struct { - - // Classification AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-classification - Classification string `json:"Classification,omitempty"` - - // ConfigurationProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-configurationproperties - ConfigurationProperties map[string]string `json:"ConfigurationProperties,omitempty"` - - // Configurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-cluster-configuration.html#cfn-emr-cluster-configuration-configurations - Configurations []AWSEMRInstanceGroupConfig_Configuration `json:"Configurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_Configuration) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.Configuration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsblockdeviceconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsblockdeviceconfig.go deleted file mode 100644 index 4b3a86cdb6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsblockdeviceconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_EbsBlockDeviceConfig AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.EbsBlockDeviceConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig.html -type AWSEMRInstanceGroupConfig_EbsBlockDeviceConfig struct { - - // VolumeSpecification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification - VolumeSpecification *AWSEMRInstanceGroupConfig_VolumeSpecification `json:"VolumeSpecification,omitempty"` - - // VolumesPerInstance AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumesperinstance - VolumesPerInstance int `json:"VolumesPerInstance,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_EbsBlockDeviceConfig) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.EbsBlockDeviceConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsconfiguration.go deleted file mode 100644 index 6a4983413f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_ebsconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_EbsConfiguration AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.EbsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration.html -type AWSEMRInstanceGroupConfig_EbsConfiguration struct { - - // EbsBlockDeviceConfigs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfigs - EbsBlockDeviceConfigs []AWSEMRInstanceGroupConfig_EbsBlockDeviceConfig `json:"EbsBlockDeviceConfigs,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration.html#cfn-emr-ebsconfiguration-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_EbsConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.EbsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_metricdimension.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_metricdimension.go deleted file mode 100644 index 3407472f41..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_metricdimension.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_MetricDimension AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.MetricDimension) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html -type AWSEMRInstanceGroupConfig_MetricDimension struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html#cfn-elasticmapreduce-instancegroupconfig-metricdimension-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-metricdimension.html#cfn-elasticmapreduce-instancegroupconfig-metricdimension-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_MetricDimension) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.MetricDimension" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingaction.go deleted file mode 100644 index 5160eae470..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingaction.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_ScalingAction AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.ScalingAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html -type AWSEMRInstanceGroupConfig_ScalingAction struct { - - // Market AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-market - Market string `json:"Market,omitempty"` - - // SimpleScalingPolicyConfiguration AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-simplescalingpolicyconfiguration - SimpleScalingPolicyConfiguration *AWSEMRInstanceGroupConfig_SimpleScalingPolicyConfiguration `json:"SimpleScalingPolicyConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_ScalingAction) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.ScalingAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingconstraints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingconstraints.go deleted file mode 100644 index b465b79744..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingconstraints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_ScalingConstraints AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.ScalingConstraints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html -type AWSEMRInstanceGroupConfig_ScalingConstraints struct { - - // MaxCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html#cfn-elasticmapreduce-instancegroupconfig-scalingconstraints-maxcapacity - MaxCapacity int `json:"MaxCapacity,omitempty"` - - // MinCapacity AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingconstraints.html#cfn-elasticmapreduce-instancegroupconfig-scalingconstraints-mincapacity - MinCapacity int `json:"MinCapacity,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_ScalingConstraints) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.ScalingConstraints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingrule.go deleted file mode 100644 index fb3106ac50..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingrule.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_ScalingRule AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.ScalingRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingrule.html -type AWSEMRInstanceGroupConfig_ScalingRule struct { - - // Action AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingrule.html#cfn-elasticmapreduce-instancegroupconfig-scalingrule-action - Action *AWSEMRInstanceGroupConfig_ScalingAction `json:"Action,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingrule.html#cfn-elasticmapreduce-instancegroupconfig-scalingrule-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingrule.html#cfn-elasticmapreduce-instancegroupconfig-scalingrule-name - Name string `json:"Name,omitempty"` - - // Trigger AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingrule.html#cfn-elasticmapreduce-instancegroupconfig-scalingrule-trigger - Trigger *AWSEMRInstanceGroupConfig_ScalingTrigger `json:"Trigger,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_ScalingRule) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.ScalingRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingtrigger.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingtrigger.go deleted file mode 100644 index 4464acdf39..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_scalingtrigger.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_ScalingTrigger AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.ScalingTrigger) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingtrigger.html -type AWSEMRInstanceGroupConfig_ScalingTrigger struct { - - // CloudWatchAlarmDefinition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingtrigger.html#cfn-elasticmapreduce-instancegroupconfig-scalingtrigger-cloudwatchalarmdefinition - CloudWatchAlarmDefinition *AWSEMRInstanceGroupConfig_CloudWatchAlarmDefinition `json:"CloudWatchAlarmDefinition,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_ScalingTrigger) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.ScalingTrigger" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_simplescalingpolicyconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_simplescalingpolicyconfiguration.go deleted file mode 100644 index 2994af6d9d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_simplescalingpolicyconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_SimpleScalingPolicyConfiguration AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html -type AWSEMRInstanceGroupConfig_SimpleScalingPolicyConfiguration struct { - - // AdjustmentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-adjustmenttype - AdjustmentType string `json:"AdjustmentType,omitempty"` - - // CoolDown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-cooldown - CoolDown int `json:"CoolDown,omitempty"` - - // ScalingAdjustment AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration.html#cfn-elasticmapreduce-instancegroupconfig-simplescalingpolicyconfiguration-scalingadjustment - ScalingAdjustment int `json:"ScalingAdjustment,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_SimpleScalingPolicyConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.SimpleScalingPolicyConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_volumespecification.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_volumespecification.go deleted file mode 100644 index 5a229fa8ef..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-instancegroupconfig_volumespecification.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSEMRInstanceGroupConfig_VolumeSpecification AWS CloudFormation Resource (AWS::EMR::InstanceGroupConfig.VolumeSpecification) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html -type AWSEMRInstanceGroupConfig_VolumeSpecification struct { - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-iops - Iops int `json:"Iops,omitempty"` - - // SizeInGB AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-sizeingb - SizeInGB int `json:"SizeInGB,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification.html#cfn-emr-ebsconfiguration-ebsblockdeviceconfig-volumespecification-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRInstanceGroupConfig_VolumeSpecification) AWSCloudFormationType() string { - return "AWS::EMR::InstanceGroupConfig.VolumeSpecification" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-securityconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-securityconfiguration.go deleted file mode 100644 index c55d3f1099..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-securityconfiguration.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEMRSecurityConfiguration AWS CloudFormation Resource (AWS::EMR::SecurityConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-securityconfiguration.html -type AWSEMRSecurityConfiguration struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-securityconfiguration.html#cfn-emr-securityconfiguration-name - Name string `json:"Name,omitempty"` - - // SecurityConfiguration AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-securityconfiguration.html#cfn-emr-securityconfiguration-securityconfiguration - SecurityConfiguration interface{} `json:"SecurityConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRSecurityConfiguration) AWSCloudFormationType() string { - return "AWS::EMR::SecurityConfiguration" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEMRSecurityConfiguration) MarshalJSON() ([]byte, error) { - type Properties AWSEMRSecurityConfiguration - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEMRSecurityConfiguration) UnmarshalJSON(b []byte) error { - type Properties AWSEMRSecurityConfiguration - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEMRSecurityConfiguration(*res.Properties) - } - - return nil -} - -// GetAllAWSEMRSecurityConfigurationResources retrieves all AWSEMRSecurityConfiguration items from an AWS CloudFormation template -func (t *Template) GetAllAWSEMRSecurityConfigurationResources() map[string]AWSEMRSecurityConfiguration { - results := map[string]AWSEMRSecurityConfiguration{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEMRSecurityConfiguration: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::SecurityConfiguration" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRSecurityConfiguration - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEMRSecurityConfigurationWithName retrieves all AWSEMRSecurityConfiguration items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEMRSecurityConfigurationWithName(name string) (AWSEMRSecurityConfiguration, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEMRSecurityConfiguration: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::SecurityConfiguration" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRSecurityConfiguration - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEMRSecurityConfiguration{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step.go deleted file mode 100644 index de329a1614..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEMRStep AWS CloudFormation Resource (AWS::EMR::Step) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html -type AWSEMRStep struct { - - // ActionOnFailure AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-actiononfailure - ActionOnFailure string `json:"ActionOnFailure,omitempty"` - - // HadoopJarStep AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-hadoopjarstep - HadoopJarStep *AWSEMRStep_HadoopJarStepConfig `json:"HadoopJarStep,omitempty"` - - // JobFlowId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-jobflowid - JobFlowId string `json:"JobFlowId,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-emr-step.html#cfn-elasticmapreduce-step-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRStep) AWSCloudFormationType() string { - return "AWS::EMR::Step" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEMRStep) MarshalJSON() ([]byte, error) { - type Properties AWSEMRStep - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEMRStep) UnmarshalJSON(b []byte) error { - type Properties AWSEMRStep - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEMRStep(*res.Properties) - } - - return nil -} - -// GetAllAWSEMRStepResources retrieves all AWSEMRStep items from an AWS CloudFormation template -func (t *Template) GetAllAWSEMRStepResources() map[string]AWSEMRStep { - results := map[string]AWSEMRStep{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEMRStep: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::Step" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRStep - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEMRStepWithName retrieves all AWSEMRStep items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEMRStepWithName(name string) (AWSEMRStep, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEMRStep: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::EMR::Step" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEMRStep - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEMRStep{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_hadoopjarstepconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_hadoopjarstepconfig.go deleted file mode 100644 index 440f0783de..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_hadoopjarstepconfig.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSEMRStep_HadoopJarStepConfig AWS CloudFormation Resource (AWS::EMR::Step.HadoopJarStepConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-hadoopjarstepconfig.html -type AWSEMRStep_HadoopJarStepConfig struct { - - // Args AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-hadoopjarstepconfig.html#cfn-elasticmapreduce-step-hadoopjarstepconfig-args - Args []string `json:"Args,omitempty"` - - // Jar AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-hadoopjarstepconfig.html#cfn-elasticmapreduce-step-hadoopjarstepconfig-jar - Jar string `json:"Jar,omitempty"` - - // MainClass AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-hadoopjarstepconfig.html#cfn-elasticmapreduce-step-hadoopjarstepconfig-mainclass - MainClass string `json:"MainClass,omitempty"` - - // StepProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-hadoopjarstepconfig.html#cfn-elasticmapreduce-step-hadoopjarstepconfig-stepproperties - StepProperties []AWSEMRStep_KeyValue `json:"StepProperties,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRStep_HadoopJarStepConfig) AWSCloudFormationType() string { - return "AWS::EMR::Step.HadoopJarStepConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_keyvalue.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_keyvalue.go deleted file mode 100644 index 0337914824..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-emr-step_keyvalue.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEMRStep_KeyValue AWS CloudFormation Resource (AWS::EMR::Step.KeyValue) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-keyvalue.html -type AWSEMRStep_KeyValue struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-keyvalue.html#cfn-elasticmapreduce-step-keyvalue-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-step-keyvalue.html#cfn-elasticmapreduce-step-keyvalue-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEMRStep_KeyValue) AWSCloudFormationType() string { - return "AWS::EMR::Step.KeyValue" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule.go deleted file mode 100644 index 0881658b4b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSEventsRule AWS CloudFormation Resource (AWS::Events::Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html -type AWSEventsRule struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-description - Description string `json:"Description,omitempty"` - - // EventPattern AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-eventpattern - EventPattern interface{} `json:"EventPattern,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-name - Name string `json:"Name,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // ScheduleExpression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-scheduleexpression - ScheduleExpression string `json:"ScheduleExpression,omitempty"` - - // State AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-state - State string `json:"State,omitempty"` - - // Targets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-events-rule.html#cfn-events-rule-targets - Targets []AWSEventsRule_Target `json:"Targets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule) AWSCloudFormationType() string { - return "AWS::Events::Rule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSEventsRule) MarshalJSON() ([]byte, error) { - type Properties AWSEventsRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSEventsRule) UnmarshalJSON(b []byte) error { - type Properties AWSEventsRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSEventsRule(*res.Properties) - } - - return nil -} - -// GetAllAWSEventsRuleResources retrieves all AWSEventsRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSEventsRuleResources() map[string]AWSEventsRule { - results := map[string]AWSEventsRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSEventsRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Events::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEventsRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSEventsRuleWithName retrieves all AWSEventsRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSEventsRuleWithName(name string) (AWSEventsRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSEventsRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Events::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSEventsRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSEventsRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_ecsparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_ecsparameters.go deleted file mode 100644 index ec3d4f6327..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_ecsparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEventsRule_EcsParameters AWS CloudFormation Resource (AWS::Events::Rule.EcsParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html -type AWSEventsRule_EcsParameters struct { - - // TaskCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-taskcount - TaskCount int `json:"TaskCount,omitempty"` - - // TaskDefinitionArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-ecsparameters.html#cfn-events-rule-ecsparameters-taskdefinitionarn - TaskDefinitionArn string `json:"TaskDefinitionArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_EcsParameters) AWSCloudFormationType() string { - return "AWS::Events::Rule.EcsParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_inputtransformer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_inputtransformer.go deleted file mode 100644 index 722e9c9e96..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_inputtransformer.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEventsRule_InputTransformer AWS CloudFormation Resource (AWS::Events::Rule.InputTransformer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html -type AWSEventsRule_InputTransformer struct { - - // InputPathsMap AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputpathsmap - InputPathsMap map[string]string `json:"InputPathsMap,omitempty"` - - // InputTemplate AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-inputtransformer.html#cfn-events-rule-inputtransformer-inputtemplate - InputTemplate string `json:"InputTemplate,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_InputTransformer) AWSCloudFormationType() string { - return "AWS::Events::Rule.InputTransformer" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_kinesisparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_kinesisparameters.go deleted file mode 100644 index 57a38cc8ec..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_kinesisparameters.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEventsRule_KinesisParameters AWS CloudFormation Resource (AWS::Events::Rule.KinesisParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-kinesisparameters.html -type AWSEventsRule_KinesisParameters struct { - - // PartitionKeyPath AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-kinesisparameters.html#cfn-events-rule-kinesisparameters-partitionkeypath - PartitionKeyPath string `json:"PartitionKeyPath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_KinesisParameters) AWSCloudFormationType() string { - return "AWS::Events::Rule.KinesisParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandparameters.go deleted file mode 100644 index 350e961933..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandparameters.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSEventsRule_RunCommandParameters AWS CloudFormation Resource (AWS::Events::Rule.RunCommandParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandparameters.html -type AWSEventsRule_RunCommandParameters struct { - - // RunCommandTargets AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandparameters.html#cfn-events-rule-runcommandparameters-runcommandtargets - RunCommandTargets []AWSEventsRule_RunCommandTarget `json:"RunCommandTargets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_RunCommandParameters) AWSCloudFormationType() string { - return "AWS::Events::Rule.RunCommandParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandtarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandtarget.go deleted file mode 100644 index 2f78a5853d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_runcommandtarget.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSEventsRule_RunCommandTarget AWS CloudFormation Resource (AWS::Events::Rule.RunCommandTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html -type AWSEventsRule_RunCommandTarget struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html#cfn-events-rule-runcommandtarget-key - Key string `json:"Key,omitempty"` - - // Values AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-runcommandtarget.html#cfn-events-rule-runcommandtarget-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_RunCommandTarget) AWSCloudFormationType() string { - return "AWS::Events::Rule.RunCommandTarget" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_target.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_target.go deleted file mode 100644 index bbbe4db55c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-events-rule_target.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSEventsRule_Target AWS CloudFormation Resource (AWS::Events::Rule.Target) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html -type AWSEventsRule_Target struct { - - // Arn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-arn - Arn string `json:"Arn,omitempty"` - - // EcsParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-ecsparameters - EcsParameters *AWSEventsRule_EcsParameters `json:"EcsParameters,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-id - Id string `json:"Id,omitempty"` - - // Input AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-input - Input string `json:"Input,omitempty"` - - // InputPath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-inputpath - InputPath string `json:"InputPath,omitempty"` - - // InputTransformer AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-inputtransformer - InputTransformer *AWSEventsRule_InputTransformer `json:"InputTransformer,omitempty"` - - // KinesisParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-kinesisparameters - KinesisParameters *AWSEventsRule_KinesisParameters `json:"KinesisParameters,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // RunCommandParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-target.html#cfn-events-rule-target-runcommandparameters - RunCommandParameters *AWSEventsRule_RunCommandParameters `json:"RunCommandParameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSEventsRule_Target) AWSCloudFormationType() string { - return "AWS::Events::Rule.Target" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias.go deleted file mode 100644 index 4778ec029d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGameLiftAlias AWS CloudFormation Resource (AWS::GameLift::Alias) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-alias.html -type AWSGameLiftAlias struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-alias.html#cfn-gamelift-alias-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-alias.html#cfn-gamelift-alias-name - Name string `json:"Name,omitempty"` - - // RoutingStrategy AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-alias.html#cfn-gamelift-alias-routingstrategy - RoutingStrategy *AWSGameLiftAlias_RoutingStrategy `json:"RoutingStrategy,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftAlias) AWSCloudFormationType() string { - return "AWS::GameLift::Alias" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGameLiftAlias) MarshalJSON() ([]byte, error) { - type Properties AWSGameLiftAlias - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGameLiftAlias) UnmarshalJSON(b []byte) error { - type Properties AWSGameLiftAlias - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGameLiftAlias(*res.Properties) - } - - return nil -} - -// GetAllAWSGameLiftAliasResources retrieves all AWSGameLiftAlias items from an AWS CloudFormation template -func (t *Template) GetAllAWSGameLiftAliasResources() map[string]AWSGameLiftAlias { - results := map[string]AWSGameLiftAlias{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGameLiftAlias: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftAlias - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGameLiftAliasWithName retrieves all AWSGameLiftAlias items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGameLiftAliasWithName(name string) (AWSGameLiftAlias, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGameLiftAlias: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftAlias - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGameLiftAlias{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias_routingstrategy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias_routingstrategy.go deleted file mode 100644 index 22b1397094..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-alias_routingstrategy.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGameLiftAlias_RoutingStrategy AWS CloudFormation Resource (AWS::GameLift::Alias.RoutingStrategy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-alias-routingstrategy.html -type AWSGameLiftAlias_RoutingStrategy struct { - - // FleetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-alias-routingstrategy.html#cfn-gamelift-alias-routingstrategy-fleetid - FleetId string `json:"FleetId,omitempty"` - - // Message AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-alias-routingstrategy.html#cfn-gamelift-alias-routingstrategy-message - Message string `json:"Message,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-alias-routingstrategy.html#cfn-gamelift-alias-routingstrategy-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftAlias_RoutingStrategy) AWSCloudFormationType() string { - return "AWS::GameLift::Alias.RoutingStrategy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build.go deleted file mode 100644 index 2441463d41..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGameLiftBuild AWS CloudFormation Resource (AWS::GameLift::Build) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-build.html -type AWSGameLiftBuild struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-build.html#cfn-gamelift-build-name - Name string `json:"Name,omitempty"` - - // StorageLocation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-build.html#cfn-gamelift-build-storagelocation - StorageLocation *AWSGameLiftBuild_S3Location `json:"StorageLocation,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-build.html#cfn-gamelift-build-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftBuild) AWSCloudFormationType() string { - return "AWS::GameLift::Build" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGameLiftBuild) MarshalJSON() ([]byte, error) { - type Properties AWSGameLiftBuild - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGameLiftBuild) UnmarshalJSON(b []byte) error { - type Properties AWSGameLiftBuild - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGameLiftBuild(*res.Properties) - } - - return nil -} - -// GetAllAWSGameLiftBuildResources retrieves all AWSGameLiftBuild items from an AWS CloudFormation template -func (t *Template) GetAllAWSGameLiftBuildResources() map[string]AWSGameLiftBuild { - results := map[string]AWSGameLiftBuild{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGameLiftBuild: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Build" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftBuild - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGameLiftBuildWithName retrieves all AWSGameLiftBuild items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGameLiftBuildWithName(name string) (AWSGameLiftBuild, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGameLiftBuild: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Build" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftBuild - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGameLiftBuild{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build_s3location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build_s3location.go deleted file mode 100644 index cc53ad7456..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-build_s3location.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGameLiftBuild_S3Location AWS CloudFormation Resource (AWS::GameLift::Build.S3Location) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-build-storagelocation.html -type AWSGameLiftBuild_S3Location struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-build-storagelocation.html#cfn-gamelift-build-storage-bucket - Bucket string `json:"Bucket,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-build-storagelocation.html#cfn-gamelift-build-storage-key - Key string `json:"Key,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-build-storagelocation.html#cfn-gamelift-build-storage-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftBuild_S3Location) AWSCloudFormationType() string { - return "AWS::GameLift::Build.S3Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet.go deleted file mode 100644 index cf013cc09a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGameLiftFleet AWS CloudFormation Resource (AWS::GameLift::Fleet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html -type AWSGameLiftFleet struct { - - // BuildId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-buildid - BuildId string `json:"BuildId,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-description - Description string `json:"Description,omitempty"` - - // DesiredEC2Instances AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-desiredec2instances - DesiredEC2Instances int `json:"DesiredEC2Instances,omitempty"` - - // EC2InboundPermissions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-ec2inboundpermissions - EC2InboundPermissions []AWSGameLiftFleet_IpPermission `json:"EC2InboundPermissions,omitempty"` - - // EC2InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-ec2instancetype - EC2InstanceType string `json:"EC2InstanceType,omitempty"` - - // LogPaths AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-logpaths - LogPaths []string `json:"LogPaths,omitempty"` - - // MaxSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-maxsize - MaxSize int `json:"MaxSize,omitempty"` - - // MinSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-minsize - MinSize int `json:"MinSize,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-name - Name string `json:"Name,omitempty"` - - // ServerLaunchParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-serverlaunchparameters - ServerLaunchParameters string `json:"ServerLaunchParameters,omitempty"` - - // ServerLaunchPath AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-gamelift-fleet.html#cfn-gamelift-fleet-serverlaunchpath - ServerLaunchPath string `json:"ServerLaunchPath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftFleet) AWSCloudFormationType() string { - return "AWS::GameLift::Fleet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGameLiftFleet) MarshalJSON() ([]byte, error) { - type Properties AWSGameLiftFleet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGameLiftFleet) UnmarshalJSON(b []byte) error { - type Properties AWSGameLiftFleet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGameLiftFleet(*res.Properties) - } - - return nil -} - -// GetAllAWSGameLiftFleetResources retrieves all AWSGameLiftFleet items from an AWS CloudFormation template -func (t *Template) GetAllAWSGameLiftFleetResources() map[string]AWSGameLiftFleet { - results := map[string]AWSGameLiftFleet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGameLiftFleet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Fleet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftFleet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGameLiftFleetWithName retrieves all AWSGameLiftFleet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGameLiftFleetWithName(name string) (AWSGameLiftFleet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGameLiftFleet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::GameLift::Fleet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGameLiftFleet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGameLiftFleet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet_ippermission.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet_ippermission.go deleted file mode 100644 index b0f197bb00..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-gamelift-fleet_ippermission.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSGameLiftFleet_IpPermission AWS CloudFormation Resource (AWS::GameLift::Fleet.IpPermission) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html -type AWSGameLiftFleet_IpPermission struct { - - // FromPort AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-fromport - FromPort int `json:"FromPort,omitempty"` - - // IpRange AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-iprange - IpRange string `json:"IpRange,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-protocol - Protocol string `json:"Protocol,omitempty"` - - // ToPort AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-gamelift-fleet-ec2inboundpermission.html#cfn-gamelift-fleet-ec2inboundpermissions-toport - ToPort int `json:"ToPort,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGameLiftFleet_IpPermission) AWSCloudFormationType() string { - return "AWS::GameLift::Fleet.IpPermission" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier.go deleted file mode 100644 index 0e50cf06cc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueClassifier AWS CloudFormation Resource (AWS::Glue::Classifier) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-classifier.html -type AWSGlueClassifier struct { - - // GrokClassifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-classifier.html#cfn-glue-classifier-grokclassifier - GrokClassifier *AWSGlueClassifier_GrokClassifier `json:"GrokClassifier,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueClassifier) AWSCloudFormationType() string { - return "AWS::Glue::Classifier" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueClassifier) MarshalJSON() ([]byte, error) { - type Properties AWSGlueClassifier - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueClassifier) UnmarshalJSON(b []byte) error { - type Properties AWSGlueClassifier - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueClassifier(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueClassifierResources retrieves all AWSGlueClassifier items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueClassifierResources() map[string]AWSGlueClassifier { - results := map[string]AWSGlueClassifier{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueClassifier: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Classifier" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueClassifier - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueClassifierWithName retrieves all AWSGlueClassifier items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueClassifierWithName(name string) (AWSGlueClassifier, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueClassifier: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Classifier" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueClassifier - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueClassifier{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier_grokclassifier.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier_grokclassifier.go deleted file mode 100644 index de13d67f9a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-classifier_grokclassifier.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSGlueClassifier_GrokClassifier AWS CloudFormation Resource (AWS::Glue::Classifier.GrokClassifier) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html -type AWSGlueClassifier_GrokClassifier struct { - - // Classification AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html#cfn-glue-classifier-grokclassifier-classification - Classification string `json:"Classification,omitempty"` - - // CustomPatterns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html#cfn-glue-classifier-grokclassifier-custompatterns - CustomPatterns string `json:"CustomPatterns,omitempty"` - - // GrokPattern AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html#cfn-glue-classifier-grokclassifier-grokpattern - GrokPattern string `json:"GrokPattern,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-classifier-grokclassifier.html#cfn-glue-classifier-grokclassifier-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueClassifier_GrokClassifier) AWSCloudFormationType() string { - return "AWS::Glue::Classifier.GrokClassifier" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection.go deleted file mode 100644 index af57b792d4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueConnection AWS CloudFormation Resource (AWS::Glue::Connection) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-connection.html -type AWSGlueConnection struct { - - // CatalogId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-connection.html#cfn-glue-connection-catalogid - CatalogId string `json:"CatalogId,omitempty"` - - // ConnectionInput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-connection.html#cfn-glue-connection-connectioninput - ConnectionInput *AWSGlueConnection_ConnectionInput `json:"ConnectionInput,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueConnection) AWSCloudFormationType() string { - return "AWS::Glue::Connection" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueConnection) MarshalJSON() ([]byte, error) { - type Properties AWSGlueConnection - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueConnection) UnmarshalJSON(b []byte) error { - type Properties AWSGlueConnection - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueConnection(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueConnectionResources retrieves all AWSGlueConnection items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueConnectionResources() map[string]AWSGlueConnection { - results := map[string]AWSGlueConnection{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueConnection: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Connection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueConnection - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueConnectionWithName retrieves all AWSGlueConnection items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueConnectionWithName(name string) (AWSGlueConnection, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueConnection: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Connection" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueConnection - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueConnection{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_connectioninput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_connectioninput.go deleted file mode 100644 index 2459ea54e5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_connectioninput.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSGlueConnection_ConnectionInput AWS CloudFormation Resource (AWS::Glue::Connection.ConnectionInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html -type AWSGlueConnection_ConnectionInput struct { - - // ConnectionProperties AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-connectionproperties - ConnectionProperties interface{} `json:"ConnectionProperties,omitempty"` - - // ConnectionType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-connectiontype - ConnectionType string `json:"ConnectionType,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-description - Description string `json:"Description,omitempty"` - - // MatchCriteria AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-matchcriteria - MatchCriteria []string `json:"MatchCriteria,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-name - Name string `json:"Name,omitempty"` - - // PhysicalConnectionRequirements AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-connectioninput.html#cfn-glue-connection-connectioninput-physicalconnectionrequirements - PhysicalConnectionRequirements *AWSGlueConnection_PhysicalConnectionRequirements `json:"PhysicalConnectionRequirements,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueConnection_ConnectionInput) AWSCloudFormationType() string { - return "AWS::Glue::Connection.ConnectionInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_physicalconnectionrequirements.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_physicalconnectionrequirements.go deleted file mode 100644 index ccde2455fa..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-connection_physicalconnectionrequirements.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueConnection_PhysicalConnectionRequirements AWS CloudFormation Resource (AWS::Glue::Connection.PhysicalConnectionRequirements) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-physicalconnectionrequirements.html -type AWSGlueConnection_PhysicalConnectionRequirements struct { - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-physicalconnectionrequirements.html#cfn-glue-connection-physicalconnectionrequirements-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // SecurityGroupIdList AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-physicalconnectionrequirements.html#cfn-glue-connection-physicalconnectionrequirements-securitygroupidlist - SecurityGroupIdList []string `json:"SecurityGroupIdList,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-connection-physicalconnectionrequirements.html#cfn-glue-connection-physicalconnectionrequirements-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueConnection_PhysicalConnectionRequirements) AWSCloudFormationType() string { - return "AWS::Glue::Connection.PhysicalConnectionRequirements" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler.go deleted file mode 100644 index b99a1fa4be..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueCrawler AWS CloudFormation Resource (AWS::Glue::Crawler) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html -type AWSGlueCrawler struct { - - // Classifiers AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-classifiers - Classifiers []string `json:"Classifiers,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-name - Name string `json:"Name,omitempty"` - - // Role AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-role - Role string `json:"Role,omitempty"` - - // Schedule AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-schedule - Schedule *AWSGlueCrawler_Schedule `json:"Schedule,omitempty"` - - // SchemaChangePolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-schemachangepolicy - SchemaChangePolicy *AWSGlueCrawler_SchemaChangePolicy `json:"SchemaChangePolicy,omitempty"` - - // TablePrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-tableprefix - TablePrefix string `json:"TablePrefix,omitempty"` - - // Targets AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-crawler.html#cfn-glue-crawler-targets - Targets *AWSGlueCrawler_Targets `json:"Targets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler) AWSCloudFormationType() string { - return "AWS::Glue::Crawler" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueCrawler) MarshalJSON() ([]byte, error) { - type Properties AWSGlueCrawler - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueCrawler) UnmarshalJSON(b []byte) error { - type Properties AWSGlueCrawler - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueCrawler(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueCrawlerResources retrieves all AWSGlueCrawler items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueCrawlerResources() map[string]AWSGlueCrawler { - results := map[string]AWSGlueCrawler{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueCrawler: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Crawler" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueCrawler - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueCrawlerWithName retrieves all AWSGlueCrawler items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueCrawlerWithName(name string) (AWSGlueCrawler, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueCrawler: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Crawler" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueCrawler - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueCrawler{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_jdbctarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_jdbctarget.go deleted file mode 100644 index ec76a9a218..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_jdbctarget.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueCrawler_JdbcTarget AWS CloudFormation Resource (AWS::Glue::Crawler.JdbcTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-jdbctarget.html -type AWSGlueCrawler_JdbcTarget struct { - - // ConnectionName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-jdbctarget.html#cfn-glue-crawler-jdbctarget-connectionname - ConnectionName string `json:"ConnectionName,omitempty"` - - // Exclusions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-jdbctarget.html#cfn-glue-crawler-jdbctarget-exclusions - Exclusions []string `json:"Exclusions,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-jdbctarget.html#cfn-glue-crawler-jdbctarget-path - Path string `json:"Path,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler_JdbcTarget) AWSCloudFormationType() string { - return "AWS::Glue::Crawler.JdbcTarget" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_s3target.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_s3target.go deleted file mode 100644 index 17f6f64664..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_s3target.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueCrawler_S3Target AWS CloudFormation Resource (AWS::Glue::Crawler.S3Target) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-s3target.html -type AWSGlueCrawler_S3Target struct { - - // Exclusions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-s3target.html#cfn-glue-crawler-s3target-exclusions - Exclusions []string `json:"Exclusions,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-s3target.html#cfn-glue-crawler-s3target-path - Path string `json:"Path,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler_S3Target) AWSCloudFormationType() string { - return "AWS::Glue::Crawler.S3Target" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schedule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schedule.go deleted file mode 100644 index cdb30535f7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schedule.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSGlueCrawler_Schedule AWS CloudFormation Resource (AWS::Glue::Crawler.Schedule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-schedule.html -type AWSGlueCrawler_Schedule struct { - - // ScheduleExpression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-schedule.html#cfn-glue-crawler-schedule-scheduleexpression - ScheduleExpression string `json:"ScheduleExpression,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler_Schedule) AWSCloudFormationType() string { - return "AWS::Glue::Crawler.Schedule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schemachangepolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schemachangepolicy.go deleted file mode 100644 index 2c3c04319e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_schemachangepolicy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueCrawler_SchemaChangePolicy AWS CloudFormation Resource (AWS::Glue::Crawler.SchemaChangePolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-schemachangepolicy.html -type AWSGlueCrawler_SchemaChangePolicy struct { - - // DeleteBehavior AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-schemachangepolicy.html#cfn-glue-crawler-schemachangepolicy-deletebehavior - DeleteBehavior string `json:"DeleteBehavior,omitempty"` - - // UpdateBehavior AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-schemachangepolicy.html#cfn-glue-crawler-schemachangepolicy-updatebehavior - UpdateBehavior string `json:"UpdateBehavior,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler_SchemaChangePolicy) AWSCloudFormationType() string { - return "AWS::Glue::Crawler.SchemaChangePolicy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_targets.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_targets.go deleted file mode 100644 index 31adde7891..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-crawler_targets.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueCrawler_Targets AWS CloudFormation Resource (AWS::Glue::Crawler.Targets) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-targets.html -type AWSGlueCrawler_Targets struct { - - // JdbcTargets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-targets.html#cfn-glue-crawler-targets-jdbctargets - JdbcTargets []AWSGlueCrawler_JdbcTarget `json:"JdbcTargets,omitempty"` - - // S3Targets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-crawler-targets.html#cfn-glue-crawler-targets-s3targets - S3Targets []AWSGlueCrawler_S3Target `json:"S3Targets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueCrawler_Targets) AWSCloudFormationType() string { - return "AWS::Glue::Crawler.Targets" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database.go deleted file mode 100644 index c2752bdb29..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueDatabase AWS CloudFormation Resource (AWS::Glue::Database) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-database.html -type AWSGlueDatabase struct { - - // CatalogId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-database.html#cfn-glue-database-catalogid - CatalogId string `json:"CatalogId,omitempty"` - - // DatabaseInput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-database.html#cfn-glue-database-databaseinput - DatabaseInput *AWSGlueDatabase_DatabaseInput `json:"DatabaseInput,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueDatabase) AWSCloudFormationType() string { - return "AWS::Glue::Database" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueDatabase) MarshalJSON() ([]byte, error) { - type Properties AWSGlueDatabase - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueDatabase) UnmarshalJSON(b []byte) error { - type Properties AWSGlueDatabase - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueDatabase(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueDatabaseResources retrieves all AWSGlueDatabase items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueDatabaseResources() map[string]AWSGlueDatabase { - results := map[string]AWSGlueDatabase{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueDatabase: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Database" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueDatabase - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueDatabaseWithName retrieves all AWSGlueDatabase items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueDatabaseWithName(name string) (AWSGlueDatabase, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueDatabase: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Database" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueDatabase - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueDatabase{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database_databaseinput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database_databaseinput.go deleted file mode 100644 index 154331311f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-database_databaseinput.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSGlueDatabase_DatabaseInput AWS CloudFormation Resource (AWS::Glue::Database.DatabaseInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-database-databaseinput.html -type AWSGlueDatabase_DatabaseInput struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-database-databaseinput.html#cfn-glue-database-databaseinput-description - Description string `json:"Description,omitempty"` - - // LocationUri AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-database-databaseinput.html#cfn-glue-database-databaseinput-locationuri - LocationUri string `json:"LocationUri,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-database-databaseinput.html#cfn-glue-database-databaseinput-name - Name string `json:"Name,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-database-databaseinput.html#cfn-glue-database-databaseinput-parameters - Parameters interface{} `json:"Parameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueDatabase_DatabaseInput) AWSCloudFormationType() string { - return "AWS::Glue::Database.DatabaseInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-devendpoint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-devendpoint.go deleted file mode 100644 index 08d5876053..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-devendpoint.go +++ /dev/null @@ -1,145 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueDevEndpoint AWS CloudFormation Resource (AWS::Glue::DevEndpoint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html -type AWSGlueDevEndpoint struct { - - // EndpointName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-endpointname - EndpointName string `json:"EndpointName,omitempty"` - - // ExtraJarsS3Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-extrajarss3path - ExtraJarsS3Path string `json:"ExtraJarsS3Path,omitempty"` - - // ExtraPythonLibsS3Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-extrapythonlibss3path - ExtraPythonLibsS3Path string `json:"ExtraPythonLibsS3Path,omitempty"` - - // NumberOfNodes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-numberofnodes - NumberOfNodes int `json:"NumberOfNodes,omitempty"` - - // PublicKey AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-publickey - PublicKey string `json:"PublicKey,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // SecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-devendpoint.html#cfn-glue-devendpoint-subnetid - SubnetId string `json:"SubnetId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueDevEndpoint) AWSCloudFormationType() string { - return "AWS::Glue::DevEndpoint" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueDevEndpoint) MarshalJSON() ([]byte, error) { - type Properties AWSGlueDevEndpoint - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueDevEndpoint) UnmarshalJSON(b []byte) error { - type Properties AWSGlueDevEndpoint - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueDevEndpoint(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueDevEndpointResources retrieves all AWSGlueDevEndpoint items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueDevEndpointResources() map[string]AWSGlueDevEndpoint { - results := map[string]AWSGlueDevEndpoint{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueDevEndpoint: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::DevEndpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueDevEndpoint - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueDevEndpointWithName retrieves all AWSGlueDevEndpoint items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueDevEndpointWithName(name string) (AWSGlueDevEndpoint, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueDevEndpoint: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::DevEndpoint" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueDevEndpoint - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueDevEndpoint{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job.go deleted file mode 100644 index 83a6431d80..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job.go +++ /dev/null @@ -1,155 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueJob AWS CloudFormation Resource (AWS::Glue::Job) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html -type AWSGlueJob struct { - - // AllocatedCapacity AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-allocatedcapacity - AllocatedCapacity float64 `json:"AllocatedCapacity,omitempty"` - - // Command AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-command - Command *AWSGlueJob_JobCommand `json:"Command,omitempty"` - - // Connections AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-connections - Connections *AWSGlueJob_ConnectionsList `json:"Connections,omitempty"` - - // DefaultArguments AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-defaultarguments - DefaultArguments interface{} `json:"DefaultArguments,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-description - Description string `json:"Description,omitempty"` - - // ExecutionProperty AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-executionproperty - ExecutionProperty *AWSGlueJob_ExecutionProperty `json:"ExecutionProperty,omitempty"` - - // LogUri AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-loguri - LogUri string `json:"LogUri,omitempty"` - - // MaxRetries AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-maxretries - MaxRetries float64 `json:"MaxRetries,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-name - Name string `json:"Name,omitempty"` - - // Role AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-job.html#cfn-glue-job-role - Role string `json:"Role,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueJob) AWSCloudFormationType() string { - return "AWS::Glue::Job" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueJob) MarshalJSON() ([]byte, error) { - type Properties AWSGlueJob - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueJob) UnmarshalJSON(b []byte) error { - type Properties AWSGlueJob - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueJob(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueJobResources retrieves all AWSGlueJob items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueJobResources() map[string]AWSGlueJob { - results := map[string]AWSGlueJob{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueJob: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Job" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueJob - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueJobWithName retrieves all AWSGlueJob items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueJobWithName(name string) (AWSGlueJob, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueJob: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Job" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueJob - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueJob{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_connectionslist.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_connectionslist.go deleted file mode 100644 index 68a03c11b6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_connectionslist.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSGlueJob_ConnectionsList AWS CloudFormation Resource (AWS::Glue::Job.ConnectionsList) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-connectionslist.html -type AWSGlueJob_ConnectionsList struct { - - // Connections AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-connectionslist.html#cfn-glue-job-connectionslist-connections - Connections []string `json:"Connections,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueJob_ConnectionsList) AWSCloudFormationType() string { - return "AWS::Glue::Job.ConnectionsList" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_executionproperty.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_executionproperty.go deleted file mode 100644 index 2bddba7c6d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_executionproperty.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSGlueJob_ExecutionProperty AWS CloudFormation Resource (AWS::Glue::Job.ExecutionProperty) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-executionproperty.html -type AWSGlueJob_ExecutionProperty struct { - - // MaxConcurrentRuns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-executionproperty.html#cfn-glue-job-executionproperty-maxconcurrentruns - MaxConcurrentRuns float64 `json:"MaxConcurrentRuns,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueJob_ExecutionProperty) AWSCloudFormationType() string { - return "AWS::Glue::Job.ExecutionProperty" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_jobcommand.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_jobcommand.go deleted file mode 100644 index 02d5c667bc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-job_jobcommand.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueJob_JobCommand AWS CloudFormation Resource (AWS::Glue::Job.JobCommand) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-jobcommand.html -type AWSGlueJob_JobCommand struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-jobcommand.html#cfn-glue-job-jobcommand-name - Name string `json:"Name,omitempty"` - - // ScriptLocation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-job-jobcommand.html#cfn-glue-job-jobcommand-scriptlocation - ScriptLocation string `json:"ScriptLocation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueJob_JobCommand) AWSCloudFormationType() string { - return "AWS::Glue::Job.JobCommand" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition.go deleted file mode 100644 index 8e5ccfdb58..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGluePartition AWS CloudFormation Resource (AWS::Glue::Partition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-partition.html -type AWSGluePartition struct { - - // CatalogId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-partition.html#cfn-glue-partition-catalogid - CatalogId string `json:"CatalogId,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-partition.html#cfn-glue-partition-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // PartitionInput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-partition.html#cfn-glue-partition-partitioninput - PartitionInput *AWSGluePartition_PartitionInput `json:"PartitionInput,omitempty"` - - // TableName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-partition.html#cfn-glue-partition-tablename - TableName string `json:"TableName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition) AWSCloudFormationType() string { - return "AWS::Glue::Partition" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGluePartition) MarshalJSON() ([]byte, error) { - type Properties AWSGluePartition - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGluePartition) UnmarshalJSON(b []byte) error { - type Properties AWSGluePartition - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGluePartition(*res.Properties) - } - - return nil -} - -// GetAllAWSGluePartitionResources retrieves all AWSGluePartition items from an AWS CloudFormation template -func (t *Template) GetAllAWSGluePartitionResources() map[string]AWSGluePartition { - results := map[string]AWSGluePartition{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGluePartition: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Partition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGluePartition - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGluePartitionWithName retrieves all AWSGluePartition items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGluePartitionWithName(name string) (AWSGluePartition, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGluePartition: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Partition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGluePartition - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGluePartition{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_column.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_column.go deleted file mode 100644 index 7143084010..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_column.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGluePartition_Column AWS CloudFormation Resource (AWS::Glue::Partition.Column) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-column.html -type AWSGluePartition_Column struct { - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-column.html#cfn-glue-partition-column-comment - Comment string `json:"Comment,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-column.html#cfn-glue-partition-column-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-column.html#cfn-glue-partition-column-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_Column) AWSCloudFormationType() string { - return "AWS::Glue::Partition.Column" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_order.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_order.go deleted file mode 100644 index b5fb286e8e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_order.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGluePartition_Order AWS CloudFormation Resource (AWS::Glue::Partition.Order) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-order.html -type AWSGluePartition_Order struct { - - // Column AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-order.html#cfn-glue-partition-order-column - Column string `json:"Column,omitempty"` - - // SortOrder AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-order.html#cfn-glue-partition-order-sortorder - SortOrder int `json:"SortOrder,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_Order) AWSCloudFormationType() string { - return "AWS::Glue::Partition.Order" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_partitioninput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_partitioninput.go deleted file mode 100644 index 70aaf54c6a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_partitioninput.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGluePartition_PartitionInput AWS CloudFormation Resource (AWS::Glue::Partition.PartitionInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html -type AWSGluePartition_PartitionInput struct { - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // StorageDescriptor AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-storagedescriptor - StorageDescriptor *AWSGluePartition_StorageDescriptor `json:"StorageDescriptor,omitempty"` - - // Values AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-partitioninput.html#cfn-glue-partition-partitioninput-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_PartitionInput) AWSCloudFormationType() string { - return "AWS::Glue::Partition.PartitionInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_serdeinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_serdeinfo.go deleted file mode 100644 index 72fe00d2e9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_serdeinfo.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGluePartition_SerdeInfo AWS CloudFormation Resource (AWS::Glue::Partition.SerdeInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-serdeinfo.html -type AWSGluePartition_SerdeInfo struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-serdeinfo.html#cfn-glue-partition-serdeinfo-name - Name string `json:"Name,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-serdeinfo.html#cfn-glue-partition-serdeinfo-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // SerializationLibrary AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-serdeinfo.html#cfn-glue-partition-serdeinfo-serializationlibrary - SerializationLibrary string `json:"SerializationLibrary,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_SerdeInfo) AWSCloudFormationType() string { - return "AWS::Glue::Partition.SerdeInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_skewedinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_skewedinfo.go deleted file mode 100644 index 855ed8758e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_skewedinfo.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGluePartition_SkewedInfo AWS CloudFormation Resource (AWS::Glue::Partition.SkewedInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-skewedinfo.html -type AWSGluePartition_SkewedInfo struct { - - // SkewedColumnNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-skewedinfo.html#cfn-glue-partition-skewedinfo-skewedcolumnnames - SkewedColumnNames []string `json:"SkewedColumnNames,omitempty"` - - // SkewedColumnValueLocationMaps AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-skewedinfo.html#cfn-glue-partition-skewedinfo-skewedcolumnvaluelocationmaps - SkewedColumnValueLocationMaps interface{} `json:"SkewedColumnValueLocationMaps,omitempty"` - - // SkewedColumnValues AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-skewedinfo.html#cfn-glue-partition-skewedinfo-skewedcolumnvalues - SkewedColumnValues []string `json:"SkewedColumnValues,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_SkewedInfo) AWSCloudFormationType() string { - return "AWS::Glue::Partition.SkewedInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_storagedescriptor.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_storagedescriptor.go deleted file mode 100644 index 31598adb08..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-partition_storagedescriptor.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSGluePartition_StorageDescriptor AWS CloudFormation Resource (AWS::Glue::Partition.StorageDescriptor) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html -type AWSGluePartition_StorageDescriptor struct { - - // BucketColumns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-bucketcolumns - BucketColumns []string `json:"BucketColumns,omitempty"` - - // Columns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-columns - Columns []AWSGluePartition_Column `json:"Columns,omitempty"` - - // Compressed AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-compressed - Compressed bool `json:"Compressed,omitempty"` - - // InputFormat AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-inputformat - InputFormat string `json:"InputFormat,omitempty"` - - // Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-location - Location string `json:"Location,omitempty"` - - // NumberOfBuckets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-numberofbuckets - NumberOfBuckets int `json:"NumberOfBuckets,omitempty"` - - // OutputFormat AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-outputformat - OutputFormat string `json:"OutputFormat,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // SerdeInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-serdeinfo - SerdeInfo *AWSGluePartition_SerdeInfo `json:"SerdeInfo,omitempty"` - - // SkewedInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-skewedinfo - SkewedInfo *AWSGluePartition_SkewedInfo `json:"SkewedInfo,omitempty"` - - // SortColumns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-sortcolumns - SortColumns []AWSGluePartition_Order `json:"SortColumns,omitempty"` - - // StoredAsSubDirectories AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-partition-storagedescriptor.html#cfn-glue-partition-storagedescriptor-storedassubdirectories - StoredAsSubDirectories bool `json:"StoredAsSubDirectories,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGluePartition_StorageDescriptor) AWSCloudFormationType() string { - return "AWS::Glue::Partition.StorageDescriptor" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table.go deleted file mode 100644 index 4e43f83055..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueTable AWS CloudFormation Resource (AWS::Glue::Table) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html -type AWSGlueTable struct { - - // CatalogId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html#cfn-glue-table-catalogid - CatalogId string `json:"CatalogId,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html#cfn-glue-table-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // TableInput AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-table.html#cfn-glue-table-tableinput - TableInput *AWSGlueTable_TableInput `json:"TableInput,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable) AWSCloudFormationType() string { - return "AWS::Glue::Table" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueTable) MarshalJSON() ([]byte, error) { - type Properties AWSGlueTable - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueTable) UnmarshalJSON(b []byte) error { - type Properties AWSGlueTable - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueTable(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueTableResources retrieves all AWSGlueTable items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueTableResources() map[string]AWSGlueTable { - results := map[string]AWSGlueTable{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueTable: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Table" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueTable - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueTableWithName retrieves all AWSGlueTable items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueTableWithName(name string) (AWSGlueTable, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueTable: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Table" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueTable - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueTable{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_column.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_column.go deleted file mode 100644 index dfef0af03d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_column.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueTable_Column AWS CloudFormation Resource (AWS::Glue::Table.Column) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-column.html -type AWSGlueTable_Column struct { - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-column.html#cfn-glue-table-column-comment - Comment string `json:"Comment,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-column.html#cfn-glue-table-column-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-column.html#cfn-glue-table-column-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_Column) AWSCloudFormationType() string { - return "AWS::Glue::Table.Column" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_order.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_order.go deleted file mode 100644 index f1785601bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_order.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueTable_Order AWS CloudFormation Resource (AWS::Glue::Table.Order) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-order.html -type AWSGlueTable_Order struct { - - // Column AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-order.html#cfn-glue-table-order-column - Column string `json:"Column,omitempty"` - - // SortOrder AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-order.html#cfn-glue-table-order-sortorder - SortOrder int `json:"SortOrder,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_Order) AWSCloudFormationType() string { - return "AWS::Glue::Table.Order" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_serdeinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_serdeinfo.go deleted file mode 100644 index 23fd1625bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_serdeinfo.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueTable_SerdeInfo AWS CloudFormation Resource (AWS::Glue::Table.SerdeInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-serdeinfo.html -type AWSGlueTable_SerdeInfo struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-serdeinfo.html#cfn-glue-table-serdeinfo-name - Name string `json:"Name,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-serdeinfo.html#cfn-glue-table-serdeinfo-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // SerializationLibrary AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-serdeinfo.html#cfn-glue-table-serdeinfo-serializationlibrary - SerializationLibrary string `json:"SerializationLibrary,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_SerdeInfo) AWSCloudFormationType() string { - return "AWS::Glue::Table.SerdeInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_skewedinfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_skewedinfo.go deleted file mode 100644 index cbea185b52..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_skewedinfo.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueTable_SkewedInfo AWS CloudFormation Resource (AWS::Glue::Table.SkewedInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-skewedinfo.html -type AWSGlueTable_SkewedInfo struct { - - // SkewedColumnNames AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-skewedinfo.html#cfn-glue-table-skewedinfo-skewedcolumnnames - SkewedColumnNames []string `json:"SkewedColumnNames,omitempty"` - - // SkewedColumnValueLocationMaps AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-skewedinfo.html#cfn-glue-table-skewedinfo-skewedcolumnvaluelocationmaps - SkewedColumnValueLocationMaps interface{} `json:"SkewedColumnValueLocationMaps,omitempty"` - - // SkewedColumnValues AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-skewedinfo.html#cfn-glue-table-skewedinfo-skewedcolumnvalues - SkewedColumnValues []string `json:"SkewedColumnValues,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_SkewedInfo) AWSCloudFormationType() string { - return "AWS::Glue::Table.SkewedInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_storagedescriptor.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_storagedescriptor.go deleted file mode 100644 index dd646e25ed..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_storagedescriptor.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSGlueTable_StorageDescriptor AWS CloudFormation Resource (AWS::Glue::Table.StorageDescriptor) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html -type AWSGlueTable_StorageDescriptor struct { - - // BucketColumns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-bucketcolumns - BucketColumns []string `json:"BucketColumns,omitempty"` - - // Columns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-columns - Columns []AWSGlueTable_Column `json:"Columns,omitempty"` - - // Compressed AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-compressed - Compressed bool `json:"Compressed,omitempty"` - - // InputFormat AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-inputformat - InputFormat string `json:"InputFormat,omitempty"` - - // Location AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-location - Location string `json:"Location,omitempty"` - - // NumberOfBuckets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-numberofbuckets - NumberOfBuckets int `json:"NumberOfBuckets,omitempty"` - - // OutputFormat AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-outputformat - OutputFormat string `json:"OutputFormat,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // SerdeInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-serdeinfo - SerdeInfo *AWSGlueTable_SerdeInfo `json:"SerdeInfo,omitempty"` - - // SkewedInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-skewedinfo - SkewedInfo *AWSGlueTable_SkewedInfo `json:"SkewedInfo,omitempty"` - - // SortColumns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-sortcolumns - SortColumns []AWSGlueTable_Order `json:"SortColumns,omitempty"` - - // StoredAsSubDirectories AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-storagedescriptor.html#cfn-glue-table-storagedescriptor-storedassubdirectories - StoredAsSubDirectories bool `json:"StoredAsSubDirectories,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_StorageDescriptor) AWSCloudFormationType() string { - return "AWS::Glue::Table.StorageDescriptor" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_tableinput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_tableinput.go deleted file mode 100644 index 4713807ec0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-table_tableinput.go +++ /dev/null @@ -1,61 +0,0 @@ -package cloudformation - -// AWSGlueTable_TableInput AWS CloudFormation Resource (AWS::Glue::Table.TableInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html -type AWSGlueTable_TableInput struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-name - Name string `json:"Name,omitempty"` - - // Owner AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-owner - Owner string `json:"Owner,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // PartitionKeys AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-partitionkeys - PartitionKeys []AWSGlueTable_Column `json:"PartitionKeys,omitempty"` - - // Retention AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-retention - Retention int `json:"Retention,omitempty"` - - // StorageDescriptor AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-storagedescriptor - StorageDescriptor *AWSGlueTable_StorageDescriptor `json:"StorageDescriptor,omitempty"` - - // TableType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-tabletype - TableType string `json:"TableType,omitempty"` - - // ViewExpandedText AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-viewexpandedtext - ViewExpandedText string `json:"ViewExpandedText,omitempty"` - - // ViewOriginalText AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-table-tableinput.html#cfn-glue-table-tableinput-vieworiginaltext - ViewOriginalText string `json:"ViewOriginalText,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTable_TableInput) AWSCloudFormationType() string { - return "AWS::Glue::Table.TableInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger.go deleted file mode 100644 index 88b0c189ea..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSGlueTrigger AWS CloudFormation Resource (AWS::Glue::Trigger) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html -type AWSGlueTrigger struct { - - // Actions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-actions - Actions []AWSGlueTrigger_Action `json:"Actions,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-name - Name string `json:"Name,omitempty"` - - // Predicate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-predicate - Predicate *AWSGlueTrigger_Predicate `json:"Predicate,omitempty"` - - // Schedule AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-schedule - Schedule string `json:"Schedule,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-glue-trigger.html#cfn-glue-trigger-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTrigger) AWSCloudFormationType() string { - return "AWS::Glue::Trigger" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSGlueTrigger) MarshalJSON() ([]byte, error) { - type Properties AWSGlueTrigger - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSGlueTrigger) UnmarshalJSON(b []byte) error { - type Properties AWSGlueTrigger - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSGlueTrigger(*res.Properties) - } - - return nil -} - -// GetAllAWSGlueTriggerResources retrieves all AWSGlueTrigger items from an AWS CloudFormation template -func (t *Template) GetAllAWSGlueTriggerResources() map[string]AWSGlueTrigger { - results := map[string]AWSGlueTrigger{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSGlueTrigger: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Trigger" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueTrigger - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSGlueTriggerWithName retrieves all AWSGlueTrigger items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSGlueTriggerWithName(name string) (AWSGlueTrigger, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSGlueTrigger: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Glue::Trigger" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSGlueTrigger - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSGlueTrigger{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_action.go deleted file mode 100644 index 693fd0fdc7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_action.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueTrigger_Action AWS CloudFormation Resource (AWS::Glue::Trigger.Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html -type AWSGlueTrigger_Action struct { - - // Arguments AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html#cfn-glue-trigger-action-arguments - Arguments interface{} `json:"Arguments,omitempty"` - - // JobName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-action.html#cfn-glue-trigger-action-jobname - JobName string `json:"JobName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTrigger_Action) AWSCloudFormationType() string { - return "AWS::Glue::Trigger.Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_condition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_condition.go deleted file mode 100644 index 63f812a9e9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_condition.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSGlueTrigger_Condition AWS CloudFormation Resource (AWS::Glue::Trigger.Condition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html -type AWSGlueTrigger_Condition struct { - - // JobName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-jobname - JobName string `json:"JobName,omitempty"` - - // LogicalOperator AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-logicaloperator - LogicalOperator string `json:"LogicalOperator,omitempty"` - - // State AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-state - State string `json:"State,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTrigger_Condition) AWSCloudFormationType() string { - return "AWS::Glue::Trigger.Condition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_predicate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_predicate.go deleted file mode 100644 index 67a13f69ac..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-glue-trigger_predicate.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSGlueTrigger_Predicate AWS CloudFormation Resource (AWS::Glue::Trigger.Predicate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-predicate.html -type AWSGlueTrigger_Predicate struct { - - // Conditions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-predicate.html#cfn-glue-trigger-predicate-conditions - Conditions []AWSGlueTrigger_Condition `json:"Conditions,omitempty"` - - // Logical AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-predicate.html#cfn-glue-trigger-predicate-logical - Logical string `json:"Logical,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSGlueTrigger_Predicate) AWSCloudFormationType() string { - return "AWS::Glue::Trigger.Predicate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-accesskey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-accesskey.go deleted file mode 100644 index 7ece4892ef..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-accesskey.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMAccessKey AWS CloudFormation Resource (AWS::IAM::AccessKey) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html -type AWSIAMAccessKey struct { - - // Serial AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html#cfn-iam-accesskey-serial - Serial int `json:"Serial,omitempty"` - - // Status AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html#cfn-iam-accesskey-status - Status string `json:"Status,omitempty"` - - // UserName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html#cfn-iam-accesskey-username - UserName string `json:"UserName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMAccessKey) AWSCloudFormationType() string { - return "AWS::IAM::AccessKey" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMAccessKey) MarshalJSON() ([]byte, error) { - type Properties AWSIAMAccessKey - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMAccessKey) UnmarshalJSON(b []byte) error { - type Properties AWSIAMAccessKey - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMAccessKey(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMAccessKeyResources retrieves all AWSIAMAccessKey items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMAccessKeyResources() map[string]AWSIAMAccessKey { - results := map[string]AWSIAMAccessKey{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMAccessKey: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::AccessKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMAccessKey - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMAccessKeyWithName retrieves all AWSIAMAccessKey items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMAccessKeyWithName(name string) (AWSIAMAccessKey, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMAccessKey: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::AccessKey" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMAccessKey - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMAccessKey{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group.go deleted file mode 100644 index c5dac8dafe..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMGroup AWS CloudFormation Resource (AWS::IAM::Group) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html -type AWSIAMGroup struct { - - // GroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html#cfn-iam-group-groupname - GroupName string `json:"GroupName,omitempty"` - - // ManagedPolicyArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html#cfn-iam-group-managepolicyarns - ManagedPolicyArns []string `json:"ManagedPolicyArns,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html#cfn-iam-group-path - Path string `json:"Path,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html#cfn-iam-group-policies - Policies []AWSIAMGroup_Policy `json:"Policies,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMGroup) AWSCloudFormationType() string { - return "AWS::IAM::Group" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMGroup) MarshalJSON() ([]byte, error) { - type Properties AWSIAMGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMGroup) UnmarshalJSON(b []byte) error { - type Properties AWSIAMGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMGroupResources retrieves all AWSIAMGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMGroupResources() map[string]AWSIAMGroup { - results := map[string]AWSIAMGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Group" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMGroupWithName retrieves all AWSIAMGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMGroupWithName(name string) (AWSIAMGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Group" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group_policy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group_policy.go deleted file mode 100644 index 78b16e0b48..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-group_policy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIAMGroup_Policy AWS CloudFormation Resource (AWS::IAM::Group.Policy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html -type AWSIAMGroup_Policy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMGroup_Policy) AWSCloudFormationType() string { - return "AWS::IAM::Group.Policy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-instanceprofile.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-instanceprofile.go deleted file mode 100644 index 8c5698b5c9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-instanceprofile.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMInstanceProfile AWS CloudFormation Resource (AWS::IAM::InstanceProfile) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html -type AWSIAMInstanceProfile struct { - - // InstanceProfileName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html#cfn-iam-instanceprofile-instanceprofilename - InstanceProfileName string `json:"InstanceProfileName,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html#cfn-iam-instanceprofile-path - Path string `json:"Path,omitempty"` - - // Roles AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html#cfn-iam-instanceprofile-roles - Roles []string `json:"Roles,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMInstanceProfile) AWSCloudFormationType() string { - return "AWS::IAM::InstanceProfile" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMInstanceProfile) MarshalJSON() ([]byte, error) { - type Properties AWSIAMInstanceProfile - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMInstanceProfile) UnmarshalJSON(b []byte) error { - type Properties AWSIAMInstanceProfile - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMInstanceProfile(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMInstanceProfileResources retrieves all AWSIAMInstanceProfile items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMInstanceProfileResources() map[string]AWSIAMInstanceProfile { - results := map[string]AWSIAMInstanceProfile{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMInstanceProfile: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::InstanceProfile" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMInstanceProfile - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMInstanceProfileWithName retrieves all AWSIAMInstanceProfile items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMInstanceProfileWithName(name string) (AWSIAMInstanceProfile, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMInstanceProfile: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::InstanceProfile" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMInstanceProfile - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMInstanceProfile{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-managedpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-managedpolicy.go deleted file mode 100644 index f1d8dfffb2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-managedpolicy.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMManagedPolicy AWS CloudFormation Resource (AWS::IAM::ManagedPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html -type AWSIAMManagedPolicy struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-description - Description string `json:"Description,omitempty"` - - // Groups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-groups - Groups []string `json:"Groups,omitempty"` - - // ManagedPolicyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-managedpolicyname - ManagedPolicyName string `json:"ManagedPolicyName,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-ec2-dhcpoptions-path - Path string `json:"Path,omitempty"` - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // Roles AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-roles - Roles []string `json:"Roles,omitempty"` - - // Users AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-managedpolicy.html#cfn-iam-managedpolicy-users - Users []string `json:"Users,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMManagedPolicy) AWSCloudFormationType() string { - return "AWS::IAM::ManagedPolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMManagedPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSIAMManagedPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMManagedPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSIAMManagedPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMManagedPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMManagedPolicyResources retrieves all AWSIAMManagedPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMManagedPolicyResources() map[string]AWSIAMManagedPolicy { - results := map[string]AWSIAMManagedPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMManagedPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::ManagedPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMManagedPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMManagedPolicyWithName retrieves all AWSIAMManagedPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMManagedPolicyWithName(name string) (AWSIAMManagedPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMManagedPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::ManagedPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMManagedPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMManagedPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-policy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-policy.go deleted file mode 100644 index b14c504545..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-policy.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMPolicy AWS CloudFormation Resource (AWS::IAM::Policy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html -type AWSIAMPolicy struct { - - // Groups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html#cfn-iam-policy-groups - Groups []string `json:"Groups,omitempty"` - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html#cfn-iam-policy-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html#cfn-iam-policy-policyname - PolicyName string `json:"PolicyName,omitempty"` - - // Roles AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html#cfn-iam-policy-roles - Roles []string `json:"Roles,omitempty"` - - // Users AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-policy.html#cfn-iam-policy-users - Users []string `json:"Users,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMPolicy) AWSCloudFormationType() string { - return "AWS::IAM::Policy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSIAMPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSIAMPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMPolicyResources retrieves all AWSIAMPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMPolicyResources() map[string]AWSIAMPolicy { - results := map[string]AWSIAMPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Policy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMPolicyWithName retrieves all AWSIAMPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMPolicyWithName(name string) (AWSIAMPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Policy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role.go deleted file mode 100644 index 59bfd2943c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMRole AWS CloudFormation Resource (AWS::IAM::Role) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html -type AWSIAMRole struct { - - // AssumeRolePolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-assumerolepolicydocument - AssumeRolePolicyDocument interface{} `json:"AssumeRolePolicyDocument,omitempty"` - - // ManagedPolicyArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-managepolicyarns - ManagedPolicyArns []string `json:"ManagedPolicyArns,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-path - Path string `json:"Path,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-policies - Policies []AWSIAMRole_Policy `json:"Policies,omitempty"` - - // RoleName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-rolename - RoleName string `json:"RoleName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMRole) AWSCloudFormationType() string { - return "AWS::IAM::Role" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMRole) MarshalJSON() ([]byte, error) { - type Properties AWSIAMRole - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMRole) UnmarshalJSON(b []byte) error { - type Properties AWSIAMRole - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMRole(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMRoleResources retrieves all AWSIAMRole items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMRoleResources() map[string]AWSIAMRole { - results := map[string]AWSIAMRole{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMRole: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Role" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMRole - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMRoleWithName retrieves all AWSIAMRole items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMRoleWithName(name string) (AWSIAMRole, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMRole: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::Role" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMRole - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMRole{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role_policy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role_policy.go deleted file mode 100644 index 0816e95065..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-role_policy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIAMRole_Policy AWS CloudFormation Resource (AWS::IAM::Role.Policy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html -type AWSIAMRole_Policy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMRole_Policy) AWSCloudFormationType() string { - return "AWS::IAM::Role.Policy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user.go deleted file mode 100644 index 519e5c2113..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMUser AWS CloudFormation Resource (AWS::IAM::User) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html -type AWSIAMUser struct { - - // Groups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-groups - Groups []string `json:"Groups,omitempty"` - - // LoginProfile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-loginprofile - LoginProfile *AWSIAMUser_LoginProfile `json:"LoginProfile,omitempty"` - - // ManagedPolicyArns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-managepolicyarns - ManagedPolicyArns []string `json:"ManagedPolicyArns,omitempty"` - - // Path AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-path - Path string `json:"Path,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-policies - Policies []AWSIAMUser_Policy `json:"Policies,omitempty"` - - // UserName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html#cfn-iam-user-username - UserName string `json:"UserName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMUser) AWSCloudFormationType() string { - return "AWS::IAM::User" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMUser) MarshalJSON() ([]byte, error) { - type Properties AWSIAMUser - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMUser) UnmarshalJSON(b []byte) error { - type Properties AWSIAMUser - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMUser(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMUserResources retrieves all AWSIAMUser items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMUserResources() map[string]AWSIAMUser { - results := map[string]AWSIAMUser{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMUser: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::User" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMUser - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMUserWithName retrieves all AWSIAMUser items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMUserWithName(name string) (AWSIAMUser, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMUser: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::User" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMUser - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMUser{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_loginprofile.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_loginprofile.go deleted file mode 100644 index be93b553ef..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_loginprofile.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIAMUser_LoginProfile AWS CloudFormation Resource (AWS::IAM::User.LoginProfile) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user-loginprofile.html -type AWSIAMUser_LoginProfile struct { - - // Password AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user-loginprofile.html#cfn-iam-user-loginprofile-password - Password string `json:"Password,omitempty"` - - // PasswordResetRequired AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user-loginprofile.html#cfn-iam-user-loginprofile-passwordresetrequired - PasswordResetRequired bool `json:"PasswordResetRequired,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMUser_LoginProfile) AWSCloudFormationType() string { - return "AWS::IAM::User.LoginProfile" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_policy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_policy.go deleted file mode 100644 index 1b5ea8842e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-user_policy.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIAMUser_Policy AWS CloudFormation Resource (AWS::IAM::User.Policy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html -type AWSIAMUser_Policy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html#cfn-iam-policies-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMUser_Policy) AWSCloudFormationType() string { - return "AWS::IAM::User.Policy" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-usertogroupaddition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-usertogroupaddition.go deleted file mode 100644 index 5d3209cc5e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iam-usertogroupaddition.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIAMUserToGroupAddition AWS CloudFormation Resource (AWS::IAM::UserToGroupAddition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html -type AWSIAMUserToGroupAddition struct { - - // GroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html#cfn-iam-addusertogroup-groupname - GroupName string `json:"GroupName,omitempty"` - - // Users AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html#cfn-iam-addusertogroup-users - Users []string `json:"Users,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIAMUserToGroupAddition) AWSCloudFormationType() string { - return "AWS::IAM::UserToGroupAddition" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIAMUserToGroupAddition) MarshalJSON() ([]byte, error) { - type Properties AWSIAMUserToGroupAddition - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIAMUserToGroupAddition) UnmarshalJSON(b []byte) error { - type Properties AWSIAMUserToGroupAddition - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIAMUserToGroupAddition(*res.Properties) - } - - return nil -} - -// GetAllAWSIAMUserToGroupAdditionResources retrieves all AWSIAMUserToGroupAddition items from an AWS CloudFormation template -func (t *Template) GetAllAWSIAMUserToGroupAdditionResources() map[string]AWSIAMUserToGroupAddition { - results := map[string]AWSIAMUserToGroupAddition{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIAMUserToGroupAddition: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::UserToGroupAddition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMUserToGroupAddition - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIAMUserToGroupAdditionWithName retrieves all AWSIAMUserToGroupAddition items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIAMUserToGroupAdditionWithName(name string) (AWSIAMUserToGroupAddition, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIAMUserToGroupAddition: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IAM::UserToGroupAddition" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIAMUserToGroupAddition - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIAMUserToGroupAddition{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-certificate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-certificate.go deleted file mode 100644 index 681dae687a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-certificate.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTCertificate AWS CloudFormation Resource (AWS::IoT::Certificate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-certificate.html -type AWSIoTCertificate struct { - - // CertificateSigningRequest AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-certificate.html#cfn-iot-certificate-certificatesigningrequest - CertificateSigningRequest string `json:"CertificateSigningRequest,omitempty"` - - // Status AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-certificate.html#cfn-iot-certificate-status - Status string `json:"Status,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTCertificate) AWSCloudFormationType() string { - return "AWS::IoT::Certificate" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTCertificate) MarshalJSON() ([]byte, error) { - type Properties AWSIoTCertificate - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTCertificate) UnmarshalJSON(b []byte) error { - type Properties AWSIoTCertificate - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTCertificate(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTCertificateResources retrieves all AWSIoTCertificate items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTCertificateResources() map[string]AWSIoTCertificate { - results := map[string]AWSIoTCertificate{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTCertificate: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTCertificate - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTCertificateWithName retrieves all AWSIoTCertificate items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTCertificateWithName(name string) (AWSIoTCertificate, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTCertificate: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Certificate" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTCertificate - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTCertificate{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policy.go deleted file mode 100644 index b23bf8c60a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policy.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTPolicy AWS CloudFormation Resource (AWS::IoT::Policy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policy.html -type AWSIoTPolicy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policy.html#cfn-iot-policy-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // PolicyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policy.html#cfn-iot-policy-policyname - PolicyName string `json:"PolicyName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTPolicy) AWSCloudFormationType() string { - return "AWS::IoT::Policy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSIoTPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSIoTPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTPolicyResources retrieves all AWSIoTPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTPolicyResources() map[string]AWSIoTPolicy { - results := map[string]AWSIoTPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Policy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTPolicyWithName retrieves all AWSIoTPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTPolicyWithName(name string) (AWSIoTPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Policy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policyprincipalattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policyprincipalattachment.go deleted file mode 100644 index 4a5e9d7b66..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-policyprincipalattachment.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTPolicyPrincipalAttachment AWS CloudFormation Resource (AWS::IoT::PolicyPrincipalAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policyprincipalattachment.html -type AWSIoTPolicyPrincipalAttachment struct { - - // PolicyName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policyprincipalattachment.html#cfn-iot-policyprincipalattachment-policyname - PolicyName string `json:"PolicyName,omitempty"` - - // Principal AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-policyprincipalattachment.html#cfn-iot-policyprincipalattachment-principal - Principal string `json:"Principal,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTPolicyPrincipalAttachment) AWSCloudFormationType() string { - return "AWS::IoT::PolicyPrincipalAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTPolicyPrincipalAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSIoTPolicyPrincipalAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTPolicyPrincipalAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSIoTPolicyPrincipalAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTPolicyPrincipalAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTPolicyPrincipalAttachmentResources retrieves all AWSIoTPolicyPrincipalAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTPolicyPrincipalAttachmentResources() map[string]AWSIoTPolicyPrincipalAttachment { - results := map[string]AWSIoTPolicyPrincipalAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTPolicyPrincipalAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::PolicyPrincipalAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTPolicyPrincipalAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTPolicyPrincipalAttachmentWithName retrieves all AWSIoTPolicyPrincipalAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTPolicyPrincipalAttachmentWithName(name string) (AWSIoTPolicyPrincipalAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTPolicyPrincipalAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::PolicyPrincipalAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTPolicyPrincipalAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTPolicyPrincipalAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing.go deleted file mode 100644 index 70d69ba476..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTThing AWS CloudFormation Resource (AWS::IoT::Thing) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thing.html -type AWSIoTThing struct { - - // AttributePayload AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thing.html#cfn-iot-thing-attributepayload - AttributePayload *AWSIoTThing_AttributePayload `json:"AttributePayload,omitempty"` - - // ThingName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thing.html#cfn-iot-thing-thingname - ThingName string `json:"ThingName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTThing) AWSCloudFormationType() string { - return "AWS::IoT::Thing" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTThing) MarshalJSON() ([]byte, error) { - type Properties AWSIoTThing - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTThing) UnmarshalJSON(b []byte) error { - type Properties AWSIoTThing - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTThing(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTThingResources retrieves all AWSIoTThing items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTThingResources() map[string]AWSIoTThing { - results := map[string]AWSIoTThing{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTThing: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Thing" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTThing - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTThingWithName retrieves all AWSIoTThing items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTThingWithName(name string) (AWSIoTThing, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTThing: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::Thing" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTThing - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTThing{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing_attributepayload.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing_attributepayload.go deleted file mode 100644 index 88fcadf5e4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thing_attributepayload.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSIoTThing_AttributePayload AWS CloudFormation Resource (AWS::IoT::Thing.AttributePayload) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-thing-attributepayload.html -type AWSIoTThing_AttributePayload struct { - - // Attributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-thing-attributepayload.html#cfn-iot-thing-attributepayload-attributes - Attributes map[string]string `json:"Attributes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTThing_AttributePayload) AWSCloudFormationType() string { - return "AWS::IoT::Thing.AttributePayload" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thingprincipalattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thingprincipalattachment.go deleted file mode 100644 index 00cefc497a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-thingprincipalattachment.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTThingPrincipalAttachment AWS CloudFormation Resource (AWS::IoT::ThingPrincipalAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html -type AWSIoTThingPrincipalAttachment struct { - - // Principal AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal - Principal string `json:"Principal,omitempty"` - - // ThingName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname - ThingName string `json:"ThingName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTThingPrincipalAttachment) AWSCloudFormationType() string { - return "AWS::IoT::ThingPrincipalAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTThingPrincipalAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSIoTThingPrincipalAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTThingPrincipalAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSIoTThingPrincipalAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTThingPrincipalAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTThingPrincipalAttachmentResources retrieves all AWSIoTThingPrincipalAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTThingPrincipalAttachmentResources() map[string]AWSIoTThingPrincipalAttachment { - results := map[string]AWSIoTThingPrincipalAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTThingPrincipalAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::ThingPrincipalAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTThingPrincipalAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTThingPrincipalAttachmentWithName retrieves all AWSIoTThingPrincipalAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTThingPrincipalAttachmentWithName(name string) (AWSIoTThingPrincipalAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTThingPrincipalAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::ThingPrincipalAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTThingPrincipalAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTThingPrincipalAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule.go deleted file mode 100644 index 04391314f7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSIoTTopicRule AWS CloudFormation Resource (AWS::IoT::TopicRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html -type AWSIoTTopicRule struct { - - // RuleName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html#cfn-iot-topicrule-rulename - RuleName string `json:"RuleName,omitempty"` - - // TopicRulePayload AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-topicrule.html#cfn-iot-topicrule-topicrulepayload - TopicRulePayload *AWSIoTTopicRule_TopicRulePayload `json:"TopicRulePayload,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSIoTTopicRule) MarshalJSON() ([]byte, error) { - type Properties AWSIoTTopicRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSIoTTopicRule) UnmarshalJSON(b []byte) error { - type Properties AWSIoTTopicRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSIoTTopicRule(*res.Properties) - } - - return nil -} - -// GetAllAWSIoTTopicRuleResources retrieves all AWSIoTTopicRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSIoTTopicRuleResources() map[string]AWSIoTTopicRule { - results := map[string]AWSIoTTopicRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSIoTTopicRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::TopicRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTTopicRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSIoTTopicRuleWithName retrieves all AWSIoTTopicRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSIoTTopicRuleWithName(name string) (AWSIoTTopicRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSIoTTopicRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::IoT::TopicRule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSIoTTopicRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSIoTTopicRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_action.go deleted file mode 100644 index ce19bb73db..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_action.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_Action AWS CloudFormation Resource (AWS::IoT::TopicRule.Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html -type AWSIoTTopicRule_Action struct { - - // CloudwatchAlarm AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-cloudwatchalarm - CloudwatchAlarm *AWSIoTTopicRule_CloudwatchAlarmAction `json:"CloudwatchAlarm,omitempty"` - - // CloudwatchMetric AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-cloudwatchmetric - CloudwatchMetric *AWSIoTTopicRule_CloudwatchMetricAction `json:"CloudwatchMetric,omitempty"` - - // DynamoDB AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-dynamodb - DynamoDB *AWSIoTTopicRule_DynamoDBAction `json:"DynamoDB,omitempty"` - - // DynamoDBv2 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-dynamodbv2 - DynamoDBv2 *AWSIoTTopicRule_DynamoDBv2Action `json:"DynamoDBv2,omitempty"` - - // Elasticsearch AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-elasticsearch - Elasticsearch *AWSIoTTopicRule_ElasticsearchAction `json:"Elasticsearch,omitempty"` - - // Firehose AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-firehose - Firehose *AWSIoTTopicRule_FirehoseAction `json:"Firehose,omitempty"` - - // Kinesis AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-kinesis - Kinesis *AWSIoTTopicRule_KinesisAction `json:"Kinesis,omitempty"` - - // Lambda AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-lambda - Lambda *AWSIoTTopicRule_LambdaAction `json:"Lambda,omitempty"` - - // Republish AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-republish - Republish *AWSIoTTopicRule_RepublishAction `json:"Republish,omitempty"` - - // S3 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-s3 - S3 *AWSIoTTopicRule_S3Action `json:"S3,omitempty"` - - // Sns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-sns - Sns *AWSIoTTopicRule_SnsAction `json:"Sns,omitempty"` - - // Sqs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-action.html#cfn-iot-topicrule-action-sqs - Sqs *AWSIoTTopicRule_SqsAction `json:"Sqs,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_Action) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchalarmaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchalarmaction.go deleted file mode 100644 index 9c8d6c1fb1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchalarmaction.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_CloudwatchAlarmAction AWS CloudFormation Resource (AWS::IoT::TopicRule.CloudwatchAlarmAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html -type AWSIoTTopicRule_CloudwatchAlarmAction struct { - - // AlarmName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-alarmname - AlarmName string `json:"AlarmName,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // StateReason AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-statereason - StateReason string `json:"StateReason,omitempty"` - - // StateValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchalarmaction.html#cfn-iot-topicrule-cloudwatchalarmaction-statevalue - StateValue string `json:"StateValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_CloudwatchAlarmAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.CloudwatchAlarmAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchmetricaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchmetricaction.go deleted file mode 100644 index a35dacdf5e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_cloudwatchmetricaction.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_CloudwatchMetricAction AWS CloudFormation Resource (AWS::IoT::TopicRule.CloudwatchMetricAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html -type AWSIoTTopicRule_CloudwatchMetricAction struct { - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricname - MetricName string `json:"MetricName,omitempty"` - - // MetricNamespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricnamespace - MetricNamespace string `json:"MetricNamespace,omitempty"` - - // MetricTimestamp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metrictimestamp - MetricTimestamp string `json:"MetricTimestamp,omitempty"` - - // MetricUnit AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricunit - MetricUnit string `json:"MetricUnit,omitempty"` - - // MetricValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-metricvalue - MetricValue string `json:"MetricValue,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-cloudwatchmetricaction.html#cfn-iot-topicrule-cloudwatchmetricaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_CloudwatchMetricAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.CloudwatchMetricAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbaction.go deleted file mode 100644 index abb6664035..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbaction.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_DynamoDBAction AWS CloudFormation Resource (AWS::IoT::TopicRule.DynamoDBAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html -type AWSIoTTopicRule_DynamoDBAction struct { - - // HashKeyField AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeyfield - HashKeyField string `json:"HashKeyField,omitempty"` - - // HashKeyType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeytype - HashKeyType string `json:"HashKeyType,omitempty"` - - // HashKeyValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-hashkeyvalue - HashKeyValue string `json:"HashKeyValue,omitempty"` - - // PayloadField AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-payloadfield - PayloadField string `json:"PayloadField,omitempty"` - - // RangeKeyField AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeyfield - RangeKeyField string `json:"RangeKeyField,omitempty"` - - // RangeKeyType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeytype - RangeKeyType string `json:"RangeKeyType,omitempty"` - - // RangeKeyValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rangekeyvalue - RangeKeyValue string `json:"RangeKeyValue,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // TableName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbaction.html#cfn-iot-topicrule-dynamodbaction-tablename - TableName string `json:"TableName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_DynamoDBAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.DynamoDBAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbv2action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbv2action.go deleted file mode 100644 index fc4ae52183..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_dynamodbv2action.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_DynamoDBv2Action AWS CloudFormation Resource (AWS::IoT::TopicRule.DynamoDBv2Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbv2action.html -type AWSIoTTopicRule_DynamoDBv2Action struct { - - // PutItem AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbv2action.html#cfn-iot-topicrule-dynamodbv2action-putitem - PutItem *AWSIoTTopicRule_PutItemInput `json:"PutItem,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-dynamodbv2action.html#cfn-iot-topicrule-dynamodbv2action-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_DynamoDBv2Action) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.DynamoDBv2Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_elasticsearchaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_elasticsearchaction.go deleted file mode 100644 index 4e632879a6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_elasticsearchaction.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_ElasticsearchAction AWS CloudFormation Resource (AWS::IoT::TopicRule.ElasticsearchAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html -type AWSIoTTopicRule_ElasticsearchAction struct { - - // Endpoint AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-endpoint - Endpoint string `json:"Endpoint,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-id - Id string `json:"Id,omitempty"` - - // Index AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-index - Index string `json:"Index,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-elasticsearchaction.html#cfn-iot-topicrule-elasticsearchaction-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_ElasticsearchAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.ElasticsearchAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_firehoseaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_firehoseaction.go deleted file mode 100644 index fa07f5aa48..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_firehoseaction.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_FirehoseAction AWS CloudFormation Resource (AWS::IoT::TopicRule.FirehoseAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html -type AWSIoTTopicRule_FirehoseAction struct { - - // DeliveryStreamName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-deliverystreamname - DeliveryStreamName string `json:"DeliveryStreamName,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // Separator AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-firehoseaction.html#cfn-iot-topicrule-firehoseaction-separator - Separator string `json:"Separator,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_FirehoseAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.FirehoseAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_kinesisaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_kinesisaction.go deleted file mode 100644 index ec3e7ddbf5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_kinesisaction.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_KinesisAction AWS CloudFormation Resource (AWS::IoT::TopicRule.KinesisAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html -type AWSIoTTopicRule_KinesisAction struct { - - // PartitionKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-partitionkey - PartitionKey string `json:"PartitionKey,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // StreamName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-kinesisaction.html#cfn-iot-topicrule-kinesisaction-streamname - StreamName string `json:"StreamName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_KinesisAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.KinesisAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_lambdaaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_lambdaaction.go deleted file mode 100644 index f2249ccc8f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_lambdaaction.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_LambdaAction AWS CloudFormation Resource (AWS::IoT::TopicRule.LambdaAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-lambdaaction.html -type AWSIoTTopicRule_LambdaAction struct { - - // FunctionArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-lambdaaction.html#cfn-iot-topicrule-lambdaaction-functionarn - FunctionArn string `json:"FunctionArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_LambdaAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.LambdaAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_putiteminput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_putiteminput.go deleted file mode 100644 index c3ab888974..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_putiteminput.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_PutItemInput AWS CloudFormation Resource (AWS::IoT::TopicRule.PutItemInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-putiteminput.html -type AWSIoTTopicRule_PutItemInput struct { - - // TableName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-putiteminput.html#cfn-iot-topicrule-putiteminput-tablename - TableName string `json:"TableName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_PutItemInput) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.PutItemInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_republishaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_republishaction.go deleted file mode 100644 index 712286464a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_republishaction.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_RepublishAction AWS CloudFormation Resource (AWS::IoT::TopicRule.RepublishAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-republishaction.html -type AWSIoTTopicRule_RepublishAction struct { - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-republishaction.html#cfn-iot-topicrule-republishaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // Topic AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-republishaction.html#cfn-iot-topicrule-republishaction-topic - Topic string `json:"Topic,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_RepublishAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.RepublishAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_s3action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_s3action.go deleted file mode 100644 index 2705131904..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_s3action.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_S3Action AWS CloudFormation Resource (AWS::IoT::TopicRule.S3Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html -type AWSIoTTopicRule_S3Action struct { - - // BucketName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-bucketname - BucketName string `json:"BucketName,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-key - Key string `json:"Key,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_S3Action) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.S3Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_snsaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_snsaction.go deleted file mode 100644 index 1b08360e81..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_snsaction.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_SnsAction AWS CloudFormation Resource (AWS::IoT::TopicRule.SnsAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html -type AWSIoTTopicRule_SnsAction struct { - - // MessageFormat AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-messageformat - MessageFormat string `json:"MessageFormat,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // TargetArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-snsaction.html#cfn-iot-topicrule-snsaction-targetarn - TargetArn string `json:"TargetArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_SnsAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.SnsAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_sqsaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_sqsaction.go deleted file mode 100644 index a126f591e0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_sqsaction.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_SqsAction AWS CloudFormation Resource (AWS::IoT::TopicRule.SqsAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html -type AWSIoTTopicRule_SqsAction struct { - - // QueueUrl AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-queueurl - QueueUrl string `json:"QueueUrl,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // UseBase64 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-sqsaction.html#cfn-iot-topicrule-sqsaction-usebase64 - UseBase64 bool `json:"UseBase64,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_SqsAction) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.SqsAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_topicrulepayload.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_topicrulepayload.go deleted file mode 100644 index bdde84a383..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-iot-topicrule_topicrulepayload.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSIoTTopicRule_TopicRulePayload AWS CloudFormation Resource (AWS::IoT::TopicRule.TopicRulePayload) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html -type AWSIoTTopicRule_TopicRulePayload struct { - - // Actions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-actions - Actions []AWSIoTTopicRule_Action `json:"Actions,omitempty"` - - // AwsIotSqlVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-awsiotsqlversion - AwsIotSqlVersion string `json:"AwsIotSqlVersion,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-description - Description string `json:"Description,omitempty"` - - // RuleDisabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-ruledisabled - RuleDisabled bool `json:"RuleDisabled,omitempty"` - - // Sql AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-topicrulepayload.html#cfn-iot-topicrule-topicrulepayload-sql - Sql string `json:"Sql,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSIoTTopicRule_TopicRulePayload) AWSCloudFormationType() string { - return "AWS::IoT::TopicRule.TopicRulePayload" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesis-stream.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesis-stream.go deleted file mode 100644 index ce4a0c9089..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesis-stream.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKinesisStream AWS CloudFormation Resource (AWS::Kinesis::Stream) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html -type AWSKinesisStream struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html#cfn-kinesis-stream-name - Name string `json:"Name,omitempty"` - - // RetentionPeriodHours AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html#cfn-kinesis-stream-retentionperiodhours - RetentionPeriodHours int `json:"RetentionPeriodHours,omitempty"` - - // ShardCount AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html#cfn-kinesis-stream-shardcount - ShardCount int `json:"ShardCount,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesis-stream.html#cfn-kinesis-stream-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisStream) AWSCloudFormationType() string { - return "AWS::Kinesis::Stream" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKinesisStream) MarshalJSON() ([]byte, error) { - type Properties AWSKinesisStream - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKinesisStream) UnmarshalJSON(b []byte) error { - type Properties AWSKinesisStream - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKinesisStream(*res.Properties) - } - - return nil -} - -// GetAllAWSKinesisStreamResources retrieves all AWSKinesisStream items from an AWS CloudFormation template -func (t *Template) GetAllAWSKinesisStreamResources() map[string]AWSKinesisStream { - results := map[string]AWSKinesisStream{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKinesisStream: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Kinesis::Stream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisStream - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKinesisStreamWithName retrieves all AWSKinesisStream items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKinesisStreamWithName(name string) (AWSKinesisStream, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKinesisStream: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Kinesis::Stream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisStream - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKinesisStream{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application.go deleted file mode 100644 index 672f7d5258..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKinesisAnalyticsApplication AWS CloudFormation Resource (AWS::KinesisAnalytics::Application) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-application.html -type AWSKinesisAnalyticsApplication struct { - - // ApplicationCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-application.html#cfn-kinesisanalytics-application-applicationcode - ApplicationCode string `json:"ApplicationCode,omitempty"` - - // ApplicationDescription AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-application.html#cfn-kinesisanalytics-application-applicationdescription - ApplicationDescription string `json:"ApplicationDescription,omitempty"` - - // ApplicationName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-application.html#cfn-kinesisanalytics-application-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // Inputs AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-application.html#cfn-kinesisanalytics-application-inputs - Inputs []AWSKinesisAnalyticsApplication_Input `json:"Inputs,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKinesisAnalyticsApplication) MarshalJSON() ([]byte, error) { - type Properties AWSKinesisAnalyticsApplication - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKinesisAnalyticsApplication) UnmarshalJSON(b []byte) error { - type Properties AWSKinesisAnalyticsApplication - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKinesisAnalyticsApplication(*res.Properties) - } - - return nil -} - -// GetAllAWSKinesisAnalyticsApplicationResources retrieves all AWSKinesisAnalyticsApplication items from an AWS CloudFormation template -func (t *Template) GetAllAWSKinesisAnalyticsApplicationResources() map[string]AWSKinesisAnalyticsApplication { - results := map[string]AWSKinesisAnalyticsApplication{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplication: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplication - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKinesisAnalyticsApplicationWithName retrieves all AWSKinesisAnalyticsApplication items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKinesisAnalyticsApplicationWithName(name string) (AWSKinesisAnalyticsApplication, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplication: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::Application" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplication - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKinesisAnalyticsApplication{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_csvmappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_csvmappingparameters.go deleted file mode 100644 index 1831d2d98d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_csvmappingparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_CSVMappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.CSVMappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-csvmappingparameters.html -type AWSKinesisAnalyticsApplication_CSVMappingParameters struct { - - // RecordColumnDelimiter AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-csvmappingparameters.html#cfn-kinesisanalytics-application-csvmappingparameters-recordcolumndelimiter - RecordColumnDelimiter string `json:"RecordColumnDelimiter,omitempty"` - - // RecordRowDelimiter AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-csvmappingparameters.html#cfn-kinesisanalytics-application-csvmappingparameters-recordrowdelimiter - RecordRowDelimiter string `json:"RecordRowDelimiter,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_CSVMappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.CSVMappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_input.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_input.go deleted file mode 100644 index c10c081562..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_input.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_Input AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.Input) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html -type AWSKinesisAnalyticsApplication_Input struct { - - // InputParallelism AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-inputparallelism - InputParallelism *AWSKinesisAnalyticsApplication_InputParallelism `json:"InputParallelism,omitempty"` - - // InputSchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-inputschema - InputSchema *AWSKinesisAnalyticsApplication_InputSchema `json:"InputSchema,omitempty"` - - // KinesisFirehoseInput AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-kinesisfirehoseinput - KinesisFirehoseInput *AWSKinesisAnalyticsApplication_KinesisFirehoseInput `json:"KinesisFirehoseInput,omitempty"` - - // KinesisStreamsInput AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-kinesisstreamsinput - KinesisStreamsInput *AWSKinesisAnalyticsApplication_KinesisStreamsInput `json:"KinesisStreamsInput,omitempty"` - - // NamePrefix AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-input.html#cfn-kinesisanalytics-application-input-nameprefix - NamePrefix string `json:"NamePrefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_Input) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.Input" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputparallelism.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputparallelism.go deleted file mode 100644 index 3c6c8bc843..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputparallelism.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_InputParallelism AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.InputParallelism) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputparallelism.html -type AWSKinesisAnalyticsApplication_InputParallelism struct { - - // Count AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputparallelism.html#cfn-kinesisanalytics-application-inputparallelism-count - Count int `json:"Count,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_InputParallelism) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.InputParallelism" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputschema.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputschema.go deleted file mode 100644 index a6a7a5b69e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_inputschema.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_InputSchema AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.InputSchema) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html -type AWSKinesisAnalyticsApplication_InputSchema struct { - - // RecordColumns AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordcolumns - RecordColumns []AWSKinesisAnalyticsApplication_RecordColumn `json:"RecordColumns,omitempty"` - - // RecordEncoding AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordencoding - RecordEncoding string `json:"RecordEncoding,omitempty"` - - // RecordFormat AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-inputschema.html#cfn-kinesisanalytics-application-inputschema-recordformat - RecordFormat *AWSKinesisAnalyticsApplication_RecordFormat `json:"RecordFormat,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_InputSchema) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.InputSchema" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_jsonmappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_jsonmappingparameters.go deleted file mode 100644 index ad910e1b06..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_jsonmappingparameters.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_JSONMappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.JSONMappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-jsonmappingparameters.html -type AWSKinesisAnalyticsApplication_JSONMappingParameters struct { - - // RecordRowPath AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-jsonmappingparameters.html#cfn-kinesisanalytics-application-jsonmappingparameters-recordrowpath - RecordRowPath string `json:"RecordRowPath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_JSONMappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.JSONMappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisfirehoseinput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisfirehoseinput.go deleted file mode 100644 index 3c92a94487..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisfirehoseinput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_KinesisFirehoseInput AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.KinesisFirehoseInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisfirehoseinput.html -type AWSKinesisAnalyticsApplication_KinesisFirehoseInput struct { - - // ResourceARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisfirehoseinput.html#cfn-kinesisanalytics-application-kinesisfirehoseinput-resourcearn - ResourceARN string `json:"ResourceARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisfirehoseinput.html#cfn-kinesisanalytics-application-kinesisfirehoseinput-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_KinesisFirehoseInput) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.KinesisFirehoseInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisstreamsinput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisstreamsinput.go deleted file mode 100644 index c945567f70..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_kinesisstreamsinput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_KinesisStreamsInput AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.KinesisStreamsInput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisstreamsinput.html -type AWSKinesisAnalyticsApplication_KinesisStreamsInput struct { - - // ResourceARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisstreamsinput.html#cfn-kinesisanalytics-application-kinesisstreamsinput-resourcearn - ResourceARN string `json:"ResourceARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-kinesisstreamsinput.html#cfn-kinesisanalytics-application-kinesisstreamsinput-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_KinesisStreamsInput) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.KinesisStreamsInput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_mappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_mappingparameters.go deleted file mode 100644 index a46e769390..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_mappingparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_MappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.MappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-mappingparameters.html -type AWSKinesisAnalyticsApplication_MappingParameters struct { - - // CSVMappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-mappingparameters.html#cfn-kinesisanalytics-application-mappingparameters-csvmappingparameters - CSVMappingParameters *AWSKinesisAnalyticsApplication_CSVMappingParameters `json:"CSVMappingParameters,omitempty"` - - // JSONMappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-mappingparameters.html#cfn-kinesisanalytics-application-mappingparameters-jsonmappingparameters - JSONMappingParameters *AWSKinesisAnalyticsApplication_JSONMappingParameters `json:"JSONMappingParameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_MappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.MappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordcolumn.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordcolumn.go deleted file mode 100644 index 9ce056dac2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordcolumn.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_RecordColumn AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.RecordColumn) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordcolumn.html -type AWSKinesisAnalyticsApplication_RecordColumn struct { - - // Mapping AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordcolumn.html#cfn-kinesisanalytics-application-recordcolumn-mapping - Mapping string `json:"Mapping,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordcolumn.html#cfn-kinesisanalytics-application-recordcolumn-name - Name string `json:"Name,omitempty"` - - // SqlType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordcolumn.html#cfn-kinesisanalytics-application-recordcolumn-sqltype - SqlType string `json:"SqlType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_RecordColumn) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.RecordColumn" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordformat.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordformat.go deleted file mode 100644 index 80f1a9d808..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-application_recordformat.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplication_RecordFormat AWS CloudFormation Resource (AWS::KinesisAnalytics::Application.RecordFormat) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html -type AWSKinesisAnalyticsApplication_RecordFormat struct { - - // MappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html#cfn-kinesisanalytics-application-recordformat-mappingparameters - MappingParameters *AWSKinesisAnalyticsApplication_MappingParameters `json:"MappingParameters,omitempty"` - - // RecordFormatType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-application-recordformat.html#cfn-kinesisanalytics-application-recordformat-recordformattype - RecordFormatType string `json:"RecordFormatType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplication_RecordFormat) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::Application.RecordFormat" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput.go deleted file mode 100644 index 24047cfb76..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKinesisAnalyticsApplicationOutput AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationOutput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationoutput.html -type AWSKinesisAnalyticsApplicationOutput struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationoutput.html#cfn-kinesisanalytics-applicationoutput-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // Output AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationoutput.html#cfn-kinesisanalytics-applicationoutput-output - Output *AWSKinesisAnalyticsApplicationOutput_Output `json:"Output,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationOutput) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationOutput" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKinesisAnalyticsApplicationOutput) MarshalJSON() ([]byte, error) { - type Properties AWSKinesisAnalyticsApplicationOutput - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKinesisAnalyticsApplicationOutput) UnmarshalJSON(b []byte) error { - type Properties AWSKinesisAnalyticsApplicationOutput - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKinesisAnalyticsApplicationOutput(*res.Properties) - } - - return nil -} - -// GetAllAWSKinesisAnalyticsApplicationOutputResources retrieves all AWSKinesisAnalyticsApplicationOutput items from an AWS CloudFormation template -func (t *Template) GetAllAWSKinesisAnalyticsApplicationOutputResources() map[string]AWSKinesisAnalyticsApplicationOutput { - results := map[string]AWSKinesisAnalyticsApplicationOutput{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplicationOutput: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::ApplicationOutput" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplicationOutput - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKinesisAnalyticsApplicationOutputWithName retrieves all AWSKinesisAnalyticsApplicationOutput items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKinesisAnalyticsApplicationOutputWithName(name string) (AWSKinesisAnalyticsApplicationOutput, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplicationOutput: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::ApplicationOutput" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplicationOutput - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKinesisAnalyticsApplicationOutput{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_destinationschema.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_destinationschema.go deleted file mode 100644 index d48085d269..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_destinationschema.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationOutput_DestinationSchema AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationOutput.DestinationSchema) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-destinationschema.html -type AWSKinesisAnalyticsApplicationOutput_DestinationSchema struct { - - // RecordFormatType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-destinationschema.html#cfn-kinesisanalytics-applicationoutput-destinationschema-recordformattype - RecordFormatType string `json:"RecordFormatType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationOutput_DestinationSchema) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationOutput.DestinationSchema" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisfirehoseoutput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisfirehoseoutput.go deleted file mode 100644 index 7e239c6f56..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisfirehoseoutput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationOutput_KinesisFirehoseOutput AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationOutput.KinesisFirehoseOutput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisfirehoseoutput.html -type AWSKinesisAnalyticsApplicationOutput_KinesisFirehoseOutput struct { - - // ResourceARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisfirehoseoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisfirehoseoutput-resourcearn - ResourceARN string `json:"ResourceARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisfirehoseoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisfirehoseoutput-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationOutput_KinesisFirehoseOutput) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationOutput.KinesisFirehoseOutput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisstreamsoutput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisstreamsoutput.go deleted file mode 100644 index bdce055590..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_kinesisstreamsoutput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationOutput_KinesisStreamsOutput AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationOutput.KinesisStreamsOutput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisstreamsoutput.html -type AWSKinesisAnalyticsApplicationOutput_KinesisStreamsOutput struct { - - // ResourceARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisstreamsoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisstreamsoutput-resourcearn - ResourceARN string `json:"ResourceARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-kinesisstreamsoutput.html#cfn-kinesisanalytics-applicationoutput-kinesisstreamsoutput-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationOutput_KinesisStreamsOutput) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationOutput.KinesisStreamsOutput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_output.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_output.go deleted file mode 100644 index 35611dca20..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationoutput_output.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationOutput_Output AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationOutput.Output) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html -type AWSKinesisAnalyticsApplicationOutput_Output struct { - - // DestinationSchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-destinationschema - DestinationSchema *AWSKinesisAnalyticsApplicationOutput_DestinationSchema `json:"DestinationSchema,omitempty"` - - // KinesisFirehoseOutput AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisfirehoseoutput - KinesisFirehoseOutput *AWSKinesisAnalyticsApplicationOutput_KinesisFirehoseOutput `json:"KinesisFirehoseOutput,omitempty"` - - // KinesisStreamsOutput AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-kinesisstreamsoutput - KinesisStreamsOutput *AWSKinesisAnalyticsApplicationOutput_KinesisStreamsOutput `json:"KinesisStreamsOutput,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationoutput-output.html#cfn-kinesisanalytics-applicationoutput-output-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationOutput_Output) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationOutput.Output" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource.go deleted file mode 100644 index 3b1901bd85..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKinesisAnalyticsApplicationReferenceDataSource AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationreferencedatasource.html -type AWSKinesisAnalyticsApplicationReferenceDataSource struct { - - // ApplicationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationreferencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-applicationname - ApplicationName string `json:"ApplicationName,omitempty"` - - // ReferenceDataSource AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisanalytics-applicationreferencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-referencedatasource - ReferenceDataSource *AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceDataSource `json:"ReferenceDataSource,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource) MarshalJSON() ([]byte, error) { - type Properties AWSKinesisAnalyticsApplicationReferenceDataSource - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource) UnmarshalJSON(b []byte) error { - type Properties AWSKinesisAnalyticsApplicationReferenceDataSource - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKinesisAnalyticsApplicationReferenceDataSource(*res.Properties) - } - - return nil -} - -// GetAllAWSKinesisAnalyticsApplicationReferenceDataSourceResources retrieves all AWSKinesisAnalyticsApplicationReferenceDataSource items from an AWS CloudFormation template -func (t *Template) GetAllAWSKinesisAnalyticsApplicationReferenceDataSourceResources() map[string]AWSKinesisAnalyticsApplicationReferenceDataSource { - results := map[string]AWSKinesisAnalyticsApplicationReferenceDataSource{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplicationReferenceDataSource: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::ApplicationReferenceDataSource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplicationReferenceDataSource - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKinesisAnalyticsApplicationReferenceDataSourceWithName retrieves all AWSKinesisAnalyticsApplicationReferenceDataSource items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKinesisAnalyticsApplicationReferenceDataSourceWithName(name string) (AWSKinesisAnalyticsApplicationReferenceDataSource, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKinesisAnalyticsApplicationReferenceDataSource: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisAnalytics::ApplicationReferenceDataSource" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisAnalyticsApplicationReferenceDataSource - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKinesisAnalyticsApplicationReferenceDataSource{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_csvmappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_csvmappingparameters.go deleted file mode 100644 index 54e9c5e407..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_csvmappingparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_CSVMappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.CSVMappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-csvmappingparameters.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_CSVMappingParameters struct { - - // RecordColumnDelimiter AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-csvmappingparameters.html#cfn-kinesisanalytics-applicationreferencedatasource-csvmappingparameters-recordcolumndelimiter - RecordColumnDelimiter string `json:"RecordColumnDelimiter,omitempty"` - - // RecordRowDelimiter AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-csvmappingparameters.html#cfn-kinesisanalytics-applicationreferencedatasource-csvmappingparameters-recordrowdelimiter - RecordRowDelimiter string `json:"RecordRowDelimiter,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_CSVMappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.CSVMappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_jsonmappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_jsonmappingparameters.go deleted file mode 100644 index b102de4db9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_jsonmappingparameters.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_JSONMappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.JSONMappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-jsonmappingparameters.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_JSONMappingParameters struct { - - // RecordRowPath AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-jsonmappingparameters.html#cfn-kinesisanalytics-applicationreferencedatasource-jsonmappingparameters-recordrowpath - RecordRowPath string `json:"RecordRowPath,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_JSONMappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.JSONMappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_mappingparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_mappingparameters.go deleted file mode 100644 index 25e5d9471b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_mappingparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_MappingParameters AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.MappingParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-mappingparameters.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_MappingParameters struct { - - // CSVMappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-mappingparameters.html#cfn-kinesisanalytics-applicationreferencedatasource-mappingparameters-csvmappingparameters - CSVMappingParameters *AWSKinesisAnalyticsApplicationReferenceDataSource_CSVMappingParameters `json:"CSVMappingParameters,omitempty"` - - // JSONMappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-mappingparameters.html#cfn-kinesisanalytics-applicationreferencedatasource-mappingparameters-jsonmappingparameters - JSONMappingParameters *AWSKinesisAnalyticsApplicationReferenceDataSource_JSONMappingParameters `json:"JSONMappingParameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_MappingParameters) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.MappingParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordcolumn.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordcolumn.go deleted file mode 100644 index 179cc78e8f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordcolumn.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_RecordColumn AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordColumn) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordcolumn.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_RecordColumn struct { - - // Mapping AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordcolumn.html#cfn-kinesisanalytics-applicationreferencedatasource-recordcolumn-mapping - Mapping string `json:"Mapping,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordcolumn.html#cfn-kinesisanalytics-applicationreferencedatasource-recordcolumn-name - Name string `json:"Name,omitempty"` - - // SqlType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordcolumn.html#cfn-kinesisanalytics-applicationreferencedatasource-recordcolumn-sqltype - SqlType string `json:"SqlType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_RecordColumn) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordColumn" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordformat.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordformat.go deleted file mode 100644 index eb949d8055..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_recordformat.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_RecordFormat AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordFormat) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordformat.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_RecordFormat struct { - - // MappingParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordformat.html#cfn-kinesisanalytics-applicationreferencedatasource-recordformat-mappingparameters - MappingParameters *AWSKinesisAnalyticsApplicationReferenceDataSource_MappingParameters `json:"MappingParameters,omitempty"` - - // RecordFormatType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-recordformat.html#cfn-kinesisanalytics-applicationreferencedatasource-recordformat-recordformattype - RecordFormatType string `json:"RecordFormatType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_RecordFormat) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.RecordFormat" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referencedatasource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referencedatasource.go deleted file mode 100644 index b05cf5f198..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referencedatasource.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceDataSource AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceDataSource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referencedatasource.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceDataSource struct { - - // ReferenceSchema AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-referencedatasource-referenceschema - ReferenceSchema *AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceSchema `json:"ReferenceSchema,omitempty"` - - // S3ReferenceDataSource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-referencedatasource-s3referencedatasource - S3ReferenceDataSource *AWSKinesisAnalyticsApplicationReferenceDataSource_S3ReferenceDataSource `json:"S3ReferenceDataSource,omitempty"` - - // TableName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-referencedatasource-tablename - TableName string `json:"TableName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceDataSource) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceDataSource" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referenceschema.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referenceschema.go deleted file mode 100644 index e1e34d4c14..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_referenceschema.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceSchema AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceSchema) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceSchema struct { - - // RecordColumns AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordcolumns - RecordColumns []AWSKinesisAnalyticsApplicationReferenceDataSource_RecordColumn `json:"RecordColumns,omitempty"` - - // RecordEncoding AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordencoding - RecordEncoding string `json:"RecordEncoding,omitempty"` - - // RecordFormat AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-referenceschema.html#cfn-kinesisanalytics-applicationreferencedatasource-referenceschema-recordformat - RecordFormat *AWSKinesisAnalyticsApplicationReferenceDataSource_RecordFormat `json:"RecordFormat,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_ReferenceSchema) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.ReferenceSchema" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_s3referencedatasource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_s3referencedatasource.go deleted file mode 100644 index 5f70ccc2ae..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisanalytics-applicationreferencedatasource_s3referencedatasource.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisAnalyticsApplicationReferenceDataSource_S3ReferenceDataSource AWS CloudFormation Resource (AWS::KinesisAnalytics::ApplicationReferenceDataSource.S3ReferenceDataSource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-s3referencedatasource.html -type AWSKinesisAnalyticsApplicationReferenceDataSource_S3ReferenceDataSource struct { - - // BucketARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-s3referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-s3referencedatasource-bucketarn - BucketARN string `json:"BucketARN,omitempty"` - - // FileKey AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-s3referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-s3referencedatasource-filekey - FileKey string `json:"FileKey,omitempty"` - - // ReferenceRoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalytics-applicationreferencedatasource-s3referencedatasource.html#cfn-kinesisanalytics-applicationreferencedatasource-s3referencedatasource-referencerolearn - ReferenceRoleARN string `json:"ReferenceRoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisAnalyticsApplicationReferenceDataSource_S3ReferenceDataSource) AWSCloudFormationType() string { - return "AWS::KinesisAnalytics::ApplicationReferenceDataSource.S3ReferenceDataSource" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream.go deleted file mode 100644 index 3d2ae1b70b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKinesisFirehoseDeliveryStream AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html -type AWSKinesisFirehoseDeliveryStream struct { - - // DeliveryStreamName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-deliverystreamname - DeliveryStreamName string `json:"DeliveryStreamName,omitempty"` - - // DeliveryStreamType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-deliverystreamtype - DeliveryStreamType string `json:"DeliveryStreamType,omitempty"` - - // ElasticsearchDestinationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration - ElasticsearchDestinationConfiguration *AWSKinesisFirehoseDeliveryStream_ElasticsearchDestinationConfiguration `json:"ElasticsearchDestinationConfiguration,omitempty"` - - // ExtendedS3DestinationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration - ExtendedS3DestinationConfiguration *AWSKinesisFirehoseDeliveryStream_ExtendedS3DestinationConfiguration `json:"ExtendedS3DestinationConfiguration,omitempty"` - - // KinesisStreamSourceConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration - KinesisStreamSourceConfiguration *AWSKinesisFirehoseDeliveryStream_KinesisStreamSourceConfiguration `json:"KinesisStreamSourceConfiguration,omitempty"` - - // RedshiftDestinationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration - RedshiftDestinationConfiguration *AWSKinesisFirehoseDeliveryStream_RedshiftDestinationConfiguration `json:"RedshiftDestinationConfiguration,omitempty"` - - // S3DestinationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kinesisfirehose-deliverystream.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration - S3DestinationConfiguration *AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration `json:"S3DestinationConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKinesisFirehoseDeliveryStream) MarshalJSON() ([]byte, error) { - type Properties AWSKinesisFirehoseDeliveryStream - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKinesisFirehoseDeliveryStream) UnmarshalJSON(b []byte) error { - type Properties AWSKinesisFirehoseDeliveryStream - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKinesisFirehoseDeliveryStream(*res.Properties) - } - - return nil -} - -// GetAllAWSKinesisFirehoseDeliveryStreamResources retrieves all AWSKinesisFirehoseDeliveryStream items from an AWS CloudFormation template -func (t *Template) GetAllAWSKinesisFirehoseDeliveryStreamResources() map[string]AWSKinesisFirehoseDeliveryStream { - results := map[string]AWSKinesisFirehoseDeliveryStream{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKinesisFirehoseDeliveryStream: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisFirehose::DeliveryStream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisFirehoseDeliveryStream - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKinesisFirehoseDeliveryStreamWithName retrieves all AWSKinesisFirehoseDeliveryStream items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKinesisFirehoseDeliveryStreamWithName(name string) (AWSKinesisFirehoseDeliveryStream, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKinesisFirehoseDeliveryStream: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KinesisFirehose::DeliveryStream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKinesisFirehoseDeliveryStream - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKinesisFirehoseDeliveryStream{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_bufferinghints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_bufferinghints.go deleted file mode 100644 index 383d5b1225..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_bufferinghints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_BufferingHints AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.BufferingHints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-bufferinghints.html -type AWSKinesisFirehoseDeliveryStream_BufferingHints struct { - - // IntervalInSeconds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-bufferinghints.html#cfn-kinesisfirehose-deliverystream-bufferinghints-intervalinseconds - IntervalInSeconds int `json:"IntervalInSeconds,omitempty"` - - // SizeInMBs AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-bufferinghints.html#cfn-kinesisfirehose-deliverystream-bufferinghints-sizeinmbs - SizeInMBs int `json:"SizeInMBs,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_BufferingHints) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.BufferingHints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_cloudwatchloggingoptions.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_cloudwatchloggingoptions.go deleted file mode 100644 index df879c624b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_cloudwatchloggingoptions.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-cloudwatchloggingoptions.html -type AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions struct { - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-cloudwatchloggingoptions.html#cfn-kinesisfirehose-deliverystream-cloudwatchloggingoptions-enabled - Enabled bool `json:"Enabled,omitempty"` - - // LogGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-cloudwatchloggingoptions.html#cfn-kinesisfirehose-deliverystream-cloudwatchloggingoptions-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // LogStreamName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-cloudwatchloggingoptions.html#cfn-kinesisfirehose-deliverystream-cloudwatchloggingoptions-logstreamname - LogStreamName string `json:"LogStreamName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.CloudWatchLoggingOptions" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_copycommand.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_copycommand.go deleted file mode 100644 index 87b06369d4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_copycommand.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_CopyCommand AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.CopyCommand) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-copycommand.html -type AWSKinesisFirehoseDeliveryStream_CopyCommand struct { - - // CopyOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-copycommand.html#cfn-kinesisfirehose-deliverystream-copycommand-copyoptions - CopyOptions string `json:"CopyOptions,omitempty"` - - // DataTableColumns AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-copycommand.html#cfn-kinesisfirehose-deliverystream-copycommand-datatablecolumns - DataTableColumns string `json:"DataTableColumns,omitempty"` - - // DataTableName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-copycommand.html#cfn-kinesisfirehose-deliverystream-copycommand-datatablename - DataTableName string `json:"DataTableName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_CopyCommand) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.CopyCommand" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchbufferinghints.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchbufferinghints.go deleted file mode 100644 index 9587b382ed..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchbufferinghints.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ElasticsearchBufferingHints AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ElasticsearchBufferingHints) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchbufferinghints.html -type AWSKinesisFirehoseDeliveryStream_ElasticsearchBufferingHints struct { - - // IntervalInSeconds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchbufferinghints.html#cfn-kinesisfirehose-deliverystream-elasticsearchbufferinghints-intervalinseconds - IntervalInSeconds int `json:"IntervalInSeconds,omitempty"` - - // SizeInMBs AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchbufferinghints.html#cfn-kinesisfirehose-deliverystream-elasticsearchbufferinghints-sizeinmbs - SizeInMBs int `json:"SizeInMBs,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ElasticsearchBufferingHints) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ElasticsearchBufferingHints" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchdestinationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchdestinationconfiguration.go deleted file mode 100644 index eec3284282..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchdestinationconfiguration.go +++ /dev/null @@ -1,66 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ElasticsearchDestinationConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html -type AWSKinesisFirehoseDeliveryStream_ElasticsearchDestinationConfiguration struct { - - // BufferingHints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-bufferinghints - BufferingHints *AWSKinesisFirehoseDeliveryStream_ElasticsearchBufferingHints `json:"BufferingHints,omitempty"` - - // CloudWatchLoggingOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-cloudwatchloggingoptions - CloudWatchLoggingOptions *AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions `json:"CloudWatchLoggingOptions,omitempty"` - - // DomainARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-domainarn - DomainARN string `json:"DomainARN,omitempty"` - - // IndexName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-indexname - IndexName string `json:"IndexName,omitempty"` - - // IndexRotationPeriod AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-indexrotationperiod - IndexRotationPeriod string `json:"IndexRotationPeriod,omitempty"` - - // ProcessingConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-processingconfiguration - ProcessingConfiguration *AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration `json:"ProcessingConfiguration,omitempty"` - - // RetryOptions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-retryoptions - RetryOptions *AWSKinesisFirehoseDeliveryStream_ElasticsearchRetryOptions `json:"RetryOptions,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-rolearn - RoleARN string `json:"RoleARN,omitempty"` - - // S3BackupMode AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-s3backupmode - S3BackupMode string `json:"S3BackupMode,omitempty"` - - // S3Configuration AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-s3configuration - S3Configuration *AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration `json:"S3Configuration,omitempty"` - - // TypeName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-elasticsearchdestinationconfiguration-typename - TypeName string `json:"TypeName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ElasticsearchDestinationConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ElasticsearchDestinationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchretryoptions.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchretryoptions.go deleted file mode 100644 index 1dc3a45a2f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_elasticsearchretryoptions.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ElasticsearchRetryOptions AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchretryoptions.html -type AWSKinesisFirehoseDeliveryStream_ElasticsearchRetryOptions struct { - - // DurationInSeconds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-elasticsearchretryoptions.html#cfn-kinesisfirehose-deliverystream-elasticsearchretryoptions-durationinseconds - DurationInSeconds int `json:"DurationInSeconds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ElasticsearchRetryOptions) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ElasticsearchRetryOptions" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_encryptionconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_encryptionconfiguration.go deleted file mode 100644 index 0db5294e89..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_encryptionconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-encryptionconfiguration.html -type AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration struct { - - // KMSEncryptionConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-encryptionconfiguration.html#cfn-kinesisfirehose-deliverystream-encryptionconfiguration-kmsencryptionconfig - KMSEncryptionConfig *AWSKinesisFirehoseDeliveryStream_KMSEncryptionConfig `json:"KMSEncryptionConfig,omitempty"` - - // NoEncryptionConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-encryptionconfiguration.html#cfn-kinesisfirehose-deliverystream-encryptionconfiguration-noencryptionconfig - NoEncryptionConfig string `json:"NoEncryptionConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.EncryptionConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_extendeds3destinationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_extendeds3destinationconfiguration.go deleted file mode 100644 index c590387e59..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_extendeds3destinationconfiguration.go +++ /dev/null @@ -1,61 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ExtendedS3DestinationConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ExtendedS3DestinationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html -type AWSKinesisFirehoseDeliveryStream_ExtendedS3DestinationConfiguration struct { - - // BucketARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-bucketarn - BucketARN string `json:"BucketARN,omitempty"` - - // BufferingHints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-bufferinghints - BufferingHints *AWSKinesisFirehoseDeliveryStream_BufferingHints `json:"BufferingHints,omitempty"` - - // CloudWatchLoggingOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-cloudwatchloggingoptions - CloudWatchLoggingOptions *AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions `json:"CloudWatchLoggingOptions,omitempty"` - - // CompressionFormat AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-compressionformat - CompressionFormat string `json:"CompressionFormat,omitempty"` - - // EncryptionConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-encryptionconfiguration - EncryptionConfiguration *AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration `json:"EncryptionConfiguration,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-prefix - Prefix string `json:"Prefix,omitempty"` - - // ProcessingConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-processingconfiguration - ProcessingConfiguration *AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration `json:"ProcessingConfiguration,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-rolearn - RoleARN string `json:"RoleARN,omitempty"` - - // S3BackupConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-s3backupconfiguration - S3BackupConfiguration *AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration `json:"S3BackupConfiguration,omitempty"` - - // S3BackupMode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-extendeds3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-extendeds3destinationconfiguration-s3backupmode - S3BackupMode string `json:"S3BackupMode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ExtendedS3DestinationConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ExtendedS3DestinationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kinesisstreamsourceconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kinesisstreamsourceconfiguration.go deleted file mode 100644 index 5734d9b30d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kinesisstreamsourceconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_KinesisStreamSourceConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.KinesisStreamSourceConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration.html -type AWSKinesisFirehoseDeliveryStream_KinesisStreamSourceConfiguration struct { - - // KinesisStreamARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration.html#cfn-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration-kinesisstreamarn - KinesisStreamARN string `json:"KinesisStreamARN,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration.html#cfn-kinesisfirehose-deliverystream-kinesisstreamsourceconfiguration-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_KinesisStreamSourceConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.KinesisStreamSourceConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kmsencryptionconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kmsencryptionconfig.go deleted file mode 100644 index d0855bb096..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_kmsencryptionconfig.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_KMSEncryptionConfig AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.KMSEncryptionConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-kmsencryptionconfig.html -type AWSKinesisFirehoseDeliveryStream_KMSEncryptionConfig struct { - - // AWSKMSKeyARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-kmsencryptionconfig.html#cfn-kinesisfirehose-deliverystream-kmsencryptionconfig-awskmskeyarn - AWSKMSKeyARN string `json:"AWSKMSKeyARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_KMSEncryptionConfig) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.KMSEncryptionConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processingconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processingconfiguration.go deleted file mode 100644 index 7d9607ec51..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processingconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processingconfiguration.html -type AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration struct { - - // Enabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processingconfiguration.html#cfn-kinesisfirehose-deliverystream-processingconfiguration-enabled - Enabled bool `json:"Enabled,omitempty"` - - // Processors AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processingconfiguration.html#cfn-kinesisfirehose-deliverystream-processingconfiguration-processors - Processors []AWSKinesisFirehoseDeliveryStream_Processor `json:"Processors,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ProcessingConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processor.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processor.go deleted file mode 100644 index 7109525dab..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processor.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_Processor AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.Processor) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html -type AWSKinesisFirehoseDeliveryStream_Processor struct { - - // Parameters AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html#cfn-kinesisfirehose-deliverystream-processor-parameters - Parameters []AWSKinesisFirehoseDeliveryStream_ProcessorParameter `json:"Parameters,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processor.html#cfn-kinesisfirehose-deliverystream-processor-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_Processor) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.Processor" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processorparameter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processorparameter.go deleted file mode 100644 index e98dd787c5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_processorparameter.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_ProcessorParameter AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.ProcessorParameter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processorparameter.html -type AWSKinesisFirehoseDeliveryStream_ProcessorParameter struct { - - // ParameterName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processorparameter.html#cfn-kinesisfirehose-deliverystream-processorparameter-parametername - ParameterName string `json:"ParameterName,omitempty"` - - // ParameterValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-processorparameter.html#cfn-kinesisfirehose-deliverystream-processorparameter-parametervalue - ParameterValue string `json:"ParameterValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_ProcessorParameter) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.ProcessorParameter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_redshiftdestinationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_redshiftdestinationconfiguration.go deleted file mode 100644 index f67fb098a6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_redshiftdestinationconfiguration.go +++ /dev/null @@ -1,51 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_RedshiftDestinationConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.RedshiftDestinationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html -type AWSKinesisFirehoseDeliveryStream_RedshiftDestinationConfiguration struct { - - // CloudWatchLoggingOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-cloudwatchloggingoptions - CloudWatchLoggingOptions *AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions `json:"CloudWatchLoggingOptions,omitempty"` - - // ClusterJDBCURL AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-clusterjdbcurl - ClusterJDBCURL string `json:"ClusterJDBCURL,omitempty"` - - // CopyCommand AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-copycommand - CopyCommand *AWSKinesisFirehoseDeliveryStream_CopyCommand `json:"CopyCommand,omitempty"` - - // Password AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-password - Password string `json:"Password,omitempty"` - - // ProcessingConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-processingconfiguration - ProcessingConfiguration *AWSKinesisFirehoseDeliveryStream_ProcessingConfiguration `json:"ProcessingConfiguration,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-rolearn - RoleARN string `json:"RoleARN,omitempty"` - - // S3Configuration AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-s3configuration - S3Configuration *AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration `json:"S3Configuration,omitempty"` - - // Username AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-redshiftdestinationconfiguration.html#cfn-kinesisfirehose-deliverystream-redshiftdestinationconfiguration-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_RedshiftDestinationConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.RedshiftDestinationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_s3destinationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_s3destinationconfiguration.go deleted file mode 100644 index 12c0847fdb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kinesisfirehose-deliverystream_s3destinationconfiguration.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration AWS CloudFormation Resource (AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html -type AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration struct { - - // BucketARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-bucketarn - BucketARN string `json:"BucketARN,omitempty"` - - // BufferingHints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-bufferinghints - BufferingHints *AWSKinesisFirehoseDeliveryStream_BufferingHints `json:"BufferingHints,omitempty"` - - // CloudWatchLoggingOptions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-cloudwatchloggingoptions - CloudWatchLoggingOptions *AWSKinesisFirehoseDeliveryStream_CloudWatchLoggingOptions `json:"CloudWatchLoggingOptions,omitempty"` - - // CompressionFormat AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-compressionformat - CompressionFormat string `json:"CompressionFormat,omitempty"` - - // EncryptionConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-encryptionconfiguration - EncryptionConfiguration *AWSKinesisFirehoseDeliveryStream_EncryptionConfiguration `json:"EncryptionConfiguration,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-prefix - Prefix string `json:"Prefix,omitempty"` - - // RoleARN AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisfirehose-deliverystream-s3destinationconfiguration.html#cfn-kinesisfirehose-deliverystream-s3destinationconfiguration-rolearn - RoleARN string `json:"RoleARN,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKinesisFirehoseDeliveryStream_S3DestinationConfiguration) AWSCloudFormationType() string { - return "AWS::KinesisFirehose::DeliveryStream.S3DestinationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-alias.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-alias.go deleted file mode 100644 index d2a4b3feef..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-alias.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKMSAlias AWS CloudFormation Resource (AWS::KMS::Alias) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-alias.html -type AWSKMSAlias struct { - - // AliasName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-alias.html#cfn-kms-alias-aliasname - AliasName string `json:"AliasName,omitempty"` - - // TargetKeyId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-alias.html#cfn-kms-alias-targetkeyid - TargetKeyId string `json:"TargetKeyId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKMSAlias) AWSCloudFormationType() string { - return "AWS::KMS::Alias" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKMSAlias) MarshalJSON() ([]byte, error) { - type Properties AWSKMSAlias - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKMSAlias) UnmarshalJSON(b []byte) error { - type Properties AWSKMSAlias - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKMSAlias(*res.Properties) - } - - return nil -} - -// GetAllAWSKMSAliasResources retrieves all AWSKMSAlias items from an AWS CloudFormation template -func (t *Template) GetAllAWSKMSAliasResources() map[string]AWSKMSAlias { - results := map[string]AWSKMSAlias{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKMSAlias: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KMS::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKMSAlias - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKMSAliasWithName retrieves all AWSKMSAlias items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKMSAliasWithName(name string) (AWSKMSAlias, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKMSAlias: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KMS::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKMSAlias - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKMSAlias{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-key.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-key.go deleted file mode 100644 index a040b95a2f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-kms-key.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSKMSKey AWS CloudFormation Resource (AWS::KMS::Key) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html -type AWSKMSKey struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-description - Description string `json:"Description,omitempty"` - - // EnableKeyRotation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-enablekeyrotation - EnableKeyRotation bool `json:"EnableKeyRotation,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-enabled - Enabled bool `json:"Enabled,omitempty"` - - // KeyPolicy AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-keypolicy - KeyPolicy interface{} `json:"KeyPolicy,omitempty"` - - // KeyUsage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-keyusage - KeyUsage string `json:"KeyUsage,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-kms-key.html#cfn-kms-key-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSKMSKey) AWSCloudFormationType() string { - return "AWS::KMS::Key" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSKMSKey) MarshalJSON() ([]byte, error) { - type Properties AWSKMSKey - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSKMSKey) UnmarshalJSON(b []byte) error { - type Properties AWSKMSKey - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSKMSKey(*res.Properties) - } - - return nil -} - -// GetAllAWSKMSKeyResources retrieves all AWSKMSKey items from an AWS CloudFormation template -func (t *Template) GetAllAWSKMSKeyResources() map[string]AWSKMSKey { - results := map[string]AWSKMSKey{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSKMSKey: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KMS::Key" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKMSKey - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSKMSKeyWithName retrieves all AWSKMSKey items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSKMSKeyWithName(name string) (AWSKMSKey, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSKMSKey: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::KMS::Key" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSKMSKey - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSKMSKey{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias.go deleted file mode 100644 index 46a9cb60cf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLambdaAlias AWS CloudFormation Resource (AWS::Lambda::Alias) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html -type AWSLambdaAlias struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html#cfn-lambda-alias-description - Description string `json:"Description,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html#cfn-lambda-alias-functionname - FunctionName string `json:"FunctionName,omitempty"` - - // FunctionVersion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html#cfn-lambda-alias-functionversion - FunctionVersion string `json:"FunctionVersion,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html#cfn-lambda-alias-name - Name string `json:"Name,omitempty"` - - // RoutingConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-alias.html#cfn-lambda-alias-routingconfig - RoutingConfig *AWSLambdaAlias_AliasRoutingConfiguration `json:"RoutingConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaAlias) AWSCloudFormationType() string { - return "AWS::Lambda::Alias" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLambdaAlias) MarshalJSON() ([]byte, error) { - type Properties AWSLambdaAlias - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLambdaAlias) UnmarshalJSON(b []byte) error { - type Properties AWSLambdaAlias - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLambdaAlias(*res.Properties) - } - - return nil -} - -// GetAllAWSLambdaAliasResources retrieves all AWSLambdaAlias items from an AWS CloudFormation template -func (t *Template) GetAllAWSLambdaAliasResources() map[string]AWSLambdaAlias { - results := map[string]AWSLambdaAlias{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLambdaAlias: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaAlias - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLambdaAliasWithName retrieves all AWSLambdaAlias items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLambdaAliasWithName(name string) (AWSLambdaAlias, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLambdaAlias: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Alias" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaAlias - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLambdaAlias{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_aliasroutingconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_aliasroutingconfiguration.go deleted file mode 100644 index c7d9d2b96f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_aliasroutingconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSLambdaAlias_AliasRoutingConfiguration AWS CloudFormation Resource (AWS::Lambda::Alias.AliasRoutingConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-aliasroutingconfiguration.html -type AWSLambdaAlias_AliasRoutingConfiguration struct { - - // AdditionalVersionWeights AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-aliasroutingconfiguration.html#cfn-lambda-alias-aliasroutingconfiguration-additionalversionweights - AdditionalVersionWeights []AWSLambdaAlias_VersionWeight `json:"AdditionalVersionWeights,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaAlias_AliasRoutingConfiguration) AWSCloudFormationType() string { - return "AWS::Lambda::Alias.AliasRoutingConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_versionweight.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_versionweight.go deleted file mode 100644 index 52055cd478..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-alias_versionweight.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSLambdaAlias_VersionWeight AWS CloudFormation Resource (AWS::Lambda::Alias.VersionWeight) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-versionweight.html -type AWSLambdaAlias_VersionWeight struct { - - // FunctionVersion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-versionweight.html#cfn-lambda-alias-versionweight-functionversion - FunctionVersion string `json:"FunctionVersion,omitempty"` - - // FunctionWeight AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-alias-versionweight.html#cfn-lambda-alias-versionweight-functionweight - FunctionWeight float64 `json:"FunctionWeight,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaAlias_VersionWeight) AWSCloudFormationType() string { - return "AWS::Lambda::Alias.VersionWeight" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-eventsourcemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-eventsourcemapping.go deleted file mode 100644 index 80959a497c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-eventsourcemapping.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLambdaEventSourceMapping AWS CloudFormation Resource (AWS::Lambda::EventSourceMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html -type AWSLambdaEventSourceMapping struct { - - // BatchSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-batchsize - BatchSize int `json:"BatchSize,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-enabled - Enabled bool `json:"Enabled,omitempty"` - - // EventSourceArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-eventsourcearn - EventSourceArn string `json:"EventSourceArn,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-functionname - FunctionName string `json:"FunctionName,omitempty"` - - // StartingPosition AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-eventsourcemapping.html#cfn-lambda-eventsourcemapping-startingposition - StartingPosition string `json:"StartingPosition,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaEventSourceMapping) AWSCloudFormationType() string { - return "AWS::Lambda::EventSourceMapping" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLambdaEventSourceMapping) MarshalJSON() ([]byte, error) { - type Properties AWSLambdaEventSourceMapping - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLambdaEventSourceMapping) UnmarshalJSON(b []byte) error { - type Properties AWSLambdaEventSourceMapping - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLambdaEventSourceMapping(*res.Properties) - } - - return nil -} - -// GetAllAWSLambdaEventSourceMappingResources retrieves all AWSLambdaEventSourceMapping items from an AWS CloudFormation template -func (t *Template) GetAllAWSLambdaEventSourceMappingResources() map[string]AWSLambdaEventSourceMapping { - results := map[string]AWSLambdaEventSourceMapping{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLambdaEventSourceMapping: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::EventSourceMapping" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaEventSourceMapping - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLambdaEventSourceMappingWithName retrieves all AWSLambdaEventSourceMapping items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLambdaEventSourceMappingWithName(name string) (AWSLambdaEventSourceMapping, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLambdaEventSourceMapping: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::EventSourceMapping" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaEventSourceMapping - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLambdaEventSourceMapping{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function.go deleted file mode 100644 index 2fc0b5e2d0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function.go +++ /dev/null @@ -1,175 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLambdaFunction AWS CloudFormation Resource (AWS::Lambda::Function) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html -type AWSLambdaFunction struct { - - // Code AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-code - Code *AWSLambdaFunction_Code `json:"Code,omitempty"` - - // DeadLetterConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-deadletterconfig - DeadLetterConfig *AWSLambdaFunction_DeadLetterConfig `json:"DeadLetterConfig,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-description - Description string `json:"Description,omitempty"` - - // Environment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-environment - Environment *AWSLambdaFunction_Environment `json:"Environment,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-functionname - FunctionName string `json:"FunctionName,omitempty"` - - // Handler AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-handler - Handler string `json:"Handler,omitempty"` - - // KmsKeyArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-kmskeyarn - KmsKeyArn string `json:"KmsKeyArn,omitempty"` - - // MemorySize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-memorysize - MemorySize int `json:"MemorySize,omitempty"` - - // Role AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-role - Role string `json:"Role,omitempty"` - - // Runtime AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-runtime - Runtime string `json:"Runtime,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-tags - Tags []Tag `json:"Tags,omitempty"` - - // Timeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-timeout - Timeout int `json:"Timeout,omitempty"` - - // TracingConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-tracingconfig - TracingConfig *AWSLambdaFunction_TracingConfig `json:"TracingConfig,omitempty"` - - // VpcConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-function.html#cfn-lambda-function-vpcconfig - VpcConfig *AWSLambdaFunction_VpcConfig `json:"VpcConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction) AWSCloudFormationType() string { - return "AWS::Lambda::Function" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLambdaFunction) MarshalJSON() ([]byte, error) { - type Properties AWSLambdaFunction - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLambdaFunction) UnmarshalJSON(b []byte) error { - type Properties AWSLambdaFunction - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLambdaFunction(*res.Properties) - } - - return nil -} - -// GetAllAWSLambdaFunctionResources retrieves all AWSLambdaFunction items from an AWS CloudFormation template -func (t *Template) GetAllAWSLambdaFunctionResources() map[string]AWSLambdaFunction { - results := map[string]AWSLambdaFunction{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLambdaFunction: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Function" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaFunction - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLambdaFunctionWithName retrieves all AWSLambdaFunction items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLambdaFunctionWithName(name string) (AWSLambdaFunction, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLambdaFunction: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Function" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaFunction - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLambdaFunction{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_code.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_code.go deleted file mode 100644 index 5e10d5b03b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_code.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSLambdaFunction_Code AWS CloudFormation Resource (AWS::Lambda::Function.Code) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html -type AWSLambdaFunction_Code struct { - - // S3Bucket AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#cfn-lambda-function-code-s3bucket - S3Bucket string `json:"S3Bucket,omitempty"` - - // S3Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#cfn-lambda-function-code-s3key - S3Key string `json:"S3Key,omitempty"` - - // S3ObjectVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#cfn-lambda-function-code-s3objectversion - S3ObjectVersion string `json:"S3ObjectVersion,omitempty"` - - // ZipFile AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-code.html#cfn-lambda-function-code-zipfile - ZipFile string `json:"ZipFile,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction_Code) AWSCloudFormationType() string { - return "AWS::Lambda::Function.Code" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_deadletterconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_deadletterconfig.go deleted file mode 100644 index 30b9655a7c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_deadletterconfig.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSLambdaFunction_DeadLetterConfig AWS CloudFormation Resource (AWS::Lambda::Function.DeadLetterConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-deadletterconfig.html -type AWSLambdaFunction_DeadLetterConfig struct { - - // TargetArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-deadletterconfig.html#cfn-lambda-function-deadletterconfig-targetarn - TargetArn string `json:"TargetArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction_DeadLetterConfig) AWSCloudFormationType() string { - return "AWS::Lambda::Function.DeadLetterConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_environment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_environment.go deleted file mode 100644 index 22ba7b5e17..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_environment.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSLambdaFunction_Environment AWS CloudFormation Resource (AWS::Lambda::Function.Environment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-environment.html -type AWSLambdaFunction_Environment struct { - - // Variables AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-environment.html#cfn-lambda-function-environment-variables - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction_Environment) AWSCloudFormationType() string { - return "AWS::Lambda::Function.Environment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_tracingconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_tracingconfig.go deleted file mode 100644 index 5be394e38c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_tracingconfig.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSLambdaFunction_TracingConfig AWS CloudFormation Resource (AWS::Lambda::Function.TracingConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-tracingconfig.html -type AWSLambdaFunction_TracingConfig struct { - - // Mode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-tracingconfig.html#cfn-lambda-function-tracingconfig-mode - Mode string `json:"Mode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction_TracingConfig) AWSCloudFormationType() string { - return "AWS::Lambda::Function.TracingConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_vpcconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_vpcconfig.go deleted file mode 100644 index 3a16ed86a9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-function_vpcconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSLambdaFunction_VpcConfig AWS CloudFormation Resource (AWS::Lambda::Function.VpcConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html -type AWSLambdaFunction_VpcConfig struct { - - // SecurityGroupIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html#cfn-lambda-function-vpcconfig-securitygroupids - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html#cfn-lambda-function-vpcconfig-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaFunction_VpcConfig) AWSCloudFormationType() string { - return "AWS::Lambda::Function.VpcConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-permission.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-permission.go deleted file mode 100644 index f8cf6a1b34..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-permission.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLambdaPermission AWS CloudFormation Resource (AWS::Lambda::Permission) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html -type AWSLambdaPermission struct { - - // Action AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-action - Action string `json:"Action,omitempty"` - - // EventSourceToken AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-eventsourcetoken - EventSourceToken string `json:"EventSourceToken,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-functionname - FunctionName string `json:"FunctionName,omitempty"` - - // Principal AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-principal - Principal string `json:"Principal,omitempty"` - - // SourceAccount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-sourceaccount - SourceAccount string `json:"SourceAccount,omitempty"` - - // SourceArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-permission.html#cfn-lambda-permission-sourcearn - SourceArn string `json:"SourceArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaPermission) AWSCloudFormationType() string { - return "AWS::Lambda::Permission" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLambdaPermission) MarshalJSON() ([]byte, error) { - type Properties AWSLambdaPermission - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLambdaPermission) UnmarshalJSON(b []byte) error { - type Properties AWSLambdaPermission - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLambdaPermission(*res.Properties) - } - - return nil -} - -// GetAllAWSLambdaPermissionResources retrieves all AWSLambdaPermission items from an AWS CloudFormation template -func (t *Template) GetAllAWSLambdaPermissionResources() map[string]AWSLambdaPermission { - results := map[string]AWSLambdaPermission{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLambdaPermission: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Permission" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaPermission - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLambdaPermissionWithName retrieves all AWSLambdaPermission items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLambdaPermissionWithName(name string) (AWSLambdaPermission, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLambdaPermission: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Permission" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaPermission - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLambdaPermission{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-version.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-version.go deleted file mode 100644 index d5f8aa6aed..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-lambda-version.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLambdaVersion AWS CloudFormation Resource (AWS::Lambda::Version) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-version.html -type AWSLambdaVersion struct { - - // CodeSha256 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-version.html#cfn-lambda-version-codesha256 - CodeSha256 string `json:"CodeSha256,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-version.html#cfn-lambda-version-description - Description string `json:"Description,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-version.html#cfn-lambda-version-functionname - FunctionName string `json:"FunctionName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLambdaVersion) AWSCloudFormationType() string { - return "AWS::Lambda::Version" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLambdaVersion) MarshalJSON() ([]byte, error) { - type Properties AWSLambdaVersion - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLambdaVersion) UnmarshalJSON(b []byte) error { - type Properties AWSLambdaVersion - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLambdaVersion(*res.Properties) - } - - return nil -} - -// GetAllAWSLambdaVersionResources retrieves all AWSLambdaVersion items from an AWS CloudFormation template -func (t *Template) GetAllAWSLambdaVersionResources() map[string]AWSLambdaVersion { - results := map[string]AWSLambdaVersion{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLambdaVersion: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Version" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaVersion - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLambdaVersionWithName retrieves all AWSLambdaVersion items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLambdaVersionWithName(name string) (AWSLambdaVersion, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLambdaVersion: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Lambda::Version" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLambdaVersion - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLambdaVersion{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-destination.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-destination.go deleted file mode 100644 index 42e21e3dec..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-destination.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLogsDestination AWS CloudFormation Resource (AWS::Logs::Destination) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-destination.html -type AWSLogsDestination struct { - - // DestinationName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-destination.html#cfn-logs-destination-destinationname - DestinationName string `json:"DestinationName,omitempty"` - - // DestinationPolicy AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-destination.html#cfn-logs-destination-destinationpolicy - DestinationPolicy string `json:"DestinationPolicy,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-destination.html#cfn-logs-destination-rolearn - RoleArn string `json:"RoleArn,omitempty"` - - // TargetArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-destination.html#cfn-logs-destination-targetarn - TargetArn string `json:"TargetArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsDestination) AWSCloudFormationType() string { - return "AWS::Logs::Destination" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLogsDestination) MarshalJSON() ([]byte, error) { - type Properties AWSLogsDestination - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLogsDestination) UnmarshalJSON(b []byte) error { - type Properties AWSLogsDestination - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLogsDestination(*res.Properties) - } - - return nil -} - -// GetAllAWSLogsDestinationResources retrieves all AWSLogsDestination items from an AWS CloudFormation template -func (t *Template) GetAllAWSLogsDestinationResources() map[string]AWSLogsDestination { - results := map[string]AWSLogsDestination{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLogsDestination: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::Destination" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsDestination - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLogsDestinationWithName retrieves all AWSLogsDestination items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLogsDestinationWithName(name string) (AWSLogsDestination, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLogsDestination: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::Destination" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsDestination - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLogsDestination{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-loggroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-loggroup.go deleted file mode 100644 index ee4b644caa..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-loggroup.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLogsLogGroup AWS CloudFormation Resource (AWS::Logs::LogGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html -type AWSLogsLogGroup struct { - - // LogGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html#cfn-cwl-loggroup-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // RetentionInDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-loggroup.html#cfn-cwl-loggroup-retentionindays - RetentionInDays int `json:"RetentionInDays,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsLogGroup) AWSCloudFormationType() string { - return "AWS::Logs::LogGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLogsLogGroup) MarshalJSON() ([]byte, error) { - type Properties AWSLogsLogGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLogsLogGroup) UnmarshalJSON(b []byte) error { - type Properties AWSLogsLogGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLogsLogGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSLogsLogGroupResources retrieves all AWSLogsLogGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSLogsLogGroupResources() map[string]AWSLogsLogGroup { - results := map[string]AWSLogsLogGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLogsLogGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::LogGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsLogGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLogsLogGroupWithName retrieves all AWSLogsLogGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLogsLogGroupWithName(name string) (AWSLogsLogGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLogsLogGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::LogGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsLogGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLogsLogGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-logstream.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-logstream.go deleted file mode 100644 index 759df4d289..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-logstream.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLogsLogStream AWS CloudFormation Resource (AWS::Logs::LogStream) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-logstream.html -type AWSLogsLogStream struct { - - // LogGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-logstream.html#cfn-logs-logstream-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // LogStreamName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-logstream.html#cfn-logs-logstream-logstreamname - LogStreamName string `json:"LogStreamName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsLogStream) AWSCloudFormationType() string { - return "AWS::Logs::LogStream" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLogsLogStream) MarshalJSON() ([]byte, error) { - type Properties AWSLogsLogStream - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLogsLogStream) UnmarshalJSON(b []byte) error { - type Properties AWSLogsLogStream - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLogsLogStream(*res.Properties) - } - - return nil -} - -// GetAllAWSLogsLogStreamResources retrieves all AWSLogsLogStream items from an AWS CloudFormation template -func (t *Template) GetAllAWSLogsLogStreamResources() map[string]AWSLogsLogStream { - results := map[string]AWSLogsLogStream{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLogsLogStream: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::LogStream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsLogStream - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLogsLogStreamWithName retrieves all AWSLogsLogStream items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLogsLogStreamWithName(name string) (AWSLogsLogStream, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLogsLogStream: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::LogStream" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsLogStream - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLogsLogStream{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter.go deleted file mode 100644 index 269184afcc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLogsMetricFilter AWS CloudFormation Resource (AWS::Logs::MetricFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-metricfilter.html -type AWSLogsMetricFilter struct { - - // FilterPattern AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-metricfilter.html#cfn-cwl-metricfilter-filterpattern - FilterPattern string `json:"FilterPattern,omitempty"` - - // LogGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-metricfilter.html#cfn-cwl-metricfilter-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // MetricTransformations AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-metricfilter.html#cfn-cwl-metricfilter-metrictransformations - MetricTransformations []AWSLogsMetricFilter_MetricTransformation `json:"MetricTransformations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsMetricFilter) AWSCloudFormationType() string { - return "AWS::Logs::MetricFilter" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLogsMetricFilter) MarshalJSON() ([]byte, error) { - type Properties AWSLogsMetricFilter - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLogsMetricFilter) UnmarshalJSON(b []byte) error { - type Properties AWSLogsMetricFilter - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLogsMetricFilter(*res.Properties) - } - - return nil -} - -// GetAllAWSLogsMetricFilterResources retrieves all AWSLogsMetricFilter items from an AWS CloudFormation template -func (t *Template) GetAllAWSLogsMetricFilterResources() map[string]AWSLogsMetricFilter { - results := map[string]AWSLogsMetricFilter{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLogsMetricFilter: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::MetricFilter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsMetricFilter - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLogsMetricFilterWithName retrieves all AWSLogsMetricFilter items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLogsMetricFilterWithName(name string) (AWSLogsMetricFilter, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLogsMetricFilter: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::MetricFilter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsMetricFilter - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLogsMetricFilter{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter_metrictransformation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter_metrictransformation.go deleted file mode 100644 index acc893a076..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-metricfilter_metrictransformation.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSLogsMetricFilter_MetricTransformation AWS CloudFormation Resource (AWS::Logs::MetricFilter.MetricTransformation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html -type AWSLogsMetricFilter_MetricTransformation struct { - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html#cfn-cwl-metricfilter-metrictransformation-metricname - MetricName string `json:"MetricName,omitempty"` - - // MetricNamespace AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html#cfn-cwl-metricfilter-metrictransformation-metricnamespace - MetricNamespace string `json:"MetricNamespace,omitempty"` - - // MetricValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-logs-metricfilter-metrictransformation.html#cfn-cwl-metricfilter-metrictransformation-metricvalue - MetricValue string `json:"MetricValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsMetricFilter_MetricTransformation) AWSCloudFormationType() string { - return "AWS::Logs::MetricFilter.MetricTransformation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-subscriptionfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-subscriptionfilter.go deleted file mode 100644 index 41fb684a39..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-logs-subscriptionfilter.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSLogsSubscriptionFilter AWS CloudFormation Resource (AWS::Logs::SubscriptionFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html -type AWSLogsSubscriptionFilter struct { - - // DestinationArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html#cfn-cwl-subscriptionfilter-destinationarn - DestinationArn string `json:"DestinationArn,omitempty"` - - // FilterPattern AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html#cfn-cwl-subscriptionfilter-filterpattern - FilterPattern string `json:"FilterPattern,omitempty"` - - // LogGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html#cfn-cwl-subscriptionfilter-loggroupname - LogGroupName string `json:"LogGroupName,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-logs-subscriptionfilter.html#cfn-cwl-subscriptionfilter-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSLogsSubscriptionFilter) AWSCloudFormationType() string { - return "AWS::Logs::SubscriptionFilter" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSLogsSubscriptionFilter) MarshalJSON() ([]byte, error) { - type Properties AWSLogsSubscriptionFilter - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSLogsSubscriptionFilter) UnmarshalJSON(b []byte) error { - type Properties AWSLogsSubscriptionFilter - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSLogsSubscriptionFilter(*res.Properties) - } - - return nil -} - -// GetAllAWSLogsSubscriptionFilterResources retrieves all AWSLogsSubscriptionFilter items from an AWS CloudFormation template -func (t *Template) GetAllAWSLogsSubscriptionFilterResources() map[string]AWSLogsSubscriptionFilter { - results := map[string]AWSLogsSubscriptionFilter{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSLogsSubscriptionFilter: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::SubscriptionFilter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsSubscriptionFilter - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSLogsSubscriptionFilterWithName retrieves all AWSLogsSubscriptionFilter items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSLogsSubscriptionFilterWithName(name string) (AWSLogsSubscriptionFilter, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSLogsSubscriptionFilter: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Logs::SubscriptionFilter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSLogsSubscriptionFilter - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSLogsSubscriptionFilter{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app.go deleted file mode 100644 index a5a6772cbe..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app.go +++ /dev/null @@ -1,165 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksApp AWS CloudFormation Resource (AWS::OpsWorks::App) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html -type AWSOpsWorksApp struct { - - // AppSource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-appsource - AppSource *AWSOpsWorksApp_Source `json:"AppSource,omitempty"` - - // Attributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-attributes - Attributes map[string]string `json:"Attributes,omitempty"` - - // DataSources AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-datasources - DataSources []AWSOpsWorksApp_DataSource `json:"DataSources,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-description - Description string `json:"Description,omitempty"` - - // Domains AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-domains - Domains []string `json:"Domains,omitempty"` - - // EnableSsl AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-enablessl - EnableSsl bool `json:"EnableSsl,omitempty"` - - // Environment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-environment - Environment []AWSOpsWorksApp_EnvironmentVariable `json:"Environment,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-name - Name string `json:"Name,omitempty"` - - // Shortname AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-shortname - Shortname string `json:"Shortname,omitempty"` - - // SslConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-sslconfiguration - SslConfiguration *AWSOpsWorksApp_SslConfiguration `json:"SslConfiguration,omitempty"` - - // StackId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-stackid - StackId string `json:"StackId,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-app.html#cfn-opsworks-app-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksApp) AWSCloudFormationType() string { - return "AWS::OpsWorks::App" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksApp) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksApp - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksApp) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksApp - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksApp(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksAppResources retrieves all AWSOpsWorksApp items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksAppResources() map[string]AWSOpsWorksApp { - results := map[string]AWSOpsWorksApp{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksApp: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::App" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksApp - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksAppWithName retrieves all AWSOpsWorksApp items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksAppWithName(name string) (AWSOpsWorksApp, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksApp: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::App" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksApp - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksApp{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_datasource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_datasource.go deleted file mode 100644 index 0ab4e17ffd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_datasource.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSOpsWorksApp_DataSource AWS CloudFormation Resource (AWS::OpsWorks::App.DataSource) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-datasource.html -type AWSOpsWorksApp_DataSource struct { - - // Arn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-datasource.html#cfn-opsworks-app-datasource-arn - Arn string `json:"Arn,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-datasource.html#cfn-opsworks-app-datasource-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-datasource.html#cfn-opsworks-app-datasource-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksApp_DataSource) AWSCloudFormationType() string { - return "AWS::OpsWorks::App.DataSource" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_environmentvariable.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_environmentvariable.go deleted file mode 100644 index 80c2a9638f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_environmentvariable.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSOpsWorksApp_EnvironmentVariable AWS CloudFormation Resource (AWS::OpsWorks::App.EnvironmentVariable) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html -type AWSOpsWorksApp_EnvironmentVariable struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#cfn-opsworks-app-environment-key - Key string `json:"Key,omitempty"` - - // Secure AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#cfn-opsworks-app-environment-secure - Secure bool `json:"Secure,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-environment.html#value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksApp_EnvironmentVariable) AWSCloudFormationType() string { - return "AWS::OpsWorks::App.EnvironmentVariable" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_source.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_source.go deleted file mode 100644 index ac8c74b1da..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_source.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSOpsWorksApp_Source AWS CloudFormation Resource (AWS::OpsWorks::App.Source) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html -type AWSOpsWorksApp_Source struct { - - // Password AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-pw - Password string `json:"Password,omitempty"` - - // Revision AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-revision - Revision string `json:"Revision,omitempty"` - - // SshKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-sshkey - SshKey string `json:"SshKey,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-type - Type string `json:"Type,omitempty"` - - // Url AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-url - Url string `json:"Url,omitempty"` - - // Username AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksApp_Source) AWSCloudFormationType() string { - return "AWS::OpsWorks::App.Source" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_sslconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_sslconfiguration.go deleted file mode 100644 index 7ab0ad8704..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-app_sslconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSOpsWorksApp_SslConfiguration AWS CloudFormation Resource (AWS::OpsWorks::App.SslConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-sslconfiguration.html -type AWSOpsWorksApp_SslConfiguration struct { - - // Certificate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-sslconfiguration.html#cfn-opsworks-app-sslconfig-certificate - Certificate string `json:"Certificate,omitempty"` - - // Chain AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-sslconfiguration.html#cfn-opsworks-app-sslconfig-chain - Chain string `json:"Chain,omitempty"` - - // PrivateKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-app-sslconfiguration.html#cfn-opsworks-app-sslconfig-privatekey - PrivateKey string `json:"PrivateKey,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksApp_SslConfiguration) AWSCloudFormationType() string { - return "AWS::OpsWorks::App.SslConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-elasticloadbalancerattachment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-elasticloadbalancerattachment.go deleted file mode 100644 index a3405b2101..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-elasticloadbalancerattachment.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksElasticLoadBalancerAttachment AWS CloudFormation Resource (AWS::OpsWorks::ElasticLoadBalancerAttachment) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html -type AWSOpsWorksElasticLoadBalancerAttachment struct { - - // ElasticLoadBalancerName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html#cfn-opsworks-elbattachment-elbname - ElasticLoadBalancerName string `json:"ElasticLoadBalancerName,omitempty"` - - // LayerId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-elbattachment.html#cfn-opsworks-elbattachment-layerid - LayerId string `json:"LayerId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksElasticLoadBalancerAttachment) AWSCloudFormationType() string { - return "AWS::OpsWorks::ElasticLoadBalancerAttachment" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksElasticLoadBalancerAttachment) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksElasticLoadBalancerAttachment - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksElasticLoadBalancerAttachment) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksElasticLoadBalancerAttachment - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksElasticLoadBalancerAttachment(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksElasticLoadBalancerAttachmentResources retrieves all AWSOpsWorksElasticLoadBalancerAttachment items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksElasticLoadBalancerAttachmentResources() map[string]AWSOpsWorksElasticLoadBalancerAttachment { - results := map[string]AWSOpsWorksElasticLoadBalancerAttachment{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksElasticLoadBalancerAttachment: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::ElasticLoadBalancerAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksElasticLoadBalancerAttachment - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksElasticLoadBalancerAttachmentWithName retrieves all AWSOpsWorksElasticLoadBalancerAttachment items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksElasticLoadBalancerAttachmentWithName(name string) (AWSOpsWorksElasticLoadBalancerAttachment, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksElasticLoadBalancerAttachment: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::ElasticLoadBalancerAttachment" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksElasticLoadBalancerAttachment - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksElasticLoadBalancerAttachment{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance.go deleted file mode 100644 index e8fbef024a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance.go +++ /dev/null @@ -1,210 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksInstance AWS CloudFormation Resource (AWS::OpsWorks::Instance) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html -type AWSOpsWorksInstance struct { - - // AgentVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-agentversion - AgentVersion string `json:"AgentVersion,omitempty"` - - // AmiId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-amiid - AmiId string `json:"AmiId,omitempty"` - - // Architecture AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-architecture - Architecture string `json:"Architecture,omitempty"` - - // AutoScalingType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-autoscalingtype - AutoScalingType string `json:"AutoScalingType,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // BlockDeviceMappings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-blockdevicemappings - BlockDeviceMappings []AWSOpsWorksInstance_BlockDeviceMapping `json:"BlockDeviceMappings,omitempty"` - - // EbsOptimized AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-ebsoptimized - EbsOptimized bool `json:"EbsOptimized,omitempty"` - - // ElasticIps AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-elasticips - ElasticIps []string `json:"ElasticIps,omitempty"` - - // Hostname AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-hostname - Hostname string `json:"Hostname,omitempty"` - - // InstallUpdatesOnBoot AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-installupdatesonboot - InstallUpdatesOnBoot bool `json:"InstallUpdatesOnBoot,omitempty"` - - // InstanceType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-instancetype - InstanceType string `json:"InstanceType,omitempty"` - - // LayerIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-layerids - LayerIds []string `json:"LayerIds,omitempty"` - - // Os AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-os - Os string `json:"Os,omitempty"` - - // RootDeviceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-rootdevicetype - RootDeviceType string `json:"RootDeviceType,omitempty"` - - // SshKeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-sshkeyname - SshKeyName string `json:"SshKeyName,omitempty"` - - // StackId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-stackid - StackId string `json:"StackId,omitempty"` - - // SubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-subnetid - SubnetId string `json:"SubnetId,omitempty"` - - // Tenancy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-tenancy - Tenancy string `json:"Tenancy,omitempty"` - - // TimeBasedAutoScaling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-timebasedautoscaling - TimeBasedAutoScaling *AWSOpsWorksInstance_TimeBasedAutoScaling `json:"TimeBasedAutoScaling,omitempty"` - - // VirtualizationType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-virtualizationtype - VirtualizationType string `json:"VirtualizationType,omitempty"` - - // Volumes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-instance.html#cfn-opsworks-instance-volumes - Volumes []string `json:"Volumes,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksInstance) AWSCloudFormationType() string { - return "AWS::OpsWorks::Instance" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksInstance) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksInstance - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksInstance) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksInstance - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksInstance(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksInstanceResources retrieves all AWSOpsWorksInstance items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksInstanceResources() map[string]AWSOpsWorksInstance { - results := map[string]AWSOpsWorksInstance{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksInstance: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Instance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksInstance - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksInstanceWithName retrieves all AWSOpsWorksInstance items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksInstanceWithName(name string) (AWSOpsWorksInstance, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksInstance: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Instance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksInstance - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksInstance{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_blockdevicemapping.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_blockdevicemapping.go deleted file mode 100644 index 41505a1bb0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_blockdevicemapping.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSOpsWorksInstance_BlockDeviceMapping AWS CloudFormation Resource (AWS::OpsWorks::Instance.BlockDeviceMapping) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html -type AWSOpsWorksInstance_BlockDeviceMapping struct { - - // DeviceName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-devicename - DeviceName string `json:"DeviceName,omitempty"` - - // Ebs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-ebs - Ebs *AWSOpsWorksInstance_EbsBlockDevice `json:"Ebs,omitempty"` - - // NoDevice AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-nodevice - NoDevice string `json:"NoDevice,omitempty"` - - // VirtualName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-blockdevicemapping.html#cfn-opsworks-instance-blockdevicemapping-virtualname - VirtualName string `json:"VirtualName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksInstance_BlockDeviceMapping) AWSCloudFormationType() string { - return "AWS::OpsWorks::Instance.BlockDeviceMapping" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_ebsblockdevice.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_ebsblockdevice.go deleted file mode 100644 index bc3f2a4c82..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_ebsblockdevice.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSOpsWorksInstance_EbsBlockDevice AWS CloudFormation Resource (AWS::OpsWorks::Instance.EbsBlockDevice) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html -type AWSOpsWorksInstance_EbsBlockDevice struct { - - // DeleteOnTermination AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-deleteontermination - DeleteOnTermination bool `json:"DeleteOnTermination,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-iops - Iops int `json:"Iops,omitempty"` - - // SnapshotId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-snapshotid - SnapshotId string `json:"SnapshotId,omitempty"` - - // VolumeSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumesize - VolumeSize int `json:"VolumeSize,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-ebsblockdevice.html#cfn-opsworks-instance-ebsblockdevice-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksInstance_EbsBlockDevice) AWSCloudFormationType() string { - return "AWS::OpsWorks::Instance.EbsBlockDevice" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_timebasedautoscaling.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_timebasedautoscaling.go deleted file mode 100644 index 768e19780c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-instance_timebasedautoscaling.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSOpsWorksInstance_TimeBasedAutoScaling AWS CloudFormation Resource (AWS::OpsWorks::Instance.TimeBasedAutoScaling) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html -type AWSOpsWorksInstance_TimeBasedAutoScaling struct { - - // Friday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-friday - Friday map[string]string `json:"Friday,omitempty"` - - // Monday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-monday - Monday map[string]string `json:"Monday,omitempty"` - - // Saturday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-saturday - Saturday map[string]string `json:"Saturday,omitempty"` - - // Sunday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-sunday - Sunday map[string]string `json:"Sunday,omitempty"` - - // Thursday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-thursday - Thursday map[string]string `json:"Thursday,omitempty"` - - // Tuesday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-tuesday - Tuesday map[string]string `json:"Tuesday,omitempty"` - - // Wednesday AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-instance-timebasedautoscaling.html#cfn-opsworks-instance-timebasedautoscaling-wednesday - Wednesday map[string]string `json:"Wednesday,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksInstance_TimeBasedAutoScaling) AWSCloudFormationType() string { - return "AWS::OpsWorks::Instance.TimeBasedAutoScaling" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer.go deleted file mode 100644 index 39b425c79a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer.go +++ /dev/null @@ -1,200 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksLayer AWS CloudFormation Resource (AWS::OpsWorks::Layer) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html -type AWSOpsWorksLayer struct { - - // Attributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-attributes - Attributes map[string]string `json:"Attributes,omitempty"` - - // AutoAssignElasticIps AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-autoassignelasticips - AutoAssignElasticIps bool `json:"AutoAssignElasticIps,omitempty"` - - // AutoAssignPublicIps AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-autoassignpublicips - AutoAssignPublicIps bool `json:"AutoAssignPublicIps,omitempty"` - - // CustomInstanceProfileArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-custominstanceprofilearn - CustomInstanceProfileArn string `json:"CustomInstanceProfileArn,omitempty"` - - // CustomJson AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customjson - CustomJson interface{} `json:"CustomJson,omitempty"` - - // CustomRecipes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customrecipes - CustomRecipes *AWSOpsWorksLayer_Recipes `json:"CustomRecipes,omitempty"` - - // CustomSecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-customsecuritygroupids - CustomSecurityGroupIds []string `json:"CustomSecurityGroupIds,omitempty"` - - // EnableAutoHealing AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-enableautohealing - EnableAutoHealing bool `json:"EnableAutoHealing,omitempty"` - - // InstallUpdatesOnBoot AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-installupdatesonboot - InstallUpdatesOnBoot bool `json:"InstallUpdatesOnBoot,omitempty"` - - // LifecycleEventConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-lifecycleeventconfiguration - LifecycleEventConfiguration *AWSOpsWorksLayer_LifecycleEventConfiguration `json:"LifecycleEventConfiguration,omitempty"` - - // LoadBasedAutoScaling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-loadbasedautoscaling - LoadBasedAutoScaling *AWSOpsWorksLayer_LoadBasedAutoScaling `json:"LoadBasedAutoScaling,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-name - Name string `json:"Name,omitempty"` - - // Packages AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-packages - Packages []string `json:"Packages,omitempty"` - - // Shortname AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-shortname - Shortname string `json:"Shortname,omitempty"` - - // StackId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-stackid - StackId string `json:"StackId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-tags - Tags []Tag `json:"Tags,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-type - Type string `json:"Type,omitempty"` - - // UseEbsOptimizedInstances AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-useebsoptimizedinstances - UseEbsOptimizedInstances bool `json:"UseEbsOptimizedInstances,omitempty"` - - // VolumeConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-layer.html#cfn-opsworks-layer-volumeconfigurations - VolumeConfigurations []AWSOpsWorksLayer_VolumeConfiguration `json:"VolumeConfigurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksLayer) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksLayer - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksLayer) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksLayer - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksLayer(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksLayerResources retrieves all AWSOpsWorksLayer items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksLayerResources() map[string]AWSOpsWorksLayer { - results := map[string]AWSOpsWorksLayer{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksLayer: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Layer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksLayer - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksLayerWithName retrieves all AWSOpsWorksLayer items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksLayerWithName(name string) (AWSOpsWorksLayer, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksLayer: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Layer" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksLayer - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksLayer{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_autoscalingthresholds.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_autoscalingthresholds.go deleted file mode 100644 index 56b4b9c8c3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_autoscalingthresholds.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_AutoScalingThresholds AWS CloudFormation Resource (AWS::OpsWorks::Layer.AutoScalingThresholds) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html -type AWSOpsWorksLayer_AutoScalingThresholds struct { - - // CpuThreshold AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-cputhreshold - CpuThreshold float64 `json:"CpuThreshold,omitempty"` - - // IgnoreMetricsTime AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-ignoremetricstime - IgnoreMetricsTime int `json:"IgnoreMetricsTime,omitempty"` - - // InstanceCount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-instancecount - InstanceCount int `json:"InstanceCount,omitempty"` - - // LoadThreshold AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-loadthreshold - LoadThreshold float64 `json:"LoadThreshold,omitempty"` - - // MemoryThreshold AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-memorythreshold - MemoryThreshold float64 `json:"MemoryThreshold,omitempty"` - - // ThresholdsWaitTime AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling-autoscalingthresholds.html#cfn-opsworks-layer-loadbasedautoscaling-autoscalingthresholds-thresholdwaittime - ThresholdsWaitTime int `json:"ThresholdsWaitTime,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_AutoScalingThresholds) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.AutoScalingThresholds" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_lifecycleeventconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_lifecycleeventconfiguration.go deleted file mode 100644 index 7468abb96d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_lifecycleeventconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_LifecycleEventConfiguration AWS CloudFormation Resource (AWS::OpsWorks::Layer.LifecycleEventConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration.html -type AWSOpsWorksLayer_LifecycleEventConfiguration struct { - - // ShutdownEventConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration - ShutdownEventConfiguration *AWSOpsWorksLayer_ShutdownEventConfiguration `json:"ShutdownEventConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_LifecycleEventConfiguration) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.LifecycleEventConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_loadbasedautoscaling.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_loadbasedautoscaling.go deleted file mode 100644 index f8f071f6af..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_loadbasedautoscaling.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_LoadBasedAutoScaling AWS CloudFormation Resource (AWS::OpsWorks::Layer.LoadBasedAutoScaling) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html -type AWSOpsWorksLayer_LoadBasedAutoScaling struct { - - // DownScaling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-downscaling - DownScaling *AWSOpsWorksLayer_AutoScalingThresholds `json:"DownScaling,omitempty"` - - // Enable AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-enable - Enable bool `json:"Enable,omitempty"` - - // UpScaling AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-loadbasedautoscaling.html#cfn-opsworks-layer-loadbasedautoscaling-upscaling - UpScaling *AWSOpsWorksLayer_AutoScalingThresholds `json:"UpScaling,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_LoadBasedAutoScaling) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.LoadBasedAutoScaling" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_recipes.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_recipes.go deleted file mode 100644 index 9167aa31b3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_recipes.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_Recipes AWS CloudFormation Resource (AWS::OpsWorks::Layer.Recipes) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html -type AWSOpsWorksLayer_Recipes struct { - - // Configure AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-configure - Configure []string `json:"Configure,omitempty"` - - // Deploy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-deploy - Deploy []string `json:"Deploy,omitempty"` - - // Setup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-setup - Setup []string `json:"Setup,omitempty"` - - // Shutdown AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-shutdown - Shutdown []string `json:"Shutdown,omitempty"` - - // Undeploy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-recipes.html#cfn-opsworks-layer-customrecipes-undeploy - Undeploy []string `json:"Undeploy,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_Recipes) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.Recipes" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_shutdowneventconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_shutdowneventconfiguration.go deleted file mode 100644 index 6e4620cea5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_shutdowneventconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_ShutdownEventConfiguration AWS CloudFormation Resource (AWS::OpsWorks::Layer.ShutdownEventConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html -type AWSOpsWorksLayer_ShutdownEventConfiguration struct { - - // DelayUntilElbConnectionsDrained AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-delayuntilelbconnectionsdrained - DelayUntilElbConnectionsDrained bool `json:"DelayUntilElbConnectionsDrained,omitempty"` - - // ExecutionTimeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-executiontimeout - ExecutionTimeout int `json:"ExecutionTimeout,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_ShutdownEventConfiguration) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.ShutdownEventConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_volumeconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_volumeconfiguration.go deleted file mode 100644 index 00fed86edb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-layer_volumeconfiguration.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSOpsWorksLayer_VolumeConfiguration AWS CloudFormation Resource (AWS::OpsWorks::Layer.VolumeConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html -type AWSOpsWorksLayer_VolumeConfiguration struct { - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-iops - Iops int `json:"Iops,omitempty"` - - // MountPoint AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-mountpoint - MountPoint string `json:"MountPoint,omitempty"` - - // NumberOfDisks AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-numberofdisks - NumberOfDisks int `json:"NumberOfDisks,omitempty"` - - // RaidLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-raidlevel - RaidLevel int `json:"RaidLevel,omitempty"` - - // Size AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-size - Size int `json:"Size,omitempty"` - - // VolumeType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-volumeconfiguration.html#cfn-opsworks-layer-volconfig-volumetype - VolumeType string `json:"VolumeType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksLayer_VolumeConfiguration) AWSCloudFormationType() string { - return "AWS::OpsWorks::Layer.VolumeConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack.go deleted file mode 100644 index 5711be92d3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack.go +++ /dev/null @@ -1,230 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksStack AWS CloudFormation Resource (AWS::OpsWorks::Stack) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html -type AWSOpsWorksStack struct { - - // AgentVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-agentversion - AgentVersion string `json:"AgentVersion,omitempty"` - - // Attributes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-attributes - Attributes map[string]string `json:"Attributes,omitempty"` - - // ChefConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-chefconfiguration - ChefConfiguration *AWSOpsWorksStack_ChefConfiguration `json:"ChefConfiguration,omitempty"` - - // CloneAppIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-cloneappids - CloneAppIds []string `json:"CloneAppIds,omitempty"` - - // ClonePermissions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-clonepermissions - ClonePermissions bool `json:"ClonePermissions,omitempty"` - - // ConfigurationManager AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-configmanager - ConfigurationManager *AWSOpsWorksStack_StackConfigurationManager `json:"ConfigurationManager,omitempty"` - - // CustomCookbooksSource AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-custcookbooksource - CustomCookbooksSource *AWSOpsWorksStack_Source `json:"CustomCookbooksSource,omitempty"` - - // CustomJson AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-custjson - CustomJson interface{} `json:"CustomJson,omitempty"` - - // DefaultAvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-defaultaz - DefaultAvailabilityZone string `json:"DefaultAvailabilityZone,omitempty"` - - // DefaultInstanceProfileArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-defaultinstanceprof - DefaultInstanceProfileArn string `json:"DefaultInstanceProfileArn,omitempty"` - - // DefaultOs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-defaultos - DefaultOs string `json:"DefaultOs,omitempty"` - - // DefaultRootDeviceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-defaultrootdevicetype - DefaultRootDeviceType string `json:"DefaultRootDeviceType,omitempty"` - - // DefaultSshKeyName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-defaultsshkeyname - DefaultSshKeyName string `json:"DefaultSshKeyName,omitempty"` - - // DefaultSubnetId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#defaultsubnet - DefaultSubnetId string `json:"DefaultSubnetId,omitempty"` - - // EcsClusterArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-ecsclusterarn - EcsClusterArn string `json:"EcsClusterArn,omitempty"` - - // ElasticIps AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-elasticips - ElasticIps []AWSOpsWorksStack_ElasticIp `json:"ElasticIps,omitempty"` - - // HostnameTheme AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-hostnametheme - HostnameTheme string `json:"HostnameTheme,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-name - Name string `json:"Name,omitempty"` - - // RdsDbInstances AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-rdsdbinstances - RdsDbInstances []AWSOpsWorksStack_RdsDbInstance `json:"RdsDbInstances,omitempty"` - - // ServiceRoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-servicerolearn - ServiceRoleArn string `json:"ServiceRoleArn,omitempty"` - - // SourceStackId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-sourcestackid - SourceStackId string `json:"SourceStackId,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-tags - Tags []Tag `json:"Tags,omitempty"` - - // UseCustomCookbooks AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#usecustcookbooks - UseCustomCookbooks bool `json:"UseCustomCookbooks,omitempty"` - - // UseOpsworksSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-useopsworkssecuritygroups - UseOpsworksSecurityGroups bool `json:"UseOpsworksSecurityGroups,omitempty"` - - // VpcId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-stack.html#cfn-opsworks-stack-vpcid - VpcId string `json:"VpcId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksStack) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksStack - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksStack) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksStack - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksStack(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksStackResources retrieves all AWSOpsWorksStack items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksStackResources() map[string]AWSOpsWorksStack { - results := map[string]AWSOpsWorksStack{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksStack: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Stack" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksStack - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksStackWithName retrieves all AWSOpsWorksStack items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksStackWithName(name string) (AWSOpsWorksStack, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksStack: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Stack" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksStack - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksStack{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_chefconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_chefconfiguration.go deleted file mode 100644 index efe39357ad..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_chefconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSOpsWorksStack_ChefConfiguration AWS CloudFormation Resource (AWS::OpsWorks::Stack.ChefConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-chefconfiguration.html -type AWSOpsWorksStack_ChefConfiguration struct { - - // BerkshelfVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-chefconfiguration.html#cfn-opsworks-chefconfiguration-berkshelfversion - BerkshelfVersion string `json:"BerkshelfVersion,omitempty"` - - // ManageBerkshelf AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-chefconfiguration.html#cfn-opsworks-chefconfiguration-berkshelfversion - ManageBerkshelf bool `json:"ManageBerkshelf,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack_ChefConfiguration) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack.ChefConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_elasticip.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_elasticip.go deleted file mode 100644 index 5959769ca5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_elasticip.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSOpsWorksStack_ElasticIp AWS CloudFormation Resource (AWS::OpsWorks::Stack.ElasticIp) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html -type AWSOpsWorksStack_ElasticIp struct { - - // Ip AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html#cfn-opsworks-stack-elasticip-ip - Ip string `json:"Ip,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-elasticip.html#cfn-opsworks-stack-elasticip-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack_ElasticIp) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack.ElasticIp" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_rdsdbinstance.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_rdsdbinstance.go deleted file mode 100644 index a70f82787e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_rdsdbinstance.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSOpsWorksStack_RdsDbInstance AWS CloudFormation Resource (AWS::OpsWorks::Stack.RdsDbInstance) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-rdsdbinstance.html -type AWSOpsWorksStack_RdsDbInstance struct { - - // DbPassword AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-rdsdbinstance.html#cfn-opsworks-stack-rdsdbinstance-dbpassword - DbPassword string `json:"DbPassword,omitempty"` - - // DbUser AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-rdsdbinstance.html#cfn-opsworks-stack-rdsdbinstance-dbuser - DbUser string `json:"DbUser,omitempty"` - - // RdsDbInstanceArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-rdsdbinstance.html#cfn-opsworks-stack-rdsdbinstance-rdsdbinstancearn - RdsDbInstanceArn string `json:"RdsDbInstanceArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack_RdsDbInstance) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack.RdsDbInstance" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_source.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_source.go deleted file mode 100644 index a1f5d7d24a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_source.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSOpsWorksStack_Source AWS CloudFormation Resource (AWS::OpsWorks::Stack.Source) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html -type AWSOpsWorksStack_Source struct { - - // Password AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-password - Password string `json:"Password,omitempty"` - - // Revision AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-revision - Revision string `json:"Revision,omitempty"` - - // SshKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-sshkey - SshKey string `json:"SshKey,omitempty"` - - // Type AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-type - Type string `json:"Type,omitempty"` - - // Url AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-url - Url string `json:"Url,omitempty"` - - // Username AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-source.html#cfn-opsworks-custcookbooksource-username - Username string `json:"Username,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack_Source) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack.Source" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_stackconfigurationmanager.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_stackconfigurationmanager.go deleted file mode 100644 index 057a62d038..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-stack_stackconfigurationmanager.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSOpsWorksStack_StackConfigurationManager AWS CloudFormation Resource (AWS::OpsWorks::Stack.StackConfigurationManager) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-stackconfigmanager.html -type AWSOpsWorksStack_StackConfigurationManager struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-stackconfigmanager.html#cfn-opsworks-configmanager-name - Name string `json:"Name,omitempty"` - - // Version AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-stack-stackconfigmanager.html#cfn-opsworks-configmanager-version - Version string `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksStack_StackConfigurationManager) AWSCloudFormationType() string { - return "AWS::OpsWorks::Stack.StackConfigurationManager" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-userprofile.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-userprofile.go deleted file mode 100644 index c507542709..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-userprofile.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksUserProfile AWS CloudFormation Resource (AWS::OpsWorks::UserProfile) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html -type AWSOpsWorksUserProfile struct { - - // AllowSelfManagement AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html#cfn-opsworks-userprofile-allowselfmanagement - AllowSelfManagement bool `json:"AllowSelfManagement,omitempty"` - - // IamUserArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html#cfn-opsworks-userprofile-iamuserarn - IamUserArn string `json:"IamUserArn,omitempty"` - - // SshPublicKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html#cfn-opsworks-userprofile-sshpublickey - SshPublicKey string `json:"SshPublicKey,omitempty"` - - // SshUsername AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-userprofile.html#cfn-opsworks-userprofile-sshusername - SshUsername string `json:"SshUsername,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksUserProfile) AWSCloudFormationType() string { - return "AWS::OpsWorks::UserProfile" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksUserProfile) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksUserProfile - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksUserProfile) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksUserProfile - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksUserProfile(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksUserProfileResources retrieves all AWSOpsWorksUserProfile items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksUserProfileResources() map[string]AWSOpsWorksUserProfile { - results := map[string]AWSOpsWorksUserProfile{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksUserProfile: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::UserProfile" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksUserProfile - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksUserProfileWithName retrieves all AWSOpsWorksUserProfile items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksUserProfileWithName(name string) (AWSOpsWorksUserProfile, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksUserProfile: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::UserProfile" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksUserProfile - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksUserProfile{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-volume.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-volume.go deleted file mode 100644 index df6f21119f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-opsworks-volume.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSOpsWorksVolume AWS CloudFormation Resource (AWS::OpsWorks::Volume) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html -type AWSOpsWorksVolume struct { - - // Ec2VolumeId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html#cfn-opsworks-volume-ec2volumeid - Ec2VolumeId string `json:"Ec2VolumeId,omitempty"` - - // MountPoint AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html#cfn-opsworks-volume-mountpoint - MountPoint string `json:"MountPoint,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html#cfn-opsworks-volume-name - Name string `json:"Name,omitempty"` - - // StackId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-opsworks-volume.html#cfn-opsworks-volume-stackid - StackId string `json:"StackId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSOpsWorksVolume) AWSCloudFormationType() string { - return "AWS::OpsWorks::Volume" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSOpsWorksVolume) MarshalJSON() ([]byte, error) { - type Properties AWSOpsWorksVolume - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSOpsWorksVolume) UnmarshalJSON(b []byte) error { - type Properties AWSOpsWorksVolume - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSOpsWorksVolume(*res.Properties) - } - - return nil -} - -// GetAllAWSOpsWorksVolumeResources retrieves all AWSOpsWorksVolume items from an AWS CloudFormation template -func (t *Template) GetAllAWSOpsWorksVolumeResources() map[string]AWSOpsWorksVolume { - results := map[string]AWSOpsWorksVolume{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSOpsWorksVolume: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Volume" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksVolume - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSOpsWorksVolumeWithName retrieves all AWSOpsWorksVolume items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSOpsWorksVolumeWithName(name string) (AWSOpsWorksVolume, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSOpsWorksVolume: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::OpsWorks::Volume" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSOpsWorksVolume - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSOpsWorksVolume{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbcluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbcluster.go deleted file mode 100644 index ac51650d59..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbcluster.go +++ /dev/null @@ -1,195 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBCluster AWS CloudFormation Resource (AWS::RDS::DBCluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html -type AWSRDSDBCluster struct { - - // AvailabilityZones AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-availabilityzones - AvailabilityZones string `json:"AvailabilityZones,omitempty"` - - // BackupRetentionPeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-backuprententionperiod - BackupRetentionPeriod int `json:"BackupRetentionPeriod,omitempty"` - - // DBClusterParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-dbclusterparametergroupname - DBClusterParameterGroupName string `json:"DBClusterParameterGroupName,omitempty"` - - // DBSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-dbsubnetgroupname - DBSubnetGroupName string `json:"DBSubnetGroupName,omitempty"` - - // DatabaseName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-databasename - DatabaseName string `json:"DatabaseName,omitempty"` - - // Engine AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-engine - Engine string `json:"Engine,omitempty"` - - // EngineVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-engineversion - EngineVersion string `json:"EngineVersion,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // MasterUserPassword AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-masteruserpassword - MasterUserPassword string `json:"MasterUserPassword,omitempty"` - - // MasterUsername AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-masterusername - MasterUsername string `json:"MasterUsername,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-port - Port int `json:"Port,omitempty"` - - // PreferredBackupWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-preferredbackupwindow - PreferredBackupWindow string `json:"PreferredBackupWindow,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // ReplicationSourceIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-replicationsourceidentifier - ReplicationSourceIdentifier string `json:"ReplicationSourceIdentifier,omitempty"` - - // SnapshotIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-snapshotidentifier - SnapshotIdentifier string `json:"SnapshotIdentifier,omitempty"` - - // StorageEncrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-storageencrypted - StorageEncrypted bool `json:"StorageEncrypted,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcSecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbcluster.html#cfn-rds-dbcluster-vpcsecuritygroupids - VpcSecurityGroupIds []string `json:"VpcSecurityGroupIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBCluster) AWSCloudFormationType() string { - return "AWS::RDS::DBCluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBCluster) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBCluster) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBClusterResources retrieves all AWSRDSDBCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBClusterResources() map[string]AWSRDSDBCluster { - results := map[string]AWSRDSDBCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBCluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBClusterWithName retrieves all AWSRDSDBCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBClusterWithName(name string) (AWSRDSDBCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBCluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbclusterparametergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbclusterparametergroup.go deleted file mode 100644 index c048a90ae8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbclusterparametergroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBClusterParameterGroup AWS CloudFormation Resource (AWS::RDS::DBClusterParameterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html -type AWSRDSDBClusterParameterGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html#cfn-rds-dbclusterparametergroup-description - Description string `json:"Description,omitempty"` - - // Family AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html#cfn-rds-dbclusterparametergroup-family - Family string `json:"Family,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html#cfn-rds-dbclusterparametergroup-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbclusterparametergroup.html#cfn-rds-dbclusterparametergroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBClusterParameterGroup) AWSCloudFormationType() string { - return "AWS::RDS::DBClusterParameterGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBClusterParameterGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBClusterParameterGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBClusterParameterGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBClusterParameterGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBClusterParameterGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBClusterParameterGroupResources retrieves all AWSRDSDBClusterParameterGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBClusterParameterGroupResources() map[string]AWSRDSDBClusterParameterGroup { - results := map[string]AWSRDSDBClusterParameterGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBClusterParameterGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBClusterParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBClusterParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBClusterParameterGroupWithName retrieves all AWSRDSDBClusterParameterGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBClusterParameterGroupWithName(name string) (AWSRDSDBClusterParameterGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBClusterParameterGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBClusterParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBClusterParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBClusterParameterGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbinstance.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbinstance.go deleted file mode 100644 index 3ac6ddba76..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbinstance.go +++ /dev/null @@ -1,295 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBInstance AWS CloudFormation Resource (AWS::RDS::DBInstance) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html -type AWSRDSDBInstance struct { - - // AllocatedStorage AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-allocatedstorage - AllocatedStorage string `json:"AllocatedStorage,omitempty"` - - // AllowMajorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-allowmajorversionupgrade - AllowMajorVersionUpgrade bool `json:"AllowMajorVersionUpgrade,omitempty"` - - // AutoMinorVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-autominorversionupgrade - AutoMinorVersionUpgrade bool `json:"AutoMinorVersionUpgrade,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // BackupRetentionPeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-backupretentionperiod - BackupRetentionPeriod string `json:"BackupRetentionPeriod,omitempty"` - - // CharacterSetName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-charactersetname - CharacterSetName string `json:"CharacterSetName,omitempty"` - - // CopyTagsToSnapshot AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-copytagstosnapshot - CopyTagsToSnapshot bool `json:"CopyTagsToSnapshot,omitempty"` - - // DBClusterIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbclusteridentifier - DBClusterIdentifier string `json:"DBClusterIdentifier,omitempty"` - - // DBInstanceClass AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbinstanceclass - DBInstanceClass string `json:"DBInstanceClass,omitempty"` - - // DBInstanceIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbinstanceidentifier - DBInstanceIdentifier string `json:"DBInstanceIdentifier,omitempty"` - - // DBName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbname - DBName string `json:"DBName,omitempty"` - - // DBParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbparametergroupname - DBParameterGroupName string `json:"DBParameterGroupName,omitempty"` - - // DBSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbsecuritygroups - DBSecurityGroups []string `json:"DBSecurityGroups,omitempty"` - - // DBSnapshotIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbsnapshotidentifier - DBSnapshotIdentifier string `json:"DBSnapshotIdentifier,omitempty"` - - // DBSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-dbsubnetgroupname - DBSubnetGroupName string `json:"DBSubnetGroupName,omitempty"` - - // Domain AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-domain - Domain string `json:"Domain,omitempty"` - - // DomainIAMRoleName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-domainiamrolename - DomainIAMRoleName string `json:"DomainIAMRoleName,omitempty"` - - // Engine AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-engine - Engine string `json:"Engine,omitempty"` - - // EngineVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-engineversion - EngineVersion string `json:"EngineVersion,omitempty"` - - // Iops AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-iops - Iops int `json:"Iops,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // LicenseModel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-licensemodel - LicenseModel string `json:"LicenseModel,omitempty"` - - // MasterUserPassword AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-masteruserpassword - MasterUserPassword string `json:"MasterUserPassword,omitempty"` - - // MasterUsername AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-masterusername - MasterUsername string `json:"MasterUsername,omitempty"` - - // MonitoringInterval AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-monitoringinterval - MonitoringInterval int `json:"MonitoringInterval,omitempty"` - - // MonitoringRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-monitoringrolearn - MonitoringRoleArn string `json:"MonitoringRoleArn,omitempty"` - - // MultiAZ AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-multiaz - MultiAZ bool `json:"MultiAZ,omitempty"` - - // OptionGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-optiongroupname - OptionGroupName string `json:"OptionGroupName,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-port - Port string `json:"Port,omitempty"` - - // PreferredBackupWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-preferredbackupwindow - PreferredBackupWindow string `json:"PreferredBackupWindow,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // PubliclyAccessible AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-publiclyaccessible - PubliclyAccessible bool `json:"PubliclyAccessible,omitempty"` - - // SourceDBInstanceIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-sourcedbinstanceidentifier - SourceDBInstanceIdentifier string `json:"SourceDBInstanceIdentifier,omitempty"` - - // StorageEncrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-storageencrypted - StorageEncrypted bool `json:"StorageEncrypted,omitempty"` - - // StorageType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-storagetype - StorageType string `json:"StorageType,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-tags - Tags []Tag `json:"Tags,omitempty"` - - // Timezone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-timezone - Timezone string `json:"Timezone,omitempty"` - - // VPCSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html#cfn-rds-dbinstance-vpcsecuritygroups - VPCSecurityGroups []string `json:"VPCSecurityGroups,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBInstance) AWSCloudFormationType() string { - return "AWS::RDS::DBInstance" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBInstance) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBInstance - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBInstance) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBInstance - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBInstance(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBInstanceResources retrieves all AWSRDSDBInstance items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBInstanceResources() map[string]AWSRDSDBInstance { - results := map[string]AWSRDSDBInstance{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBInstance: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBInstance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBInstance - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBInstanceWithName retrieves all AWSRDSDBInstance items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBInstanceWithName(name string) (AWSRDSDBInstance, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBInstance: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBInstance" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBInstance - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBInstance{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbparametergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbparametergroup.go deleted file mode 100644 index 75753c8074..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbparametergroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBParameterGroup AWS CloudFormation Resource (AWS::RDS::DBParameterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbparametergroup.html -type AWSRDSDBParameterGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbparametergroup.html#cfn-rds-dbparametergroup-description - Description string `json:"Description,omitempty"` - - // Family AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbparametergroup.html#cfn-rds-dbparametergroup-family - Family string `json:"Family,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbparametergroup.html#cfn-rds-dbparametergroup-parameters - Parameters map[string]string `json:"Parameters,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-dbparametergroup.html#cfn-rds-dbparametergroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBParameterGroup) AWSCloudFormationType() string { - return "AWS::RDS::DBParameterGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBParameterGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBParameterGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBParameterGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBParameterGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBParameterGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBParameterGroupResources retrieves all AWSRDSDBParameterGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBParameterGroupResources() map[string]AWSRDSDBParameterGroup { - results := map[string]AWSRDSDBParameterGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBParameterGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBParameterGroupWithName retrieves all AWSRDSDBParameterGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBParameterGroupWithName(name string) (AWSRDSDBParameterGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBParameterGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBParameterGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup.go deleted file mode 100644 index 38afa1dcb1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBSecurityGroup AWS CloudFormation Resource (AWS::RDS::DBSecurityGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group.html -type AWSRDSDBSecurityGroup struct { - - // DBSecurityGroupIngress AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group.html#cfn-rds-dbsecuritygroup-dbsecuritygroupingress - DBSecurityGroupIngress []AWSRDSDBSecurityGroup_Ingress `json:"DBSecurityGroupIngress,omitempty"` - - // EC2VpcId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group.html#cfn-rds-dbsecuritygroup-ec2vpcid - EC2VpcId string `json:"EC2VpcId,omitempty"` - - // GroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group.html#cfn-rds-dbsecuritygroup-groupdescription - GroupDescription string `json:"GroupDescription,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group.html#cfn-rds-dbsecuritygroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBSecurityGroup) AWSCloudFormationType() string { - return "AWS::RDS::DBSecurityGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBSecurityGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBSecurityGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBSecurityGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBSecurityGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBSecurityGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBSecurityGroupResources retrieves all AWSRDSDBSecurityGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBSecurityGroupResources() map[string]AWSRDSDBSecurityGroup { - results := map[string]AWSRDSDBSecurityGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBSecurityGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBSecurityGroupWithName retrieves all AWSRDSDBSecurityGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBSecurityGroupWithName(name string) (AWSRDSDBSecurityGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBSecurityGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBSecurityGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup_ingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup_ingress.go deleted file mode 100644 index f957e16992..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroup_ingress.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSRDSDBSecurityGroup_Ingress AWS CloudFormation Resource (AWS::RDS::DBSecurityGroup.Ingress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group-rule.html -type AWSRDSDBSecurityGroup_Ingress struct { - - // CIDRIP AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group-rule.html#cfn-rds-securitygroup-cidrip - CIDRIP string `json:"CIDRIP,omitempty"` - - // EC2SecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group-rule.html#cfn-rds-securitygroup-ec2securitygroupid - EC2SecurityGroupId string `json:"EC2SecurityGroupId,omitempty"` - - // EC2SecurityGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group-rule.html#cfn-rds-securitygroup-ec2securitygroupname - EC2SecurityGroupName string `json:"EC2SecurityGroupName,omitempty"` - - // EC2SecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-security-group-rule.html#cfn-rds-securitygroup-ec2securitygroupownerid - EC2SecurityGroupOwnerId string `json:"EC2SecurityGroupOwnerId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBSecurityGroup_Ingress) AWSCloudFormationType() string { - return "AWS::RDS::DBSecurityGroup.Ingress" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroupingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroupingress.go deleted file mode 100644 index 0d8fa2aed8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsecuritygroupingress.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBSecurityGroupIngress AWS CloudFormation Resource (AWS::RDS::DBSecurityGroupIngress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html -type AWSRDSDBSecurityGroupIngress struct { - - // CIDRIP AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html#cfn-rds-securitygroup-ingress-cidrip - CIDRIP string `json:"CIDRIP,omitempty"` - - // DBSecurityGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html#cfn-rds-securitygroup-ingress-dbsecuritygroupname - DBSecurityGroupName string `json:"DBSecurityGroupName,omitempty"` - - // EC2SecurityGroupId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html#cfn-rds-securitygroup-ingress-ec2securitygroupid - EC2SecurityGroupId string `json:"EC2SecurityGroupId,omitempty"` - - // EC2SecurityGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html#cfn-rds-securitygroup-ingress-ec2securitygroupname - EC2SecurityGroupName string `json:"EC2SecurityGroupName,omitempty"` - - // EC2SecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-security-group-ingress.html#cfn-rds-securitygroup-ingress-ec2securitygroupownerid - EC2SecurityGroupOwnerId string `json:"EC2SecurityGroupOwnerId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBSecurityGroupIngress) AWSCloudFormationType() string { - return "AWS::RDS::DBSecurityGroupIngress" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBSecurityGroupIngress) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBSecurityGroupIngress - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBSecurityGroupIngress) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBSecurityGroupIngress - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBSecurityGroupIngress(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBSecurityGroupIngressResources retrieves all AWSRDSDBSecurityGroupIngress items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBSecurityGroupIngressResources() map[string]AWSRDSDBSecurityGroupIngress { - results := map[string]AWSRDSDBSecurityGroupIngress{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBSecurityGroupIngressWithName retrieves all AWSRDSDBSecurityGroupIngress items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBSecurityGroupIngressWithName(name string) (AWSRDSDBSecurityGroupIngress, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBSecurityGroupIngress{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsubnetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsubnetgroup.go deleted file mode 100644 index 4e48036510..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-dbsubnetgroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSDBSubnetGroup AWS CloudFormation Resource (AWS::RDS::DBSubnetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html -type AWSRDSDBSubnetGroup struct { - - // DBSubnetGroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html#cfn-rds-dbsubnetgroup-dbsubnetgroupdescription - DBSubnetGroupDescription string `json:"DBSubnetGroupDescription,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html#cfn-rds-dbsubnetgroup-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-dbsubnet-group.html#cfn-rds-dbsubnetgroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSDBSubnetGroup) AWSCloudFormationType() string { - return "AWS::RDS::DBSubnetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSDBSubnetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRDSDBSubnetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSDBSubnetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRDSDBSubnetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSDBSubnetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSDBSubnetGroupResources retrieves all AWSRDSDBSubnetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSDBSubnetGroupResources() map[string]AWSRDSDBSubnetGroup { - results := map[string]AWSRDSDBSubnetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSDBSubnetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSDBSubnetGroupWithName retrieves all AWSRDSDBSubnetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSDBSubnetGroupWithName(name string) (AWSRDSDBSubnetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSDBSubnetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::DBSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSDBSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSDBSubnetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-eventsubscription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-eventsubscription.go deleted file mode 100644 index bf24964c58..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-eventsubscription.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSEventSubscription AWS CloudFormation Resource (AWS::RDS::EventSubscription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html -type AWSRDSEventSubscription struct { - - // Enabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html#cfn-rds-eventsubscription-enabled - Enabled bool `json:"Enabled,omitempty"` - - // EventCategories AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html#cfn-rds-eventsubscription-eventcategories - EventCategories []string `json:"EventCategories,omitempty"` - - // SnsTopicArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html#cfn-rds-eventsubscription-snstopicarn - SnsTopicArn string `json:"SnsTopicArn,omitempty"` - - // SourceIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html#cfn-rds-eventsubscription-sourceids - SourceIds []string `json:"SourceIds,omitempty"` - - // SourceType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-eventsubscription.html#cfn-rds-eventsubscription-sourcetype - SourceType string `json:"SourceType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSEventSubscription) AWSCloudFormationType() string { - return "AWS::RDS::EventSubscription" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSEventSubscription) MarshalJSON() ([]byte, error) { - type Properties AWSRDSEventSubscription - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSEventSubscription) UnmarshalJSON(b []byte) error { - type Properties AWSRDSEventSubscription - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSEventSubscription(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSEventSubscriptionResources retrieves all AWSRDSEventSubscription items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSEventSubscriptionResources() map[string]AWSRDSEventSubscription { - results := map[string]AWSRDSEventSubscription{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSEventSubscription: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::EventSubscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSEventSubscription - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSEventSubscriptionWithName retrieves all AWSRDSEventSubscription items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSEventSubscriptionWithName(name string) (AWSRDSEventSubscription, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSEventSubscription: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::EventSubscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSEventSubscription - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSEventSubscription{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup.go deleted file mode 100644 index 65064052f6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRDSOptionGroup AWS CloudFormation Resource (AWS::RDS::OptionGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html -type AWSRDSOptionGroup struct { - - // EngineName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html#cfn-rds-optiongroup-enginename - EngineName string `json:"EngineName,omitempty"` - - // MajorEngineVersion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html#cfn-rds-optiongroup-majorengineversion - MajorEngineVersion string `json:"MajorEngineVersion,omitempty"` - - // OptionConfigurations AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html#cfn-rds-optiongroup-optionconfigurations - OptionConfigurations []AWSRDSOptionGroup_OptionConfiguration `json:"OptionConfigurations,omitempty"` - - // OptionGroupDescription AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html#cfn-rds-optiongroup-optiongroupdescription - OptionGroupDescription string `json:"OptionGroupDescription,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-rds-optiongroup.html#cfn-rds-optiongroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSOptionGroup) AWSCloudFormationType() string { - return "AWS::RDS::OptionGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRDSOptionGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRDSOptionGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRDSOptionGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRDSOptionGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRDSOptionGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRDSOptionGroupResources retrieves all AWSRDSOptionGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRDSOptionGroupResources() map[string]AWSRDSOptionGroup { - results := map[string]AWSRDSOptionGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRDSOptionGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::OptionGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSOptionGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRDSOptionGroupWithName retrieves all AWSRDSOptionGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRDSOptionGroupWithName(name string) (AWSRDSOptionGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRDSOptionGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::RDS::OptionGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRDSOptionGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRDSOptionGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionconfiguration.go deleted file mode 100644 index 39a0b29943..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionconfiguration.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSRDSOptionGroup_OptionConfiguration AWS CloudFormation Resource (AWS::RDS::OptionGroup.OptionConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html -type AWSRDSOptionGroup_OptionConfiguration struct { - - // DBSecurityGroupMemberships AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfigurations-dbsecuritygroupmemberships - DBSecurityGroupMemberships []string `json:"DBSecurityGroupMemberships,omitempty"` - - // OptionName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfigurations-optionname - OptionName string `json:"OptionName,omitempty"` - - // OptionSettings AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfigurations-optionsettings - OptionSettings *AWSRDSOptionGroup_OptionSetting `json:"OptionSettings,omitempty"` - - // OptionVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfiguration-optionversion - OptionVersion string `json:"OptionVersion,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfigurations-port - Port int `json:"Port,omitempty"` - - // VpcSecurityGroupMemberships AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations.html#cfn-rds-optiongroup-optionconfigurations-vpcsecuritygroupmemberships - VpcSecurityGroupMemberships []string `json:"VpcSecurityGroupMemberships,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSOptionGroup_OptionConfiguration) AWSCloudFormationType() string { - return "AWS::RDS::OptionGroup.OptionConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionsetting.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionsetting.go deleted file mode 100644 index 955206139d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-rds-optiongroup_optionsetting.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRDSOptionGroup_OptionSetting AWS CloudFormation Resource (AWS::RDS::OptionGroup.OptionSetting) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations-optionsettings.html -type AWSRDSOptionGroup_OptionSetting struct { - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations-optionsettings.html#cfn-rds-optiongroup-optionconfigurations-optionsettings-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-optiongroup-optionconfigurations-optionsettings.html#cfn-rds-optiongroup-optionconfigurations-optionsettings-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRDSOptionGroup_OptionSetting) AWSCloudFormationType() string { - return "AWS::RDS::OptionGroup.OptionSetting" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster.go deleted file mode 100644 index 083b756484..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster.go +++ /dev/null @@ -1,245 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRedshiftCluster AWS CloudFormation Resource (AWS::Redshift::Cluster) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html -type AWSRedshiftCluster struct { - - // AllowVersionUpgrade AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-allowversionupgrade - AllowVersionUpgrade bool `json:"AllowVersionUpgrade,omitempty"` - - // AutomatedSnapshotRetentionPeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-automatedsnapshotretentionperiod - AutomatedSnapshotRetentionPeriod int `json:"AutomatedSnapshotRetentionPeriod,omitempty"` - - // AvailabilityZone AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-availabilityzone - AvailabilityZone string `json:"AvailabilityZone,omitempty"` - - // ClusterParameterGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clusterparametergroupname - ClusterParameterGroupName string `json:"ClusterParameterGroupName,omitempty"` - - // ClusterSecurityGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustersecuritygroups - ClusterSecurityGroups []string `json:"ClusterSecurityGroups,omitempty"` - - // ClusterSubnetGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustersubnetgroupname - ClusterSubnetGroupName string `json:"ClusterSubnetGroupName,omitempty"` - - // ClusterType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clustertype - ClusterType string `json:"ClusterType,omitempty"` - - // ClusterVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-clusterversion - ClusterVersion string `json:"ClusterVersion,omitempty"` - - // DBName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-dbname - DBName string `json:"DBName,omitempty"` - - // ElasticIp AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-elasticip - ElasticIp string `json:"ElasticIp,omitempty"` - - // Encrypted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-encrypted - Encrypted bool `json:"Encrypted,omitempty"` - - // HsmClientCertificateIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-hsmclientcertidentifier - HsmClientCertificateIdentifier string `json:"HsmClientCertificateIdentifier,omitempty"` - - // HsmConfigurationIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-HsmConfigurationIdentifier - HsmConfigurationIdentifier string `json:"HsmConfigurationIdentifier,omitempty"` - - // IamRoles AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-iamroles - IamRoles []string `json:"IamRoles,omitempty"` - - // KmsKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-kmskeyid - KmsKeyId string `json:"KmsKeyId,omitempty"` - - // LoggingProperties AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-loggingproperties - LoggingProperties *AWSRedshiftCluster_LoggingProperties `json:"LoggingProperties,omitempty"` - - // MasterUserPassword AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-masteruserpassword - MasterUserPassword string `json:"MasterUserPassword,omitempty"` - - // MasterUsername AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-masterusername - MasterUsername string `json:"MasterUsername,omitempty"` - - // NodeType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-nodetype - NodeType string `json:"NodeType,omitempty"` - - // NumberOfNodes AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-nodetype - NumberOfNodes int `json:"NumberOfNodes,omitempty"` - - // OwnerAccount AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-owneraccount - OwnerAccount string `json:"OwnerAccount,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-port - Port int `json:"Port,omitempty"` - - // PreferredMaintenanceWindow AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-preferredmaintenancewindow - PreferredMaintenanceWindow string `json:"PreferredMaintenanceWindow,omitempty"` - - // PubliclyAccessible AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-publiclyaccessible - PubliclyAccessible bool `json:"PubliclyAccessible,omitempty"` - - // SnapshotClusterIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-snapshotclusteridentifier - SnapshotClusterIdentifier string `json:"SnapshotClusterIdentifier,omitempty"` - - // SnapshotIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-snapshotidentifier - SnapshotIdentifier string `json:"SnapshotIdentifier,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-tags - Tags []Tag `json:"Tags,omitempty"` - - // VpcSecurityGroupIds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-cluster.html#cfn-redshift-cluster-vpcsecuritygroupids - VpcSecurityGroupIds []string `json:"VpcSecurityGroupIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftCluster) AWSCloudFormationType() string { - return "AWS::Redshift::Cluster" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRedshiftCluster) MarshalJSON() ([]byte, error) { - type Properties AWSRedshiftCluster - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRedshiftCluster) UnmarshalJSON(b []byte) error { - type Properties AWSRedshiftCluster - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRedshiftCluster(*res.Properties) - } - - return nil -} - -// GetAllAWSRedshiftClusterResources retrieves all AWSRedshiftCluster items from an AWS CloudFormation template -func (t *Template) GetAllAWSRedshiftClusterResources() map[string]AWSRedshiftCluster { - results := map[string]AWSRedshiftCluster{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRedshiftCluster: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftCluster - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRedshiftClusterWithName retrieves all AWSRedshiftCluster items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRedshiftClusterWithName(name string) (AWSRedshiftCluster, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRedshiftCluster: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::Cluster" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftCluster - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRedshiftCluster{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster_loggingproperties.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster_loggingproperties.go deleted file mode 100644 index b08d0c8983..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-cluster_loggingproperties.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRedshiftCluster_LoggingProperties AWS CloudFormation Resource (AWS::Redshift::Cluster.LoggingProperties) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html -type AWSRedshiftCluster_LoggingProperties struct { - - // BucketName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-bucketname - BucketName string `json:"BucketName,omitempty"` - - // S3KeyPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-redshift-cluster-loggingproperties.html#cfn-redshift-cluster-loggingproperties-s3keyprefix - S3KeyPrefix string `json:"S3KeyPrefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftCluster_LoggingProperties) AWSCloudFormationType() string { - return "AWS::Redshift::Cluster.LoggingProperties" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup.go deleted file mode 100644 index 2e3a878089..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRedshiftClusterParameterGroup AWS CloudFormation Resource (AWS::Redshift::ClusterParameterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clusterparametergroup.html -type AWSRedshiftClusterParameterGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clusterparametergroup.html#cfn-redshift-clusterparametergroup-description - Description string `json:"Description,omitempty"` - - // ParameterGroupFamily AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clusterparametergroup.html#cfn-redshift-clusterparametergroup-parametergroupfamily - ParameterGroupFamily string `json:"ParameterGroupFamily,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clusterparametergroup.html#cfn-redshift-clusterparametergroup-parameters - Parameters []AWSRedshiftClusterParameterGroup_Parameter `json:"Parameters,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clusterparametergroup.html#cfn-redshift-clusterparametergroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftClusterParameterGroup) AWSCloudFormationType() string { - return "AWS::Redshift::ClusterParameterGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRedshiftClusterParameterGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRedshiftClusterParameterGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRedshiftClusterParameterGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRedshiftClusterParameterGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRedshiftClusterParameterGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRedshiftClusterParameterGroupResources retrieves all AWSRedshiftClusterParameterGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRedshiftClusterParameterGroupResources() map[string]AWSRedshiftClusterParameterGroup { - results := map[string]AWSRedshiftClusterParameterGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRedshiftClusterParameterGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRedshiftClusterParameterGroupWithName retrieves all AWSRedshiftClusterParameterGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRedshiftClusterParameterGroupWithName(name string) (AWSRedshiftClusterParameterGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRedshiftClusterParameterGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterParameterGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterParameterGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRedshiftClusterParameterGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup_parameter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup_parameter.go deleted file mode 100644 index f917f6d042..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clusterparametergroup_parameter.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRedshiftClusterParameterGroup_Parameter AWS CloudFormation Resource (AWS::Redshift::ClusterParameterGroup.Parameter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-property-redshift-clusterparametergroup-parameter.html -type AWSRedshiftClusterParameterGroup_Parameter struct { - - // ParameterName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-property-redshift-clusterparametergroup-parameter.html#cfn-redshift-clusterparametergroup-parameter-parametername - ParameterName string `json:"ParameterName,omitempty"` - - // ParameterValue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-property-redshift-clusterparametergroup-parameter.html#cfn-redshift-clusterparametergroup-parameter-parametervalue - ParameterValue string `json:"ParameterValue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftClusterParameterGroup_Parameter) AWSCloudFormationType() string { - return "AWS::Redshift::ClusterParameterGroup.Parameter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroup.go deleted file mode 100644 index 35f327960d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroup.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRedshiftClusterSecurityGroup AWS CloudFormation Resource (AWS::Redshift::ClusterSecurityGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html -type AWSRedshiftClusterSecurityGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html#cfn-redshift-clustersecuritygroup-description - Description string `json:"Description,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroup.html#cfn-redshift-clustersecuritygroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftClusterSecurityGroup) AWSCloudFormationType() string { - return "AWS::Redshift::ClusterSecurityGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRedshiftClusterSecurityGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRedshiftClusterSecurityGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRedshiftClusterSecurityGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRedshiftClusterSecurityGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRedshiftClusterSecurityGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRedshiftClusterSecurityGroupResources retrieves all AWSRedshiftClusterSecurityGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRedshiftClusterSecurityGroupResources() map[string]AWSRedshiftClusterSecurityGroup { - results := map[string]AWSRedshiftClusterSecurityGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRedshiftClusterSecurityGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRedshiftClusterSecurityGroupWithName retrieves all AWSRedshiftClusterSecurityGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRedshiftClusterSecurityGroupWithName(name string) (AWSRedshiftClusterSecurityGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRedshiftClusterSecurityGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSecurityGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSecurityGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRedshiftClusterSecurityGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroupingress.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroupingress.go deleted file mode 100644 index a5a1dd72ab..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersecuritygroupingress.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRedshiftClusterSecurityGroupIngress AWS CloudFormation Resource (AWS::Redshift::ClusterSecurityGroupIngress) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroupingress.html -type AWSRedshiftClusterSecurityGroupIngress struct { - - // CIDRIP AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroupingress.html#cfn-redshift-clustersecuritygroupingress-cidrip - CIDRIP string `json:"CIDRIP,omitempty"` - - // ClusterSecurityGroupName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroupingress.html#cfn-redshift-clustersecuritygroupingress-clustersecuritygroupname - ClusterSecurityGroupName string `json:"ClusterSecurityGroupName,omitempty"` - - // EC2SecurityGroupName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroupingress.html#cfn-redshift-clustersecuritygroupingress-ec2securitygroupname - EC2SecurityGroupName string `json:"EC2SecurityGroupName,omitempty"` - - // EC2SecurityGroupOwnerId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersecuritygroupingress.html#cfn-redshift-clustersecuritygroupingress-ec2securitygroupownerid - EC2SecurityGroupOwnerId string `json:"EC2SecurityGroupOwnerId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftClusterSecurityGroupIngress) AWSCloudFormationType() string { - return "AWS::Redshift::ClusterSecurityGroupIngress" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRedshiftClusterSecurityGroupIngress) MarshalJSON() ([]byte, error) { - type Properties AWSRedshiftClusterSecurityGroupIngress - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRedshiftClusterSecurityGroupIngress) UnmarshalJSON(b []byte) error { - type Properties AWSRedshiftClusterSecurityGroupIngress - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRedshiftClusterSecurityGroupIngress(*res.Properties) - } - - return nil -} - -// GetAllAWSRedshiftClusterSecurityGroupIngressResources retrieves all AWSRedshiftClusterSecurityGroupIngress items from an AWS CloudFormation template -func (t *Template) GetAllAWSRedshiftClusterSecurityGroupIngressResources() map[string]AWSRedshiftClusterSecurityGroupIngress { - results := map[string]AWSRedshiftClusterSecurityGroupIngress{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRedshiftClusterSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRedshiftClusterSecurityGroupIngressWithName retrieves all AWSRedshiftClusterSecurityGroupIngress items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRedshiftClusterSecurityGroupIngressWithName(name string) (AWSRedshiftClusterSecurityGroupIngress, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRedshiftClusterSecurityGroupIngress: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSecurityGroupIngress" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSecurityGroupIngress - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRedshiftClusterSecurityGroupIngress{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersubnetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersubnetgroup.go deleted file mode 100644 index 66222aabc3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-redshift-clustersubnetgroup.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRedshiftClusterSubnetGroup AWS CloudFormation Resource (AWS::Redshift::ClusterSubnetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersubnetgroup.html -type AWSRedshiftClusterSubnetGroup struct { - - // Description AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersubnetgroup.html#cfn-redshift-clustersubnetgroup-description - Description string `json:"Description,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersubnetgroup.html#cfn-redshift-clustersubnetgroup-subnetids - SubnetIds []string `json:"SubnetIds,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-redshift-clustersubnetgroup.html#cfn-redshift-clustersubnetgroup-tags - Tags []Tag `json:"Tags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRedshiftClusterSubnetGroup) AWSCloudFormationType() string { - return "AWS::Redshift::ClusterSubnetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRedshiftClusterSubnetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRedshiftClusterSubnetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRedshiftClusterSubnetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRedshiftClusterSubnetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRedshiftClusterSubnetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRedshiftClusterSubnetGroupResources retrieves all AWSRedshiftClusterSubnetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRedshiftClusterSubnetGroupResources() map[string]AWSRedshiftClusterSubnetGroup { - results := map[string]AWSRedshiftClusterSubnetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRedshiftClusterSubnetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRedshiftClusterSubnetGroupWithName retrieves all AWSRedshiftClusterSubnetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRedshiftClusterSubnetGroupWithName(name string) (AWSRedshiftClusterSubnetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRedshiftClusterSubnetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Redshift::ClusterSubnetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRedshiftClusterSubnetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRedshiftClusterSubnetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck.go deleted file mode 100644 index d70a99c15b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRoute53HealthCheck AWS CloudFormation Resource (AWS::Route53::HealthCheck) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-healthcheck.html -type AWSRoute53HealthCheck struct { - - // HealthCheckConfig AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-healthcheck.html#cfn-route53-healthcheck-healthcheckconfig - HealthCheckConfig *AWSRoute53HealthCheck_HealthCheckConfig `json:"HealthCheckConfig,omitempty"` - - // HealthCheckTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-healthcheck.html#cfn-route53-healthcheck-healthchecktags - HealthCheckTags []AWSRoute53HealthCheck_HealthCheckTag `json:"HealthCheckTags,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HealthCheck) AWSCloudFormationType() string { - return "AWS::Route53::HealthCheck" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRoute53HealthCheck) MarshalJSON() ([]byte, error) { - type Properties AWSRoute53HealthCheck - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRoute53HealthCheck) UnmarshalJSON(b []byte) error { - type Properties AWSRoute53HealthCheck - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRoute53HealthCheck(*res.Properties) - } - - return nil -} - -// GetAllAWSRoute53HealthCheckResources retrieves all AWSRoute53HealthCheck items from an AWS CloudFormation template -func (t *Template) GetAllAWSRoute53HealthCheckResources() map[string]AWSRoute53HealthCheck { - results := map[string]AWSRoute53HealthCheck{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRoute53HealthCheck: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::HealthCheck" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53HealthCheck - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRoute53HealthCheckWithName retrieves all AWSRoute53HealthCheck items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRoute53HealthCheckWithName(name string) (AWSRoute53HealthCheck, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRoute53HealthCheck: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::HealthCheck" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53HealthCheck - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRoute53HealthCheck{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_alarmidentifier.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_alarmidentifier.go deleted file mode 100644 index 61beb61341..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_alarmidentifier.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRoute53HealthCheck_AlarmIdentifier AWS CloudFormation Resource (AWS::Route53::HealthCheck.AlarmIdentifier) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-alarmidentifier.html -type AWSRoute53HealthCheck_AlarmIdentifier struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-alarmidentifier.html#cfn-route53-healthcheck-alarmidentifier-name - Name string `json:"Name,omitempty"` - - // Region AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-alarmidentifier.html#cfn-route53-healthcheck-alarmidentifier-region - Region string `json:"Region,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HealthCheck_AlarmIdentifier) AWSCloudFormationType() string { - return "AWS::Route53::HealthCheck.AlarmIdentifier" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthcheckconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthcheckconfig.go deleted file mode 100644 index 3cdc6657d0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthcheckconfig.go +++ /dev/null @@ -1,86 +0,0 @@ -package cloudformation - -// AWSRoute53HealthCheck_HealthCheckConfig AWS CloudFormation Resource (AWS::Route53::HealthCheck.HealthCheckConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html -type AWSRoute53HealthCheck_HealthCheckConfig struct { - - // AlarmIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-alarmidentifier - AlarmIdentifier *AWSRoute53HealthCheck_AlarmIdentifier `json:"AlarmIdentifier,omitempty"` - - // ChildHealthChecks AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-childhealthchecks - ChildHealthChecks []string `json:"ChildHealthChecks,omitempty"` - - // EnableSNI AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-enablesni - EnableSNI bool `json:"EnableSNI,omitempty"` - - // FailureThreshold AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-failurethreshold - FailureThreshold int `json:"FailureThreshold,omitempty"` - - // FullyQualifiedDomainName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-fullyqualifieddomainname - FullyQualifiedDomainName string `json:"FullyQualifiedDomainName,omitempty"` - - // HealthThreshold AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-healththreshold - HealthThreshold int `json:"HealthThreshold,omitempty"` - - // IPAddress AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-ipaddress - IPAddress string `json:"IPAddress,omitempty"` - - // InsufficientDataHealthStatus AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-insufficientdatahealthstatus - InsufficientDataHealthStatus string `json:"InsufficientDataHealthStatus,omitempty"` - - // Inverted AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-inverted - Inverted bool `json:"Inverted,omitempty"` - - // MeasureLatency AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-measurelatency - MeasureLatency bool `json:"MeasureLatency,omitempty"` - - // Port AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-port - Port int `json:"Port,omitempty"` - - // RequestInterval AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-requestinterval - RequestInterval int `json:"RequestInterval,omitempty"` - - // ResourcePath AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-resourcepath - ResourcePath string `json:"ResourcePath,omitempty"` - - // SearchString AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-searchstring - SearchString string `json:"SearchString,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthcheckconfig.html#cfn-route53-healthcheck-healthcheckconfig-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HealthCheck_HealthCheckConfig) AWSCloudFormationType() string { - return "AWS::Route53::HealthCheck.HealthCheckConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthchecktag.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthchecktag.go deleted file mode 100644 index 7ccec326be..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-healthcheck_healthchecktag.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRoute53HealthCheck_HealthCheckTag AWS CloudFormation Resource (AWS::Route53::HealthCheck.HealthCheckTag) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthchecktag.html -type AWSRoute53HealthCheck_HealthCheckTag struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthchecktag.html#cfn-route53-healthchecktags-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-healthcheck-healthchecktag.html#cfn-route53-healthchecktags-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HealthCheck_HealthCheckTag) AWSCloudFormationType() string { - return "AWS::Route53::HealthCheck.HealthCheckTag" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone.go deleted file mode 100644 index 1036dc5277..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRoute53HostedZone AWS CloudFormation Resource (AWS::Route53::HostedZone) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html -type AWSRoute53HostedZone struct { - - // HostedZoneConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzoneconfig - HostedZoneConfig *AWSRoute53HostedZone_HostedZoneConfig `json:"HostedZoneConfig,omitempty"` - - // HostedZoneTags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-hostedzonetags - HostedZoneTags []AWSRoute53HostedZone_HostedZoneTag `json:"HostedZoneTags,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-name - Name string `json:"Name,omitempty"` - - // VPCs AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html#cfn-route53-hostedzone-vpcs - VPCs []AWSRoute53HostedZone_VPC `json:"VPCs,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HostedZone) AWSCloudFormationType() string { - return "AWS::Route53::HostedZone" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRoute53HostedZone) MarshalJSON() ([]byte, error) { - type Properties AWSRoute53HostedZone - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRoute53HostedZone) UnmarshalJSON(b []byte) error { - type Properties AWSRoute53HostedZone - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRoute53HostedZone(*res.Properties) - } - - return nil -} - -// GetAllAWSRoute53HostedZoneResources retrieves all AWSRoute53HostedZone items from an AWS CloudFormation template -func (t *Template) GetAllAWSRoute53HostedZoneResources() map[string]AWSRoute53HostedZone { - results := map[string]AWSRoute53HostedZone{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRoute53HostedZone: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::HostedZone" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53HostedZone - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRoute53HostedZoneWithName retrieves all AWSRoute53HostedZone items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRoute53HostedZoneWithName(name string) (AWSRoute53HostedZone, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRoute53HostedZone: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::HostedZone" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53HostedZone - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRoute53HostedZone{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzoneconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzoneconfig.go deleted file mode 100644 index a3b82c0f77..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzoneconfig.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSRoute53HostedZone_HostedZoneConfig AWS CloudFormation Resource (AWS::Route53::HostedZone.HostedZoneConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-hostedzone-hostedzoneconfig.html -type AWSRoute53HostedZone_HostedZoneConfig struct { - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-hostedzone-hostedzoneconfig.html#cfn-route53-hostedzone-hostedzoneconfig-comment - Comment string `json:"Comment,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HostedZone_HostedZoneConfig) AWSCloudFormationType() string { - return "AWS::Route53::HostedZone.HostedZoneConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzonetag.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzonetag.go deleted file mode 100644 index 084c111879..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_hostedzonetag.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRoute53HostedZone_HostedZoneTag AWS CloudFormation Resource (AWS::Route53::HostedZone.HostedZoneTag) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-hostedzone-hostedzonetags.html -type AWSRoute53HostedZone_HostedZoneTag struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-hostedzone-hostedzonetags.html#cfn-route53-hostedzonetags-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-hostedzone-hostedzonetags.html#cfn-route53-hostedzonetags-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HostedZone_HostedZoneTag) AWSCloudFormationType() string { - return "AWS::Route53::HostedZone.HostedZoneTag" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_vpc.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_vpc.go deleted file mode 100644 index ada44ed7ae..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-hostedzone_vpc.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSRoute53HostedZone_VPC AWS CloudFormation Resource (AWS::Route53::HostedZone.VPC) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone-hostedzonevpcs.html -type AWSRoute53HostedZone_VPC struct { - - // VPCId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone-hostedzonevpcs.html#cfn-route53-hostedzone-hostedzonevpcs-vpcid - VPCId string `json:"VPCId,omitempty"` - - // VPCRegion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone-hostedzonevpcs.html#cfn-route53-hostedzone-hostedzonevpcs-vpcregion - VPCRegion string `json:"VPCRegion,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53HostedZone_VPC) AWSCloudFormationType() string { - return "AWS::Route53::HostedZone.VPC" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset.go deleted file mode 100644 index 0acf7b3128..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset.go +++ /dev/null @@ -1,175 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRoute53RecordSet AWS CloudFormation Resource (AWS::Route53::RecordSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html -type AWSRoute53RecordSet struct { - - // AliasTarget AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-aliastarget - AliasTarget *AWSRoute53RecordSet_AliasTarget `json:"AliasTarget,omitempty"` - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-comment - Comment string `json:"Comment,omitempty"` - - // Failover AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-failover - Failover string `json:"Failover,omitempty"` - - // GeoLocation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-geolocation - GeoLocation *AWSRoute53RecordSet_GeoLocation `json:"GeoLocation,omitempty"` - - // HealthCheckId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-healthcheckid - HealthCheckId string `json:"HealthCheckId,omitempty"` - - // HostedZoneId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzoneid - HostedZoneId string `json:"HostedZoneId,omitempty"` - - // HostedZoneName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename - HostedZoneName string `json:"HostedZoneName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-name - Name string `json:"Name,omitempty"` - - // Region AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-region - Region string `json:"Region,omitempty"` - - // ResourceRecords AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-resourcerecords - ResourceRecords []string `json:"ResourceRecords,omitempty"` - - // SetIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-setidentifier - SetIdentifier string `json:"SetIdentifier,omitempty"` - - // TTL AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-ttl - TTL string `json:"TTL,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-type - Type string `json:"Type,omitempty"` - - // Weight AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-weight - Weight int `json:"Weight,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSet) AWSCloudFormationType() string { - return "AWS::Route53::RecordSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRoute53RecordSet) MarshalJSON() ([]byte, error) { - type Properties AWSRoute53RecordSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRoute53RecordSet) UnmarshalJSON(b []byte) error { - type Properties AWSRoute53RecordSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRoute53RecordSet(*res.Properties) - } - - return nil -} - -// GetAllAWSRoute53RecordSetResources retrieves all AWSRoute53RecordSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSRoute53RecordSetResources() map[string]AWSRoute53RecordSet { - results := map[string]AWSRoute53RecordSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRoute53RecordSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::RecordSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53RecordSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRoute53RecordSetWithName retrieves all AWSRoute53RecordSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRoute53RecordSetWithName(name string) (AWSRoute53RecordSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRoute53RecordSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::RecordSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53RecordSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRoute53RecordSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_aliastarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_aliastarget.go deleted file mode 100644 index 8c0abca629..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_aliastarget.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSRoute53RecordSet_AliasTarget AWS CloudFormation Resource (AWS::Route53::RecordSet.AliasTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html -type AWSRoute53RecordSet_AliasTarget struct { - - // DNSName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-dnshostname - DNSName string `json:"DNSName,omitempty"` - - // EvaluateTargetHealth AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-evaluatetargethealth - EvaluateTargetHealth bool `json:"EvaluateTargetHealth,omitempty"` - - // HostedZoneId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-hostedzoneid - HostedZoneId string `json:"HostedZoneId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSet_AliasTarget) AWSCloudFormationType() string { - return "AWS::Route53::RecordSet.AliasTarget" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_geolocation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_geolocation.go deleted file mode 100644 index de96568b17..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordset_geolocation.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSRoute53RecordSet_GeoLocation AWS CloudFormation Resource (AWS::Route53::RecordSet.GeoLocation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html -type AWSRoute53RecordSet_GeoLocation struct { - - // ContinentCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordset-geolocation-continentcode - ContinentCode string `json:"ContinentCode,omitempty"` - - // CountryCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordset-geolocation-countrycode - CountryCode string `json:"CountryCode,omitempty"` - - // SubdivisionCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordset-geolocation-subdivisioncode - SubdivisionCode string `json:"SubdivisionCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSet_GeoLocation) AWSCloudFormationType() string { - return "AWS::Route53::RecordSet.GeoLocation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup.go deleted file mode 100644 index 86992701e7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSRoute53RecordSetGroup AWS CloudFormation Resource (AWS::Route53::RecordSetGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-recordsetgroup.html -type AWSRoute53RecordSetGroup struct { - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-recordsetgroup.html#cfn-route53-recordsetgroup-comment - Comment string `json:"Comment,omitempty"` - - // HostedZoneId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-recordsetgroup.html#cfn-route53-recordsetgroup-hostedzoneid - HostedZoneId string `json:"HostedZoneId,omitempty"` - - // HostedZoneName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-recordsetgroup.html#cfn-route53-recordsetgroup-hostedzonename - HostedZoneName string `json:"HostedZoneName,omitempty"` - - // RecordSets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-route53-recordsetgroup.html#cfn-route53-recordsetgroup-recordsets - RecordSets []AWSRoute53RecordSetGroup_RecordSet `json:"RecordSets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSetGroup) AWSCloudFormationType() string { - return "AWS::Route53::RecordSetGroup" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSRoute53RecordSetGroup) MarshalJSON() ([]byte, error) { - type Properties AWSRoute53RecordSetGroup - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSRoute53RecordSetGroup) UnmarshalJSON(b []byte) error { - type Properties AWSRoute53RecordSetGroup - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSRoute53RecordSetGroup(*res.Properties) - } - - return nil -} - -// GetAllAWSRoute53RecordSetGroupResources retrieves all AWSRoute53RecordSetGroup items from an AWS CloudFormation template -func (t *Template) GetAllAWSRoute53RecordSetGroupResources() map[string]AWSRoute53RecordSetGroup { - results := map[string]AWSRoute53RecordSetGroup{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSRoute53RecordSetGroup: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::RecordSetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53RecordSetGroup - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSRoute53RecordSetGroupWithName retrieves all AWSRoute53RecordSetGroup items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSRoute53RecordSetGroupWithName(name string) (AWSRoute53RecordSetGroup, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSRoute53RecordSetGroup: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Route53::RecordSetGroup" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSRoute53RecordSetGroup - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSRoute53RecordSetGroup{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_aliastarget.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_aliastarget.go deleted file mode 100644 index 39e570418d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_aliastarget.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSRoute53RecordSetGroup_AliasTarget AWS CloudFormation Resource (AWS::Route53::RecordSetGroup.AliasTarget) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html -type AWSRoute53RecordSetGroup_AliasTarget struct { - - // DNSName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-dnshostname - DNSName string `json:"DNSName,omitempty"` - - // EvaluateTargetHealth AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-evaluatetargethealth - EvaluateTargetHealth bool `json:"EvaluateTargetHealth,omitempty"` - - // HostedZoneId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html#cfn-route53-aliastarget-hostedzoneid - HostedZoneId string `json:"HostedZoneId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSetGroup_AliasTarget) AWSCloudFormationType() string { - return "AWS::Route53::RecordSetGroup.AliasTarget" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_geolocation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_geolocation.go deleted file mode 100644 index e7c1b581b3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_geolocation.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSRoute53RecordSetGroup_GeoLocation AWS CloudFormation Resource (AWS::Route53::RecordSetGroup.GeoLocation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html -type AWSRoute53RecordSetGroup_GeoLocation struct { - - // ContinentCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordsetgroup-geolocation-continentcode - ContinentCode string `json:"ContinentCode,omitempty"` - - // CountryCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordset-geolocation-countrycode - CountryCode string `json:"CountryCode,omitempty"` - - // SubdivisionCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset-geolocation.html#cfn-route53-recordset-geolocation-subdivisioncode - SubdivisionCode string `json:"SubdivisionCode,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSetGroup_GeoLocation) AWSCloudFormationType() string { - return "AWS::Route53::RecordSetGroup.GeoLocation" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_recordset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_recordset.go deleted file mode 100644 index 14981aa79d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-route53-recordsetgroup_recordset.go +++ /dev/null @@ -1,81 +0,0 @@ -package cloudformation - -// AWSRoute53RecordSetGroup_RecordSet AWS CloudFormation Resource (AWS::Route53::RecordSetGroup.RecordSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html -type AWSRoute53RecordSetGroup_RecordSet struct { - - // AliasTarget AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-aliastarget - AliasTarget *AWSRoute53RecordSetGroup_AliasTarget `json:"AliasTarget,omitempty"` - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-comment - Comment string `json:"Comment,omitempty"` - - // Failover AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-failover - Failover string `json:"Failover,omitempty"` - - // GeoLocation AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-geolocation - GeoLocation *AWSRoute53RecordSetGroup_GeoLocation `json:"GeoLocation,omitempty"` - - // HealthCheckId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-healthcheckid - HealthCheckId string `json:"HealthCheckId,omitempty"` - - // HostedZoneId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzoneid - HostedZoneId string `json:"HostedZoneId,omitempty"` - - // HostedZoneName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-hostedzonename - HostedZoneName string `json:"HostedZoneName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-name - Name string `json:"Name,omitempty"` - - // Region AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-region - Region string `json:"Region,omitempty"` - - // ResourceRecords AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-resourcerecords - ResourceRecords []string `json:"ResourceRecords,omitempty"` - - // SetIdentifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-setidentifier - SetIdentifier string `json:"SetIdentifier,omitempty"` - - // TTL AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-ttl - TTL string `json:"TTL,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-type - Type string `json:"Type,omitempty"` - - // Weight AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html#cfn-route53-recordset-weight - Weight int `json:"Weight,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSRoute53RecordSetGroup_RecordSet) AWSCloudFormationType() string { - return "AWS::Route53::RecordSetGroup.RecordSet" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket.go deleted file mode 100644 index 6efde767f7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket.go +++ /dev/null @@ -1,175 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSS3Bucket AWS CloudFormation Resource (AWS::S3::Bucket) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html -type AWSS3Bucket struct { - - // AccelerateConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-accelerateconfiguration - AccelerateConfiguration *AWSS3Bucket_AccelerateConfiguration `json:"AccelerateConfiguration,omitempty"` - - // AccessControl AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-accesscontrol - AccessControl string `json:"AccessControl,omitempty"` - - // AnalyticsConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-analyticsconfigurations - AnalyticsConfigurations []AWSS3Bucket_AnalyticsConfiguration `json:"AnalyticsConfigurations,omitempty"` - - // BucketName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-name - BucketName string `json:"BucketName,omitempty"` - - // CorsConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-crossoriginconfig - CorsConfiguration *AWSS3Bucket_CorsConfiguration `json:"CorsConfiguration,omitempty"` - - // InventoryConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-inventoryconfigurations - InventoryConfigurations []AWSS3Bucket_InventoryConfiguration `json:"InventoryConfigurations,omitempty"` - - // LifecycleConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-lifecycleconfig - LifecycleConfiguration *AWSS3Bucket_LifecycleConfiguration `json:"LifecycleConfiguration,omitempty"` - - // LoggingConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-loggingconfig - LoggingConfiguration *AWSS3Bucket_LoggingConfiguration `json:"LoggingConfiguration,omitempty"` - - // MetricsConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-metricsconfigurations - MetricsConfigurations []AWSS3Bucket_MetricsConfiguration `json:"MetricsConfigurations,omitempty"` - - // NotificationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-notification - NotificationConfiguration *AWSS3Bucket_NotificationConfiguration `json:"NotificationConfiguration,omitempty"` - - // ReplicationConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-replicationconfiguration - ReplicationConfiguration *AWSS3Bucket_ReplicationConfiguration `json:"ReplicationConfiguration,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-tags - Tags []Tag `json:"Tags,omitempty"` - - // VersioningConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-versioning - VersioningConfiguration *AWSS3Bucket_VersioningConfiguration `json:"VersioningConfiguration,omitempty"` - - // WebsiteConfiguration AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket.html#cfn-s3-bucket-websiteconfiguration - WebsiteConfiguration *AWSS3Bucket_WebsiteConfiguration `json:"WebsiteConfiguration,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket) AWSCloudFormationType() string { - return "AWS::S3::Bucket" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSS3Bucket) MarshalJSON() ([]byte, error) { - type Properties AWSS3Bucket - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSS3Bucket) UnmarshalJSON(b []byte) error { - type Properties AWSS3Bucket - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSS3Bucket(*res.Properties) - } - - return nil -} - -// GetAllAWSS3BucketResources retrieves all AWSS3Bucket items from an AWS CloudFormation template -func (t *Template) GetAllAWSS3BucketResources() map[string]AWSS3Bucket { - results := map[string]AWSS3Bucket{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSS3Bucket: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::S3::Bucket" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSS3Bucket - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSS3BucketWithName retrieves all AWSS3Bucket items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSS3BucketWithName(name string) (AWSS3Bucket, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSS3Bucket: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::S3::Bucket" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSS3Bucket - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSS3Bucket{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_abortincompletemultipartupload.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_abortincompletemultipartupload.go deleted file mode 100644 index 724e760953..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_abortincompletemultipartupload.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_AbortIncompleteMultipartUpload AWS CloudFormation Resource (AWS::S3::Bucket.AbortIncompleteMultipartUpload) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-abortincompletemultipartupload.html -type AWSS3Bucket_AbortIncompleteMultipartUpload struct { - - // DaysAfterInitiation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-abortincompletemultipartupload.html#cfn-s3-bucket-abortincompletemultipartupload-daysafterinitiation - DaysAfterInitiation int `json:"DaysAfterInitiation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_AbortIncompleteMultipartUpload) AWSCloudFormationType() string { - return "AWS::S3::Bucket.AbortIncompleteMultipartUpload" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_accelerateconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_accelerateconfiguration.go deleted file mode 100644 index d2167e5a24..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_accelerateconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_AccelerateConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.AccelerateConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-accelerateconfiguration.html -type AWSS3Bucket_AccelerateConfiguration struct { - - // AccelerationStatus AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-accelerateconfiguration.html#cfn-s3-bucket-accelerateconfiguration-accelerationstatus - AccelerationStatus string `json:"AccelerationStatus,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_AccelerateConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.AccelerateConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_analyticsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_analyticsconfiguration.go deleted file mode 100644 index ada22b0106..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_analyticsconfiguration.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSS3Bucket_AnalyticsConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.AnalyticsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-analyticsconfiguration.html -type AWSS3Bucket_AnalyticsConfiguration struct { - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-analyticsconfiguration.html#cfn-s3-bucket-analyticsconfiguration-id - Id string `json:"Id,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-analyticsconfiguration.html#cfn-s3-bucket-analyticsconfiguration-prefix - Prefix string `json:"Prefix,omitempty"` - - // StorageClassAnalysis AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-analyticsconfiguration.html#cfn-s3-bucket-analyticsconfiguration-storageclassanalysis - StorageClassAnalysis *AWSS3Bucket_StorageClassAnalysis `json:"StorageClassAnalysis,omitempty"` - - // TagFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-analyticsconfiguration.html#cfn-s3-bucket-analyticsconfiguration-tagfilters - TagFilters []AWSS3Bucket_TagFilter `json:"TagFilters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_AnalyticsConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.AnalyticsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsconfiguration.go deleted file mode 100644 index 0a6699cace..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_CorsConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.CorsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors.html -type AWSS3Bucket_CorsConfiguration struct { - - // CorsRules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors.html#cfn-s3-bucket-cors-corsrule - CorsRules []AWSS3Bucket_CorsRule `json:"CorsRules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_CorsConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.CorsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsrule.go deleted file mode 100644 index 9ea5b6d670..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_corsrule.go +++ /dev/null @@ -1,41 +0,0 @@ -package cloudformation - -// AWSS3Bucket_CorsRule AWS CloudFormation Resource (AWS::S3::Bucket.CorsRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html -type AWSS3Bucket_CorsRule struct { - - // AllowedHeaders AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-allowedheaders - AllowedHeaders []string `json:"AllowedHeaders,omitempty"` - - // AllowedMethods AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-allowedmethods - AllowedMethods []string `json:"AllowedMethods,omitempty"` - - // AllowedOrigins AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-allowedorigins - AllowedOrigins []string `json:"AllowedOrigins,omitempty"` - - // ExposedHeaders AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-exposedheaders - ExposedHeaders []string `json:"ExposedHeaders,omitempty"` - - // Id AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-id - Id string `json:"Id,omitempty"` - - // MaxAge AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-cors-corsrule.html#cfn-s3-bucket-cors-corsrule-maxage - MaxAge int `json:"MaxAge,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_CorsRule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.CorsRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_dataexport.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_dataexport.go deleted file mode 100644 index 66fbe3caef..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_dataexport.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_DataExport AWS CloudFormation Resource (AWS::S3::Bucket.DataExport) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-dataexport.html -type AWSS3Bucket_DataExport struct { - - // Destination AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-dataexport.html#cfn-s3-bucket-dataexport-destination - Destination *AWSS3Bucket_Destination `json:"Destination,omitempty"` - - // OutputSchemaVersion AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-dataexport.html#cfn-s3-bucket-dataexport-outputschemaversion - OutputSchemaVersion string `json:"OutputSchemaVersion,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_DataExport) AWSCloudFormationType() string { - return "AWS::S3::Bucket.DataExport" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_destination.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_destination.go deleted file mode 100644 index ada48703b2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_destination.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSS3Bucket_Destination AWS CloudFormation Resource (AWS::S3::Bucket.Destination) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-destination.html -type AWSS3Bucket_Destination struct { - - // BucketAccountId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-destination.html#cfn-s3-bucket-destination-bucketaccountid - BucketAccountId string `json:"BucketAccountId,omitempty"` - - // BucketArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-destination.html#cfn-s3-bucket-destination-bucketarn - BucketArn string `json:"BucketArn,omitempty"` - - // Format AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-destination.html#cfn-s3-bucket-destination-format - Format string `json:"Format,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-destination.html#cfn-s3-bucket-destination-prefix - Prefix string `json:"Prefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_Destination) AWSCloudFormationType() string { - return "AWS::S3::Bucket.Destination" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_filterrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_filterrule.go deleted file mode 100644 index 451ec289eb..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_filterrule.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_FilterRule AWS CloudFormation Resource (AWS::S3::Bucket.FilterRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter-s3key-rules.html -type AWSS3Bucket_FilterRule struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter-s3key-rules.html#cfn-s3-bucket-notificationconfiguraiton-config-filter-s3key-rules-name - Name string `json:"Name,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter-s3key-rules.html#cfn-s3-bucket-notificationconfiguraiton-config-filter-s3key-rules-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_FilterRule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.FilterRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_inventoryconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_inventoryconfiguration.go deleted file mode 100644 index 2853be67ff..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_inventoryconfiguration.go +++ /dev/null @@ -1,46 +0,0 @@ -package cloudformation - -// AWSS3Bucket_InventoryConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.InventoryConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html -type AWSS3Bucket_InventoryConfiguration struct { - - // Destination AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-destination - Destination *AWSS3Bucket_Destination `json:"Destination,omitempty"` - - // Enabled AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-enabled - Enabled bool `json:"Enabled,omitempty"` - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-id - Id string `json:"Id,omitempty"` - - // IncludedObjectVersions AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-includedobjectversions - IncludedObjectVersions string `json:"IncludedObjectVersions,omitempty"` - - // OptionalFields AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-optionalfields - OptionalFields []string `json:"OptionalFields,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-prefix - Prefix string `json:"Prefix,omitempty"` - - // ScheduleFrequency AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-inventoryconfiguration.html#cfn-s3-bucket-inventoryconfiguration-schedulefrequency - ScheduleFrequency string `json:"ScheduleFrequency,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_InventoryConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.InventoryConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lambdaconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lambdaconfiguration.go deleted file mode 100644 index c18724661b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lambdaconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_LambdaConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.LambdaConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html -type AWSS3Bucket_LambdaConfiguration struct { - - // Event AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-event - Event string `json:"Event,omitempty"` - - // Filter AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-filter - Filter *AWSS3Bucket_NotificationFilter `json:"Filter,omitempty"` - - // Function AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-lambdaconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig-function - Function string `json:"Function,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_LambdaConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.LambdaConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lifecycleconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lifecycleconfiguration.go deleted file mode 100644 index d9bb503de3..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_lifecycleconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_LifecycleConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.LifecycleConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html -type AWSS3Bucket_LifecycleConfiguration struct { - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig.html#cfn-s3-bucket-lifecycleconfig-rules - Rules []AWSS3Bucket_Rule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_LifecycleConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.LifecycleConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_loggingconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_loggingconfiguration.go deleted file mode 100644 index c8e3b61655..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_loggingconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_LoggingConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.LoggingConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-loggingconfig.html -type AWSS3Bucket_LoggingConfiguration struct { - - // DestinationBucketName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-loggingconfig.html#cfn-s3-bucket-loggingconfig-destinationbucketname - DestinationBucketName string `json:"DestinationBucketName,omitempty"` - - // LogFilePrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-loggingconfig.html#cfn-s3-bucket-loggingconfig-logfileprefix - LogFilePrefix string `json:"LogFilePrefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_LoggingConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.LoggingConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_metricsconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_metricsconfiguration.go deleted file mode 100644 index a1197bfbb8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_metricsconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_MetricsConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.MetricsConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html -type AWSS3Bucket_MetricsConfiguration struct { - - // Id AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-id - Id string `json:"Id,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-prefix - Prefix string `json:"Prefix,omitempty"` - - // TagFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-metricsconfiguration.html#cfn-s3-bucket-metricsconfiguration-tagfilters - TagFilters []AWSS3Bucket_TagFilter `json:"TagFilters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_MetricsConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.MetricsConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_noncurrentversiontransition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_noncurrentversiontransition.go deleted file mode 100644 index fd7c988957..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_noncurrentversiontransition.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_NoncurrentVersionTransition AWS CloudFormation Resource (AWS::S3::Bucket.NoncurrentVersionTransition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition.html -type AWSS3Bucket_NoncurrentVersionTransition struct { - - // StorageClass AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition.html#cfn-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition-storageclass - StorageClass string `json:"StorageClass,omitempty"` - - // TransitionInDays AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition.html#cfn-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition-transitionindays - TransitionInDays int `json:"TransitionInDays,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_NoncurrentVersionTransition) AWSCloudFormationType() string { - return "AWS::S3::Bucket.NoncurrentVersionTransition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationconfiguration.go deleted file mode 100644 index cf2e8f087f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_NotificationConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.NotificationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig.html -type AWSS3Bucket_NotificationConfiguration struct { - - // LambdaConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig.html#cfn-s3-bucket-notificationconfig-lambdaconfig - LambdaConfigurations []AWSS3Bucket_LambdaConfiguration `json:"LambdaConfigurations,omitempty"` - - // QueueConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig.html#cfn-s3-bucket-notificationconfig-queueconfig - QueueConfigurations []AWSS3Bucket_QueueConfiguration `json:"QueueConfigurations,omitempty"` - - // TopicConfigurations AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig.html#cfn-s3-bucket-notificationconfig-topicconfig - TopicConfigurations []AWSS3Bucket_TopicConfiguration `json:"TopicConfigurations,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_NotificationConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.NotificationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationfilter.go deleted file mode 100644 index 09ba33412b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_notificationfilter.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_NotificationFilter AWS CloudFormation Resource (AWS::S3::Bucket.NotificationFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter.html -type AWSS3Bucket_NotificationFilter struct { - - // S3Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter.html#cfn-s3-bucket-notificationconfiguraiton-config-filter-s3key - S3Key *AWSS3Bucket_S3KeyFilter `json:"S3Key,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_NotificationFilter) AWSCloudFormationType() string { - return "AWS::S3::Bucket.NotificationFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_queueconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_queueconfiguration.go deleted file mode 100644 index 9f8d865445..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_queueconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_QueueConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.QueueConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-queueconfig.html -type AWSS3Bucket_QueueConfiguration struct { - - // Event AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-queueconfig.html#cfn-s3-bucket-notificationconfig-queueconfig-event - Event string `json:"Event,omitempty"` - - // Filter AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-queueconfig.html#cfn-s3-bucket-notificationconfig-queueconfig-filter - Filter *AWSS3Bucket_NotificationFilter `json:"Filter,omitempty"` - - // Queue AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-queueconfig.html#cfn-s3-bucket-notificationconfig-queueconfig-queue - Queue string `json:"Queue,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_QueueConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.QueueConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectallrequeststo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectallrequeststo.go deleted file mode 100644 index 37114b7ac9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectallrequeststo.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_RedirectAllRequestsTo AWS CloudFormation Resource (AWS::S3::Bucket.RedirectAllRequestsTo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html -type AWSS3Bucket_RedirectAllRequestsTo struct { - - // HostName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html#cfn-s3-websiteconfiguration-redirectallrequeststo-hostname - HostName string `json:"HostName,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-redirectallrequeststo.html#cfn-s3-websiteconfiguration-redirectallrequeststo-protocol - Protocol string `json:"Protocol,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_RedirectAllRequestsTo) AWSCloudFormationType() string { - return "AWS::S3::Bucket.RedirectAllRequestsTo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectrule.go deleted file mode 100644 index 348e4466d5..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_redirectrule.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSS3Bucket_RedirectRule AWS CloudFormation Resource (AWS::S3::Bucket.RedirectRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html -type AWSS3Bucket_RedirectRule struct { - - // HostName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html#cfn-s3-websiteconfiguration-redirectrule-hostname - HostName string `json:"HostName,omitempty"` - - // HttpRedirectCode AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html#cfn-s3-websiteconfiguration-redirectrule-httpredirectcode - HttpRedirectCode string `json:"HttpRedirectCode,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html#cfn-s3-websiteconfiguration-redirectrule-protocol - Protocol string `json:"Protocol,omitempty"` - - // ReplaceKeyPrefixWith AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html#cfn-s3-websiteconfiguration-redirectrule-replacekeyprefixwith - ReplaceKeyPrefixWith string `json:"ReplaceKeyPrefixWith,omitempty"` - - // ReplaceKeyWith AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-redirectrule.html#cfn-s3-websiteconfiguration-redirectrule-replacekeywith - ReplaceKeyWith string `json:"ReplaceKeyWith,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_RedirectRule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.RedirectRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationconfiguration.go deleted file mode 100644 index a15826e27e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationconfiguration.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_ReplicationConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.ReplicationConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration.html -type AWSS3Bucket_ReplicationConfiguration struct { - - // Role AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration.html#cfn-s3-bucket-replicationconfiguration-role - Role string `json:"Role,omitempty"` - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration.html#cfn-s3-bucket-replicationconfiguration-rules - Rules []AWSS3Bucket_ReplicationRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_ReplicationConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.ReplicationConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationdestination.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationdestination.go deleted file mode 100644 index 8faf383c3c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationdestination.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_ReplicationDestination AWS CloudFormation Resource (AWS::S3::Bucket.ReplicationDestination) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules-destination.html -type AWSS3Bucket_ReplicationDestination struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules-destination.html#cfn-s3-bucket-replicationconfiguration-rules-destination-bucket - Bucket string `json:"Bucket,omitempty"` - - // StorageClass AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules-destination.html#cfn-s3-bucket-replicationconfiguration-rules-destination-storageclass - StorageClass string `json:"StorageClass,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_ReplicationDestination) AWSCloudFormationType() string { - return "AWS::S3::Bucket.ReplicationDestination" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationrule.go deleted file mode 100644 index edcbb5e946..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_replicationrule.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSS3Bucket_ReplicationRule AWS CloudFormation Resource (AWS::S3::Bucket.ReplicationRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules.html -type AWSS3Bucket_ReplicationRule struct { - - // Destination AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules.html#cfn-s3-bucket-replicationconfiguration-rules-destination - Destination *AWSS3Bucket_ReplicationDestination `json:"Destination,omitempty"` - - // Id AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules.html#cfn-s3-bucket-replicationconfiguration-rules-id - Id string `json:"Id,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules.html#cfn-s3-bucket-replicationconfiguration-rules-prefix - Prefix string `json:"Prefix,omitempty"` - - // Status AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-replicationconfiguration-rules.html#cfn-s3-bucket-replicationconfiguration-rules-status - Status string `json:"Status,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_ReplicationRule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.ReplicationRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrule.go deleted file mode 100644 index e13b8903d9..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrule.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_RoutingRule AWS CloudFormation Resource (AWS::S3::Bucket.RoutingRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules.html -type AWSS3Bucket_RoutingRule struct { - - // RedirectRule AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules.html#cfn-s3-websiteconfiguration-routingrules-redirectrule - RedirectRule *AWSS3Bucket_RedirectRule `json:"RedirectRule,omitempty"` - - // RoutingRuleCondition AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules.html#cfn-s3-websiteconfiguration-routingrules-routingrulecondition - RoutingRuleCondition *AWSS3Bucket_RoutingRuleCondition `json:"RoutingRuleCondition,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_RoutingRule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.RoutingRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrulecondition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrulecondition.go deleted file mode 100644 index ee5d46a76a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_routingrulecondition.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_RoutingRuleCondition AWS CloudFormation Resource (AWS::S3::Bucket.RoutingRuleCondition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-routingrulecondition.html -type AWSS3Bucket_RoutingRuleCondition struct { - - // HttpErrorCodeReturnedEquals AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-routingrulecondition.html#cfn-s3-websiteconfiguration-routingrules-routingrulecondition-httperrorcodereturnedequals - HttpErrorCodeReturnedEquals string `json:"HttpErrorCodeReturnedEquals,omitempty"` - - // KeyPrefixEquals AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration-routingrules-routingrulecondition.html#cfn-s3-websiteconfiguration-routingrules-routingrulecondition-keyprefixequals - KeyPrefixEquals string `json:"KeyPrefixEquals,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_RoutingRuleCondition) AWSCloudFormationType() string { - return "AWS::S3::Bucket.RoutingRuleCondition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_rule.go deleted file mode 100644 index 87e65e9627..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_rule.go +++ /dev/null @@ -1,71 +0,0 @@ -package cloudformation - -// AWSS3Bucket_Rule AWS CloudFormation Resource (AWS::S3::Bucket.Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html -type AWSS3Bucket_Rule struct { - - // AbortIncompleteMultipartUpload AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-rule-abortincompletemultipartupload - AbortIncompleteMultipartUpload *AWSS3Bucket_AbortIncompleteMultipartUpload `json:"AbortIncompleteMultipartUpload,omitempty"` - - // ExpirationDate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-expirationdate - ExpirationDate string `json:"ExpirationDate,omitempty"` - - // ExpirationInDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-expirationindays - ExpirationInDays int `json:"ExpirationInDays,omitempty"` - - // Id AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-id - Id string `json:"Id,omitempty"` - - // NoncurrentVersionExpirationInDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-noncurrentversionexpirationindays - NoncurrentVersionExpirationInDays int `json:"NoncurrentVersionExpirationInDays,omitempty"` - - // NoncurrentVersionTransition AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-noncurrentversiontransition - NoncurrentVersionTransition *AWSS3Bucket_NoncurrentVersionTransition `json:"NoncurrentVersionTransition,omitempty"` - - // NoncurrentVersionTransitions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-noncurrentversiontransitions - NoncurrentVersionTransitions []AWSS3Bucket_NoncurrentVersionTransition `json:"NoncurrentVersionTransitions,omitempty"` - - // Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-prefix - Prefix string `json:"Prefix,omitempty"` - - // Status AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-status - Status string `json:"Status,omitempty"` - - // TagFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-rule-tagfilters - TagFilters []AWSS3Bucket_TagFilter `json:"TagFilters,omitempty"` - - // Transition AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-transition - Transition *AWSS3Bucket_Transition `json:"Transition,omitempty"` - - // Transitions AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule.html#cfn-s3-bucket-lifecycleconfig-rule-transitions - Transitions []AWSS3Bucket_Transition `json:"Transitions,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_Rule) AWSCloudFormationType() string { - return "AWS::S3::Bucket.Rule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_s3keyfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_s3keyfilter.go deleted file mode 100644 index 6716bf3e3a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_s3keyfilter.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_S3KeyFilter AWS CloudFormation Resource (AWS::S3::Bucket.S3KeyFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter-s3key.html -type AWSS3Bucket_S3KeyFilter struct { - - // Rules AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter-s3key.html#cfn-s3-bucket-notificationconfiguraiton-config-filter-s3key-rules - Rules []AWSS3Bucket_FilterRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_S3KeyFilter) AWSCloudFormationType() string { - return "AWS::S3::Bucket.S3KeyFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_storageclassanalysis.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_storageclassanalysis.go deleted file mode 100644 index c326fa71d7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_storageclassanalysis.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_StorageClassAnalysis AWS CloudFormation Resource (AWS::S3::Bucket.StorageClassAnalysis) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-storageclassanalysis.html -type AWSS3Bucket_StorageClassAnalysis struct { - - // DataExport AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-storageclassanalysis.html#cfn-s3-bucket-storageclassanalysis-dataexport - DataExport *AWSS3Bucket_DataExport `json:"DataExport,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_StorageClassAnalysis) AWSCloudFormationType() string { - return "AWS::S3::Bucket.StorageClassAnalysis" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_tagfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_tagfilter.go deleted file mode 100644 index 2d5a758b4c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_tagfilter.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSS3Bucket_TagFilter AWS CloudFormation Resource (AWS::S3::Bucket.TagFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-tagfilter.html -type AWSS3Bucket_TagFilter struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-tagfilter.html#cfn-s3-bucket-tagfilter-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-tagfilter.html#cfn-s3-bucket-tagfilter-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_TagFilter) AWSCloudFormationType() string { - return "AWS::S3::Bucket.TagFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_topicconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_topicconfiguration.go deleted file mode 100644 index f5d90a2ff6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_topicconfiguration.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_TopicConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.TopicConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-topicconfig.html -type AWSS3Bucket_TopicConfiguration struct { - - // Event AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-topicconfig.html#cfn-s3-bucket-notificationconfig-topicconfig-event - Event string `json:"Event,omitempty"` - - // Filter AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-topicconfig.html#cfn-s3-bucket-notificationconfig-topicconfig-filter - Filter *AWSS3Bucket_NotificationFilter `json:"Filter,omitempty"` - - // Topic AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfig-topicconfig.html#cfn-s3-bucket-notificationconfig-topicconfig-topic - Topic string `json:"Topic,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_TopicConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.TopicConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_transition.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_transition.go deleted file mode 100644 index 92d4ef850d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_transition.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSS3Bucket_Transition AWS CloudFormation Resource (AWS::S3::Bucket.Transition) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-transition.html -type AWSS3Bucket_Transition struct { - - // StorageClass AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-transition.html#cfn-s3-bucket-lifecycleconfig-rule-transition-storageclass - StorageClass string `json:"StorageClass,omitempty"` - - // TransitionDate AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-transition.html#cfn-s3-bucket-lifecycleconfig-rule-transition-transitiondate - TransitionDate string `json:"TransitionDate,omitempty"` - - // TransitionInDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-lifecycleconfig-rule-transition.html#cfn-s3-bucket-lifecycleconfig-rule-transition-transitionindays - TransitionInDays int `json:"TransitionInDays,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_Transition) AWSCloudFormationType() string { - return "AWS::S3::Bucket.Transition" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_versioningconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_versioningconfiguration.go deleted file mode 100644 index f8548e3faa..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_versioningconfiguration.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSS3Bucket_VersioningConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.VersioningConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-versioningconfig.html -type AWSS3Bucket_VersioningConfiguration struct { - - // Status AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-versioningconfig.html#cfn-s3-bucket-versioningconfig-status - Status string `json:"Status,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_VersioningConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.VersioningConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_websiteconfiguration.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_websiteconfiguration.go deleted file mode 100644 index 47324e0b5e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucket_websiteconfiguration.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSS3Bucket_WebsiteConfiguration AWS CloudFormation Resource (AWS::S3::Bucket.WebsiteConfiguration) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration.html -type AWSS3Bucket_WebsiteConfiguration struct { - - // ErrorDocument AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration.html#cfn-s3-websiteconfiguration-errordocument - ErrorDocument string `json:"ErrorDocument,omitempty"` - - // IndexDocument AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration.html#cfn-s3-websiteconfiguration-indexdocument - IndexDocument string `json:"IndexDocument,omitempty"` - - // RedirectAllRequestsTo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration.html#cfn-s3-websiteconfiguration-redirectallrequeststo - RedirectAllRequestsTo *AWSS3Bucket_RedirectAllRequestsTo `json:"RedirectAllRequestsTo,omitempty"` - - // RoutingRules AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-websiteconfiguration.html#cfn-s3-websiteconfiguration-routingrules - RoutingRules []AWSS3Bucket_RoutingRule `json:"RoutingRules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3Bucket_WebsiteConfiguration) AWSCloudFormationType() string { - return "AWS::S3::Bucket.WebsiteConfiguration" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucketpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucketpolicy.go deleted file mode 100644 index 36d63a734a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-s3-bucketpolicy.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSS3BucketPolicy AWS CloudFormation Resource (AWS::S3::BucketPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-policy.html -type AWSS3BucketPolicy struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-policy.html#aws-properties-s3-policy-bucket - Bucket string `json:"Bucket,omitempty"` - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-policy.html#aws-properties-s3-policy-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSS3BucketPolicy) AWSCloudFormationType() string { - return "AWS::S3::BucketPolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSS3BucketPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSS3BucketPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSS3BucketPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSS3BucketPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSS3BucketPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSS3BucketPolicyResources retrieves all AWSS3BucketPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSS3BucketPolicyResources() map[string]AWSS3BucketPolicy { - results := map[string]AWSS3BucketPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSS3BucketPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::S3::BucketPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSS3BucketPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSS3BucketPolicyWithName retrieves all AWSS3BucketPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSS3BucketPolicyWithName(name string) (AWSS3BucketPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSS3BucketPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::S3::BucketPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSS3BucketPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSS3BucketPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sdb-domain.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sdb-domain.go deleted file mode 100644 index 7a60001637..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sdb-domain.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSDBDomain AWS CloudFormation Resource (AWS::SDB::Domain) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-simpledb.html -type AWSSDBDomain struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-simpledb.html#cfn-sdb-domain-description - Description string `json:"Description,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSDBDomain) AWSCloudFormationType() string { - return "AWS::SDB::Domain" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSDBDomain) MarshalJSON() ([]byte, error) { - type Properties AWSSDBDomain - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSDBDomain) UnmarshalJSON(b []byte) error { - type Properties AWSSDBDomain - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSDBDomain(*res.Properties) - } - - return nil -} - -// GetAllAWSSDBDomainResources retrieves all AWSSDBDomain items from an AWS CloudFormation template -func (t *Template) GetAllAWSSDBDomainResources() map[string]AWSSDBDomain { - results := map[string]AWSSDBDomain{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSDBDomain: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SDB::Domain" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSDBDomain - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSDBDomainWithName retrieves all AWSSDBDomain items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSDBDomainWithName(name string) (AWSSDBDomain, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSDBDomain: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SDB::Domain" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSDBDomain - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSDBDomain{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api.go deleted file mode 100644 index 17335679be..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api.go +++ /dev/null @@ -1,140 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSServerlessApi AWS CloudFormation Resource (AWS::Serverless::Api) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi -type AWSServerlessApi struct { - - // CacheClusterEnabled AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - CacheClusterEnabled bool `json:"CacheClusterEnabled,omitempty"` - - // CacheClusterSize AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - CacheClusterSize string `json:"CacheClusterSize,omitempty"` - - // DefinitionBody AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - DefinitionBody interface{} `json:"DefinitionBody,omitempty"` - - // DefinitionUri AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - DefinitionUri *AWSServerlessApi_DefinitionUri `json:"DefinitionUri,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - Name string `json:"Name,omitempty"` - - // StageName AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - StageName string `json:"StageName,omitempty"` - - // Variables AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessapi - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessApi) AWSCloudFormationType() string { - return "AWS::Serverless::Api" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSServerlessApi) MarshalJSON() ([]byte, error) { - type Properties AWSServerlessApi - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSServerlessApi) UnmarshalJSON(b []byte) error { - type Properties AWSServerlessApi - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSServerlessApi(*res.Properties) - } - - return nil -} - -// GetAllAWSServerlessApiResources retrieves all AWSServerlessApi items from an AWS CloudFormation template -func (t *Template) GetAllAWSServerlessApiResources() map[string]AWSServerlessApi { - results := map[string]AWSServerlessApi{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSServerlessApi: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::Api" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessApi - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSServerlessApiWithName retrieves all AWSServerlessApi items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSServerlessApiWithName(name string) (AWSServerlessApi, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSServerlessApi: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::Api" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessApi - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSServerlessApi{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api_s3location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api_s3location.go deleted file mode 100644 index ae8eaa1e8a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-api_s3location.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessApi_S3Location AWS CloudFormation Resource (AWS::Serverless::Api.S3Location) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3-location-object -type AWSServerlessApi_S3Location struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Bucket string `json:"Bucket,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Key string `json:"Key,omitempty"` - - // Version AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Version int `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessApi_S3Location) AWSCloudFormationType() string { - return "AWS::Serverless::Api.S3Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function.go deleted file mode 100644 index f5ae2ba062..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSServerlessFunction AWS CloudFormation Resource (AWS::Serverless::Function) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction -type AWSServerlessFunction struct { - - // CodeUri AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - CodeUri *AWSServerlessFunction_CodeUri `json:"CodeUri,omitempty"` - - // DeadLetterQueue AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - DeadLetterQueue *AWSServerlessFunction_DeadLetterQueue `json:"DeadLetterQueue,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Description string `json:"Description,omitempty"` - - // Environment AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Environment *AWSServerlessFunction_FunctionEnvironment `json:"Environment,omitempty"` - - // Events AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Events map[string]AWSServerlessFunction_EventSource `json:"Events,omitempty"` - - // FunctionName AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - FunctionName string `json:"FunctionName,omitempty"` - - // Handler AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Handler string `json:"Handler,omitempty"` - - // KmsKeyArn AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - KmsKeyArn string `json:"KmsKeyArn,omitempty"` - - // MemorySize AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - MemorySize int `json:"MemorySize,omitempty"` - - // Policies AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Policies *AWSServerlessFunction_Policies `json:"Policies,omitempty"` - - // Role AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Role string `json:"Role,omitempty"` - - // Runtime AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Runtime string `json:"Runtime,omitempty"` - - // Tags AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Tags map[string]string `json:"Tags,omitempty"` - - // Timeout AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Timeout int `json:"Timeout,omitempty"` - - // Tracing AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Tracing string `json:"Tracing,omitempty"` - - // VpcConfig AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - VpcConfig *AWSServerlessFunction_VpcConfig `json:"VpcConfig,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction) AWSCloudFormationType() string { - return "AWS::Serverless::Function" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSServerlessFunction) MarshalJSON() ([]byte, error) { - type Properties AWSServerlessFunction - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSServerlessFunction) UnmarshalJSON(b []byte) error { - type Properties AWSServerlessFunction - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSServerlessFunction(*res.Properties) - } - - return nil -} - -// GetAllAWSServerlessFunctionResources retrieves all AWSServerlessFunction items from an AWS CloudFormation template -func (t *Template) GetAllAWSServerlessFunctionResources() map[string]AWSServerlessFunction { - results := map[string]AWSServerlessFunction{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSServerlessFunction: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::Function" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessFunction - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSServerlessFunctionWithName retrieves all AWSServerlessFunction items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSServerlessFunctionWithName(name string) (AWSServerlessFunction, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSServerlessFunction: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::Function" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessFunction - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSServerlessFunction{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_alexaskillevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_alexaskillevent.go deleted file mode 100644 index b9a76fa56b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_alexaskillevent.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_AlexaSkillEvent AWS CloudFormation Resource (AWS::Serverless::Function.AlexaSkillEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#alexaskill -type AWSServerlessFunction_AlexaSkillEvent struct { - - // Variables AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#alexaskill - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_AlexaSkillEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.AlexaSkillEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_apievent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_apievent.go deleted file mode 100644 index b8e2d2e231..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_apievent.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_ApiEvent AWS CloudFormation Resource (AWS::Serverless::Function.ApiEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api -type AWSServerlessFunction_ApiEvent struct { - - // Method AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api - Method string `json:"Method,omitempty"` - - // Path AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api - Path string `json:"Path,omitempty"` - - // RestApiId AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api - RestApiId string `json:"RestApiId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_ApiEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.ApiEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_cloudwatcheventevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_cloudwatcheventevent.go deleted file mode 100644 index ef6ff16045..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_cloudwatcheventevent.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_CloudWatchEventEvent AWS CloudFormation Resource (AWS::Serverless::Function.CloudWatchEventEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#cloudwatchevent -type AWSServerlessFunction_CloudWatchEventEvent struct { - - // Input AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#cloudwatchevent - Input string `json:"Input,omitempty"` - - // InputPath AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#cloudwatchevent - InputPath string `json:"InputPath,omitempty"` - - // Pattern AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html - Pattern interface{} `json:"Pattern,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_CloudWatchEventEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.CloudWatchEventEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_deadletterqueue.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_deadletterqueue.go deleted file mode 100644 index 16da9e397b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_deadletterqueue.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_DeadLetterQueue AWS CloudFormation Resource (AWS::Serverless::Function.DeadLetterQueue) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#deadletterqueue-object -type AWSServerlessFunction_DeadLetterQueue struct { - - // TargetArn AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - TargetArn string `json:"TargetArn,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_DeadLetterQueue) AWSCloudFormationType() string { - return "AWS::Serverless::Function.DeadLetterQueue" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_dynamodbevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_dynamodbevent.go deleted file mode 100644 index 6dfab150c1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_dynamodbevent.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_DynamoDBEvent AWS CloudFormation Resource (AWS::Serverless::Function.DynamoDBEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#dynamodb -type AWSServerlessFunction_DynamoDBEvent struct { - - // BatchSize AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#dynamodb - BatchSize int `json:"BatchSize,omitempty"` - - // StartingPosition AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#dynamodb - StartingPosition string `json:"StartingPosition,omitempty"` - - // Stream AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#dynamodb - Stream string `json:"Stream,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_DynamoDBEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.DynamoDBEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_eventsource.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_eventsource.go deleted file mode 100644 index 73f283f06e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_eventsource.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_EventSource AWS CloudFormation Resource (AWS::Serverless::Function.EventSource) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#event-source-object -type AWSServerlessFunction_EventSource struct { - - // Properties AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#event-source-types - Properties *AWSServerlessFunction_Properties `json:"Properties,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#event-source-object - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_EventSource) AWSCloudFormationType() string { - return "AWS::Serverless::Function.EventSource" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_functionenvironment.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_functionenvironment.go deleted file mode 100644 index 1975480731..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_functionenvironment.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_FunctionEnvironment AWS CloudFormation Resource (AWS::Serverless::Function.FunctionEnvironment) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object -type AWSServerlessFunction_FunctionEnvironment struct { - - // Variables AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object - Variables map[string]string `json:"Variables,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_FunctionEnvironment) AWSCloudFormationType() string { - return "AWS::Serverless::Function.FunctionEnvironment" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iampolicydocument.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iampolicydocument.go deleted file mode 100644 index 57a2044756..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iampolicydocument.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_IAMPolicyDocument AWS CloudFormation Resource (AWS::Serverless::Function.IAMPolicyDocument) -// See: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html -type AWSServerlessFunction_IAMPolicyDocument struct { - - // Statement AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html - Statement interface{} `json:"Statement,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_IAMPolicyDocument) AWSCloudFormationType() string { - return "AWS::Serverless::Function.IAMPolicyDocument" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iotruleevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iotruleevent.go deleted file mode 100644 index c236f74261..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_iotruleevent.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_IoTRuleEvent AWS CloudFormation Resource (AWS::Serverless::Function.IoTRuleEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#iotrule -type AWSServerlessFunction_IoTRuleEvent struct { - - // AwsIotSqlVersion AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#iotrule - AwsIotSqlVersion string `json:"AwsIotSqlVersion,omitempty"` - - // Sql AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#iotrule - Sql string `json:"Sql,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_IoTRuleEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.IoTRuleEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_kinesisevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_kinesisevent.go deleted file mode 100644 index 242c168cf7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_kinesisevent.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_KinesisEvent AWS CloudFormation Resource (AWS::Serverless::Function.KinesisEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#kinesis -type AWSServerlessFunction_KinesisEvent struct { - - // BatchSize AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#kinesis - BatchSize int `json:"BatchSize,omitempty"` - - // StartingPosition AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#kinesis - StartingPosition string `json:"StartingPosition,omitempty"` - - // Stream AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#kinesis - Stream string `json:"Stream,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_KinesisEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.KinesisEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3event.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3event.go deleted file mode 100644 index 40bfe64722..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3event.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_S3Event AWS CloudFormation Resource (AWS::Serverless::Function.S3Event) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3 -type AWSServerlessFunction_S3Event struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3 - Bucket string `json:"Bucket,omitempty"` - - // Events AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3 - Events *AWSServerlessFunction_Events `json:"Events,omitempty"` - - // Filter AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3 - Filter *AWSServerlessFunction_S3NotificationFilter `json:"Filter,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_S3Event) AWSCloudFormationType() string { - return "AWS::Serverless::Function.S3Event" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3location.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3location.go deleted file mode 100644 index cf1fdc653d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3location.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_S3Location AWS CloudFormation Resource (AWS::Serverless::Function.S3Location) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#s3-location-object -type AWSServerlessFunction_S3Location struct { - - // Bucket AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Bucket string `json:"Bucket,omitempty"` - - // Key AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Key string `json:"Key,omitempty"` - - // Version AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction - Version int `json:"Version,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_S3Location) AWSCloudFormationType() string { - return "AWS::Serverless::Function.S3Location" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3notificationfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3notificationfilter.go deleted file mode 100644 index 47f8827be7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_s3notificationfilter.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_S3NotificationFilter AWS CloudFormation Resource (AWS::Serverless::Function.S3NotificationFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter.html -type AWSServerlessFunction_S3NotificationFilter struct { - - // S3Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-s3-bucket-notificationconfiguration-config-filter.html - S3Key string `json:"S3Key,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_S3NotificationFilter) AWSCloudFormationType() string { - return "AWS::Serverless::Function.S3NotificationFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_scheduleevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_scheduleevent.go deleted file mode 100644 index d313b33c77..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_scheduleevent.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_ScheduleEvent AWS CloudFormation Resource (AWS::Serverless::Function.ScheduleEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule -type AWSServerlessFunction_ScheduleEvent struct { - - // Input AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule - Input string `json:"Input,omitempty"` - - // Schedule AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#schedule - Schedule string `json:"Schedule,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_ScheduleEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.ScheduleEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_snsevent.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_snsevent.go deleted file mode 100644 index eef66c8b8a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_snsevent.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_SNSEvent AWS CloudFormation Resource (AWS::Serverless::Function.SNSEvent) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#sns -type AWSServerlessFunction_SNSEvent struct { - - // Topic AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#sns - Topic string `json:"Topic,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_SNSEvent) AWSCloudFormationType() string { - return "AWS::Serverless::Function.SNSEvent" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_vpcconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_vpcconfig.go deleted file mode 100644 index a75b050ee0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-function_vpcconfig.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessFunction_VpcConfig AWS CloudFormation Resource (AWS::Serverless::Function.VpcConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html -type AWSServerlessFunction_VpcConfig struct { - - // SecurityGroupIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html - SecurityGroupIds []string `json:"SecurityGroupIds,omitempty"` - - // SubnetIds AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-vpcconfig.html - SubnetIds []string `json:"SubnetIds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessFunction_VpcConfig) AWSCloudFormationType() string { - return "AWS::Serverless::Function.VpcConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable.go deleted file mode 100644 index 52097c4b9c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSServerlessSimpleTable AWS CloudFormation Resource (AWS::Serverless::SimpleTable) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlesssimpletable -type AWSServerlessSimpleTable struct { - - // PrimaryKey AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#primary-key-object - PrimaryKey *AWSServerlessSimpleTable_PrimaryKey `json:"PrimaryKey,omitempty"` - - // ProvisionedThroughput AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html - ProvisionedThroughput *AWSServerlessSimpleTable_ProvisionedThroughput `json:"ProvisionedThroughput,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessSimpleTable) AWSCloudFormationType() string { - return "AWS::Serverless::SimpleTable" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSServerlessSimpleTable) MarshalJSON() ([]byte, error) { - type Properties AWSServerlessSimpleTable - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSServerlessSimpleTable) UnmarshalJSON(b []byte) error { - type Properties AWSServerlessSimpleTable - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSServerlessSimpleTable(*res.Properties) - } - - return nil -} - -// GetAllAWSServerlessSimpleTableResources retrieves all AWSServerlessSimpleTable items from an AWS CloudFormation template -func (t *Template) GetAllAWSServerlessSimpleTableResources() map[string]AWSServerlessSimpleTable { - results := map[string]AWSServerlessSimpleTable{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSServerlessSimpleTable: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::SimpleTable" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessSimpleTable - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSServerlessSimpleTableWithName retrieves all AWSServerlessSimpleTable items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSServerlessSimpleTableWithName(name string) (AWSServerlessSimpleTable, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSServerlessSimpleTable: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::Serverless::SimpleTable" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSServerlessSimpleTable - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSServerlessSimpleTable{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_primarykey.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_primarykey.go deleted file mode 100644 index c155324425..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_primarykey.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessSimpleTable_PrimaryKey AWS CloudFormation Resource (AWS::Serverless::SimpleTable.PrimaryKey) -// See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#primary-key-object -type AWSServerlessSimpleTable_PrimaryKey struct { - - // Name AWS CloudFormation Property - // Required: false - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#primary-key-object - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#primary-key-object - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessSimpleTable_PrimaryKey) AWSCloudFormationType() string { - return "AWS::Serverless::SimpleTable.PrimaryKey" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_provisionedthroughput.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_provisionedthroughput.go deleted file mode 100644 index c2ce8e4b39..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-serverless-simpletable_provisionedthroughput.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSServerlessSimpleTable_ProvisionedThroughput AWS CloudFormation Resource (AWS::Serverless::SimpleTable.ProvisionedThroughput) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html -type AWSServerlessSimpleTable_ProvisionedThroughput struct { - - // ReadCapacityUnits AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html - ReadCapacityUnits int `json:"ReadCapacityUnits,omitempty"` - - // WriteCapacityUnits AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-provisionedthroughput.html - WriteCapacityUnits int `json:"WriteCapacityUnits,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSServerlessSimpleTable_ProvisionedThroughput) AWSCloudFormationType() string { - return "AWS::Serverless::SimpleTable.ProvisionedThroughput" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-subscription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-subscription.go deleted file mode 100644 index 72342a6605..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-subscription.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSNSSubscription AWS CloudFormation Resource (AWS::SNS::Subscription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html -type AWSSNSSubscription struct { - - // Endpoint AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html#cfn-sns-endpoint - Endpoint string `json:"Endpoint,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html#cfn-sns-protocol - Protocol string `json:"Protocol,omitempty"` - - // TopicArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-sns-subscription.html#topicarn - TopicArn string `json:"TopicArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSNSSubscription) AWSCloudFormationType() string { - return "AWS::SNS::Subscription" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSNSSubscription) MarshalJSON() ([]byte, error) { - type Properties AWSSNSSubscription - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSNSSubscription) UnmarshalJSON(b []byte) error { - type Properties AWSSNSSubscription - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSNSSubscription(*res.Properties) - } - - return nil -} - -// GetAllAWSSNSSubscriptionResources retrieves all AWSSNSSubscription items from an AWS CloudFormation template -func (t *Template) GetAllAWSSNSSubscriptionResources() map[string]AWSSNSSubscription { - results := map[string]AWSSNSSubscription{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSNSSubscription: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::Subscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSSubscription - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSNSSubscriptionWithName retrieves all AWSSNSSubscription items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSNSSubscriptionWithName(name string) (AWSSNSSubscription, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSNSSubscription: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::Subscription" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSSubscription - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSNSSubscription{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic.go deleted file mode 100644 index 2b04dfd37d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSNSTopic AWS CloudFormation Resource (AWS::SNS::Topic) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html -type AWSSNSTopic struct { - - // DisplayName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html#cfn-sns-topic-displayname - DisplayName string `json:"DisplayName,omitempty"` - - // Subscription AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html#cfn-sns-topic-subscription - Subscription []AWSSNSTopic_Subscription `json:"Subscription,omitempty"` - - // TopicName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-topic.html#cfn-sns-topic-topicname - TopicName string `json:"TopicName,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSNSTopic) AWSCloudFormationType() string { - return "AWS::SNS::Topic" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSNSTopic) MarshalJSON() ([]byte, error) { - type Properties AWSSNSTopic - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSNSTopic) UnmarshalJSON(b []byte) error { - type Properties AWSSNSTopic - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSNSTopic(*res.Properties) - } - - return nil -} - -// GetAllAWSSNSTopicResources retrieves all AWSSNSTopic items from an AWS CloudFormation template -func (t *Template) GetAllAWSSNSTopicResources() map[string]AWSSNSTopic { - results := map[string]AWSSNSTopic{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSNSTopic: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::Topic" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSTopic - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSNSTopicWithName retrieves all AWSSNSTopic items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSNSTopicWithName(name string) (AWSSNSTopic, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSNSTopic: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::Topic" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSTopic - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSNSTopic{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic_subscription.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic_subscription.go deleted file mode 100644 index 2539fbecc1..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topic_subscription.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSNSTopic_Subscription AWS CloudFormation Resource (AWS::SNS::Topic.Subscription) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-subscription.html -type AWSSNSTopic_Subscription struct { - - // Endpoint AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-subscription.html#cfn-sns-topic-subscription-endpoint - Endpoint string `json:"Endpoint,omitempty"` - - // Protocol AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-subscription.html#cfn-sns-topic-subscription-protocol - Protocol string `json:"Protocol,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSNSTopic_Subscription) AWSCloudFormationType() string { - return "AWS::SNS::Topic.Subscription" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topicpolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topicpolicy.go deleted file mode 100644 index 53b4f4262d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sns-topicpolicy.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSNSTopicPolicy AWS CloudFormation Resource (AWS::SNS::TopicPolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-policy.html -type AWSSNSTopicPolicy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-policy.html#cfn-sns-topicpolicy-policydocument - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // Topics AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sns-policy.html#cfn-sns-topicpolicy-topics - Topics []string `json:"Topics,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSNSTopicPolicy) AWSCloudFormationType() string { - return "AWS::SNS::TopicPolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSNSTopicPolicy) MarshalJSON() ([]byte, error) { - type Properties AWSSNSTopicPolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSNSTopicPolicy) UnmarshalJSON(b []byte) error { - type Properties AWSSNSTopicPolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSNSTopicPolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSSNSTopicPolicyResources retrieves all AWSSNSTopicPolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSSNSTopicPolicyResources() map[string]AWSSNSTopicPolicy { - results := map[string]AWSSNSTopicPolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSNSTopicPolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::TopicPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSTopicPolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSNSTopicPolicyWithName retrieves all AWSSNSTopicPolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSNSTopicPolicyWithName(name string) (AWSSNSTopicPolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSNSTopicPolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SNS::TopicPolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSNSTopicPolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSNSTopicPolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queue.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queue.go deleted file mode 100644 index 95a632dbc2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queue.go +++ /dev/null @@ -1,160 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSQSQueue AWS CloudFormation Resource (AWS::SQS::Queue) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html -type AWSSQSQueue struct { - - // ContentBasedDeduplication AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-contentbaseddeduplication - ContentBasedDeduplication bool `json:"ContentBasedDeduplication,omitempty"` - - // DelaySeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-delayseconds - DelaySeconds int `json:"DelaySeconds,omitempty"` - - // FifoQueue AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-fifoqueue - FifoQueue bool `json:"FifoQueue,omitempty"` - - // KmsDataKeyReusePeriodSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsdatakeyreuseperiodseconds - KmsDataKeyReusePeriodSeconds int `json:"KmsDataKeyReusePeriodSeconds,omitempty"` - - // KmsMasterKeyId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-kmsmasterkeyid - KmsMasterKeyId string `json:"KmsMasterKeyId,omitempty"` - - // MaximumMessageSize AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-maxmesgsize - MaximumMessageSize int `json:"MaximumMessageSize,omitempty"` - - // MessageRetentionPeriod AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-msgretentionperiod - MessageRetentionPeriod int `json:"MessageRetentionPeriod,omitempty"` - - // QueueName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-name - QueueName string `json:"QueueName,omitempty"` - - // ReceiveMessageWaitTimeSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-receivemsgwaittime - ReceiveMessageWaitTimeSeconds int `json:"ReceiveMessageWaitTimeSeconds,omitempty"` - - // RedrivePolicy AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-redrive - RedrivePolicy interface{} `json:"RedrivePolicy,omitempty"` - - // VisibilityTimeout AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-queues.html#aws-sqs-queue-visiblitytimeout - VisibilityTimeout int `json:"VisibilityTimeout,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSQSQueue) AWSCloudFormationType() string { - return "AWS::SQS::Queue" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSQSQueue) MarshalJSON() ([]byte, error) { - type Properties AWSSQSQueue - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSQSQueue) UnmarshalJSON(b []byte) error { - type Properties AWSSQSQueue - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSQSQueue(*res.Properties) - } - - return nil -} - -// GetAllAWSSQSQueueResources retrieves all AWSSQSQueue items from an AWS CloudFormation template -func (t *Template) GetAllAWSSQSQueueResources() map[string]AWSSQSQueue { - results := map[string]AWSSQSQueue{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSQSQueue: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SQS::Queue" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSQSQueue - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSQSQueueWithName retrieves all AWSSQSQueue items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSQSQueueWithName(name string) (AWSSQSQueue, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSQSQueue: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SQS::Queue" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSQSQueue - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSQSQueue{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queuepolicy.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queuepolicy.go deleted file mode 100644 index a46db209d6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-sqs-queuepolicy.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSQSQueuePolicy AWS CloudFormation Resource (AWS::SQS::QueuePolicy) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-policy.html -type AWSSQSQueuePolicy struct { - - // PolicyDocument AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-policy.html#cfn-sqs-queuepolicy-policydoc - PolicyDocument interface{} `json:"PolicyDocument,omitempty"` - - // Queues AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-sqs-policy.html#cfn-sqs-queuepolicy-queues - Queues []string `json:"Queues,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSQSQueuePolicy) AWSCloudFormationType() string { - return "AWS::SQS::QueuePolicy" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSQSQueuePolicy) MarshalJSON() ([]byte, error) { - type Properties AWSSQSQueuePolicy - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSQSQueuePolicy) UnmarshalJSON(b []byte) error { - type Properties AWSSQSQueuePolicy - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSQSQueuePolicy(*res.Properties) - } - - return nil -} - -// GetAllAWSSQSQueuePolicyResources retrieves all AWSSQSQueuePolicy items from an AWS CloudFormation template -func (t *Template) GetAllAWSSQSQueuePolicyResources() map[string]AWSSQSQueuePolicy { - results := map[string]AWSSQSQueuePolicy{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSQSQueuePolicy: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SQS::QueuePolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSQSQueuePolicy - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSQSQueuePolicyWithName retrieves all AWSSQSQueuePolicy items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSQSQueuePolicyWithName(name string) (AWSSQSQueuePolicy, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSQSQueuePolicy: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SQS::QueuePolicy" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSQSQueuePolicy - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSQSQueuePolicy{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association.go deleted file mode 100644 index 0daa8c281b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSSMAssociation AWS CloudFormation Resource (AWS::SSM::Association) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html -type AWSSSMAssociation struct { - - // DocumentVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-documentversion - DocumentVersion string `json:"DocumentVersion,omitempty"` - - // InstanceId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-instanceid - InstanceId string `json:"InstanceId,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-name - Name string `json:"Name,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-parameters - Parameters map[string]AWSSSMAssociation_ParameterValues `json:"Parameters,omitempty"` - - // ScheduleExpression AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-scheduleexpression - ScheduleExpression string `json:"ScheduleExpression,omitempty"` - - // Targets AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-association.html#cfn-ssm-association-targets - Targets []AWSSSMAssociation_Target `json:"Targets,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMAssociation) AWSCloudFormationType() string { - return "AWS::SSM::Association" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSSMAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSSSMAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSSMAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSSSMAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSSMAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSSSMAssociationResources retrieves all AWSSSMAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSSSMAssociationResources() map[string]AWSSSMAssociation { - results := map[string]AWSSSMAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSSMAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Association" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSSMAssociationWithName retrieves all AWSSSMAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSSMAssociationWithName(name string) (AWSSSMAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSSMAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Association" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSSMAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_parametervalues.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_parametervalues.go deleted file mode 100644 index 8040247f95..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_parametervalues.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSSSMAssociation_ParameterValues AWS CloudFormation Resource (AWS::SSM::Association.ParameterValues) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-association-parametervalues.html -type AWSSSMAssociation_ParameterValues struct { - - // ParameterValues AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-association-parametervalues.html#cfn-ssm-association-parametervalues-parametervalues - ParameterValues []string `json:"ParameterValues,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMAssociation_ParameterValues) AWSCloudFormationType() string { - return "AWS::SSM::Association.ParameterValues" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_target.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_target.go deleted file mode 100644 index a080a94e25..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-association_target.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSSMAssociation_Target AWS CloudFormation Resource (AWS::SSM::Association.Target) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-association-target.html -type AWSSSMAssociation_Target struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-association-target.html#cfn-ssm-association-target-key - Key string `json:"Key,omitempty"` - - // Values AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-association-target.html#cfn-ssm-association-target-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMAssociation_Target) AWSCloudFormationType() string { - return "AWS::SSM::Association.Target" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-document.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-document.go deleted file mode 100644 index 0b49ca8c27..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-document.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSSMDocument AWS CloudFormation Resource (AWS::SSM::Document) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-document.html -type AWSSSMDocument struct { - - // Content AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-document.html#cfn-ssm-document-content - Content interface{} `json:"Content,omitempty"` - - // DocumentType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-document.html#cfn-ssm-document-documenttype - DocumentType string `json:"DocumentType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMDocument) AWSCloudFormationType() string { - return "AWS::SSM::Document" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSSMDocument) MarshalJSON() ([]byte, error) { - type Properties AWSSSMDocument - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSSMDocument) UnmarshalJSON(b []byte) error { - type Properties AWSSSMDocument - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSSMDocument(*res.Properties) - } - - return nil -} - -// GetAllAWSSSMDocumentResources retrieves all AWSSSMDocument items from an AWS CloudFormation template -func (t *Template) GetAllAWSSSMDocumentResources() map[string]AWSSSMDocument { - results := map[string]AWSSSMDocument{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSSMDocument: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Document" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMDocument - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSSMDocumentWithName retrieves all AWSSSMDocument items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSSMDocumentWithName(name string) (AWSSSMDocument, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSSMDocument: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Document" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMDocument - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSSMDocument{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask.go deleted file mode 100644 index 8c811dd645..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask.go +++ /dev/null @@ -1,170 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSSMMaintenanceWindowTask AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html -type AWSSSMMaintenanceWindowTask struct { - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-description - Description string `json:"Description,omitempty"` - - // LoggingInfo AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-logginginfo - LoggingInfo *AWSSSMMaintenanceWindowTask_LoggingInfo `json:"LoggingInfo,omitempty"` - - // MaxConcurrency AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-maxconcurrency - MaxConcurrency string `json:"MaxConcurrency,omitempty"` - - // MaxErrors AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-maxerrors - MaxErrors string `json:"MaxErrors,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-name - Name string `json:"Name,omitempty"` - - // Priority AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-priority - Priority int `json:"Priority,omitempty"` - - // ServiceRoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-servicerolearn - ServiceRoleArn string `json:"ServiceRoleArn,omitempty"` - - // Targets AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-targets - Targets []AWSSSMMaintenanceWindowTask_Target `json:"Targets,omitempty"` - - // TaskArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskarn - TaskArn string `json:"TaskArn,omitempty"` - - // TaskInvocationParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters - TaskInvocationParameters *AWSSSMMaintenanceWindowTask_TaskInvocationParameters `json:"TaskInvocationParameters,omitempty"` - - // TaskParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-taskparameters - TaskParameters interface{} `json:"TaskParameters,omitempty"` - - // TaskType AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-tasktype - TaskType string `json:"TaskType,omitempty"` - - // WindowId AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-maintenancewindowtask.html#cfn-ssm-maintenancewindowtask-windowid - WindowId string `json:"WindowId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSSMMaintenanceWindowTask) MarshalJSON() ([]byte, error) { - type Properties AWSSSMMaintenanceWindowTask - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSSMMaintenanceWindowTask) UnmarshalJSON(b []byte) error { - type Properties AWSSSMMaintenanceWindowTask - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSSMMaintenanceWindowTask(*res.Properties) - } - - return nil -} - -// GetAllAWSSSMMaintenanceWindowTaskResources retrieves all AWSSSMMaintenanceWindowTask items from an AWS CloudFormation template -func (t *Template) GetAllAWSSSMMaintenanceWindowTaskResources() map[string]AWSSSMMaintenanceWindowTask { - results := map[string]AWSSSMMaintenanceWindowTask{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSSMMaintenanceWindowTask: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::MaintenanceWindowTask" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMMaintenanceWindowTask - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSSMMaintenanceWindowTaskWithName retrieves all AWSSSMMaintenanceWindowTask items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSSMMaintenanceWindowTaskWithName(name string) (AWSSSMMaintenanceWindowTask, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSSMMaintenanceWindowTask: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::MaintenanceWindowTask" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMMaintenanceWindowTask - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSSMMaintenanceWindowTask{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_logginginfo.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_logginginfo.go deleted file mode 100644 index 6185a9fdf2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_logginginfo.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_LoggingInfo AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.LoggingInfo) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html -type AWSSSMMaintenanceWindowTask_LoggingInfo struct { - - // Region AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-region - Region string `json:"Region,omitempty"` - - // S3Bucket AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-s3bucket - S3Bucket string `json:"S3Bucket,omitempty"` - - // S3Prefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-logginginfo.html#cfn-ssm-maintenancewindowtask-logginginfo-s3prefix - S3Prefix string `json:"S3Prefix,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_LoggingInfo) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.LoggingInfo" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowautomationparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowautomationparameters.go deleted file mode 100644 index 2fc3799d12..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowautomationparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_MaintenanceWindowAutomationParameters AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.MaintenanceWindowAutomationParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowautomationparameters.html -type AWSSSMMaintenanceWindowTask_MaintenanceWindowAutomationParameters struct { - - // DocumentVersion AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowautomationparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowautomationparameters-documentversion - DocumentVersion string `json:"DocumentVersion,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowautomationparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowautomationparameters-parameters - Parameters interface{} `json:"Parameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_MaintenanceWindowAutomationParameters) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowAutomationParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowlambdaparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowlambdaparameters.go deleted file mode 100644 index 1cfbdad09f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowlambdaparameters.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_MaintenanceWindowLambdaParameters AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.MaintenanceWindowLambdaParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html -type AWSSSMMaintenanceWindowTask_MaintenanceWindowLambdaParameters struct { - - // ClientContext AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-clientcontext - ClientContext string `json:"ClientContext,omitempty"` - - // Payload AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-payload - Payload string `json:"Payload,omitempty"` - - // Qualifier AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowlambdaparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowlambdaparameters-qualifier - Qualifier string `json:"Qualifier,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_MaintenanceWindowLambdaParameters) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowLambdaParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowruncommandparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowruncommandparameters.go deleted file mode 100644 index 7515a0903a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowruncommandparameters.go +++ /dev/null @@ -1,56 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_MaintenanceWindowRunCommandParameters AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html -type AWSSSMMaintenanceWindowTask_MaintenanceWindowRunCommandParameters struct { - - // Comment AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-comment - Comment string `json:"Comment,omitempty"` - - // DocumentHash AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthash - DocumentHash string `json:"DocumentHash,omitempty"` - - // DocumentHashType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-documenthashtype - DocumentHashType string `json:"DocumentHashType,omitempty"` - - // NotificationConfig AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-notificationconfig - NotificationConfig *AWSSSMMaintenanceWindowTask_NotificationConfig `json:"NotificationConfig,omitempty"` - - // OutputS3BucketName AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3bucketname - OutputS3BucketName string `json:"OutputS3BucketName,omitempty"` - - // OutputS3KeyPrefix AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-outputs3keyprefix - OutputS3KeyPrefix string `json:"OutputS3KeyPrefix,omitempty"` - - // Parameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-parameters - Parameters interface{} `json:"Parameters,omitempty"` - - // ServiceRoleArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-servicerolearn - ServiceRoleArn string `json:"ServiceRoleArn,omitempty"` - - // TimeoutSeconds AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowruncommandparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowruncommandparameters-timeoutseconds - TimeoutSeconds int `json:"TimeoutSeconds,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_MaintenanceWindowRunCommandParameters) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowRunCommandParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowstepfunctionsparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowstepfunctionsparameters.go deleted file mode 100644 index 6ec288595d..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_maintenancewindowstepfunctionsparameters.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_MaintenanceWindowStepFunctionsParameters AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.MaintenanceWindowStepFunctionsParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters.html -type AWSSSMMaintenanceWindowTask_MaintenanceWindowStepFunctionsParameters struct { - - // Input AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters-input - Input string `json:"Input,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters.html#cfn-ssm-maintenancewindowtask-maintenancewindowstepfunctionsparameters-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_MaintenanceWindowStepFunctionsParameters) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.MaintenanceWindowStepFunctionsParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_notificationconfig.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_notificationconfig.go deleted file mode 100644 index 2ca1baeacf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_notificationconfig.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_NotificationConfig AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.NotificationConfig) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html -type AWSSSMMaintenanceWindowTask_NotificationConfig struct { - - // NotificationArn AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationarn - NotificationArn string `json:"NotificationArn,omitempty"` - - // NotificationEvents AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationevents - NotificationEvents []string `json:"NotificationEvents,omitempty"` - - // NotificationType AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-notificationconfig.html#cfn-ssm-maintenancewindowtask-notificationconfig-notificationtype - NotificationType string `json:"NotificationType,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_NotificationConfig) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.NotificationConfig" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_target.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_target.go deleted file mode 100644 index 4bf1090d97..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_target.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_Target AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.Target) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-target.html -type AWSSSMMaintenanceWindowTask_Target struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-target.html#cfn-ssm-maintenancewindowtask-target-key - Key string `json:"Key,omitempty"` - - // Values AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-target.html#cfn-ssm-maintenancewindowtask-target-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_Target) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.Target" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_taskinvocationparameters.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_taskinvocationparameters.go deleted file mode 100644 index 82ac54fffc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-maintenancewindowtask_taskinvocationparameters.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSSSMMaintenanceWindowTask_TaskInvocationParameters AWS CloudFormation Resource (AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html -type AWSSSMMaintenanceWindowTask_TaskInvocationParameters struct { - - // MaintenanceWindowAutomationParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowautomationparameters - MaintenanceWindowAutomationParameters *AWSSSMMaintenanceWindowTask_MaintenanceWindowAutomationParameters `json:"MaintenanceWindowAutomationParameters,omitempty"` - - // MaintenanceWindowLambdaParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowlambdaparameters - MaintenanceWindowLambdaParameters *AWSSSMMaintenanceWindowTask_MaintenanceWindowLambdaParameters `json:"MaintenanceWindowLambdaParameters,omitempty"` - - // MaintenanceWindowRunCommandParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowruncommandparameters - MaintenanceWindowRunCommandParameters *AWSSSMMaintenanceWindowTask_MaintenanceWindowRunCommandParameters `json:"MaintenanceWindowRunCommandParameters,omitempty"` - - // MaintenanceWindowStepFunctionsParameters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-maintenancewindowtask-taskinvocationparameters.html#cfn-ssm-maintenancewindowtask-taskinvocationparameters-maintenancewindowstepfunctionsparameters - MaintenanceWindowStepFunctionsParameters *AWSSSMMaintenanceWindowTask_MaintenanceWindowStepFunctionsParameters `json:"MaintenanceWindowStepFunctionsParameters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMMaintenanceWindowTask_TaskInvocationParameters) AWSCloudFormationType() string { - return "AWS::SSM::MaintenanceWindowTask.TaskInvocationParameters" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-parameter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-parameter.go deleted file mode 100644 index a9036d5c89..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-parameter.go +++ /dev/null @@ -1,130 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSSMParameter AWS CloudFormation Resource (AWS::SSM::Parameter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html -type AWSSSMParameter struct { - - // AllowedPattern AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html#cfn-ssm-parameter-allowedpattern - AllowedPattern string `json:"AllowedPattern,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html#cfn-ssm-parameter-description - Description string `json:"Description,omitempty"` - - // Name AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html#cfn-ssm-parameter-name - Name string `json:"Name,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html#cfn-ssm-parameter-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-parameter.html#cfn-ssm-parameter-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMParameter) AWSCloudFormationType() string { - return "AWS::SSM::Parameter" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSSMParameter) MarshalJSON() ([]byte, error) { - type Properties AWSSSMParameter - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSSMParameter) UnmarshalJSON(b []byte) error { - type Properties AWSSSMParameter - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSSMParameter(*res.Properties) - } - - return nil -} - -// GetAllAWSSSMParameterResources retrieves all AWSSSMParameter items from an AWS CloudFormation template -func (t *Template) GetAllAWSSSMParameterResources() map[string]AWSSSMParameter { - results := map[string]AWSSSMParameter{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSSMParameter: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Parameter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMParameter - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSSMParameterWithName retrieves all AWSSSMParameter items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSSMParameterWithName(name string) (AWSSSMParameter, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSSMParameter: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::Parameter" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMParameter - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSSMParameter{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline.go deleted file mode 100644 index 5d27930ce0..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSSSMPatchBaseline AWS CloudFormation Resource (AWS::SSM::PatchBaseline) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html -type AWSSSMPatchBaseline struct { - - // ApprovalRules AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvalrules - ApprovalRules *AWSSSMPatchBaseline_RuleGroup `json:"ApprovalRules,omitempty"` - - // ApprovedPatches AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatches - ApprovedPatches []string `json:"ApprovedPatches,omitempty"` - - // ApprovedPatchesComplianceLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-approvedpatchescompliancelevel - ApprovedPatchesComplianceLevel string `json:"ApprovedPatchesComplianceLevel,omitempty"` - - // Description AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-description - Description string `json:"Description,omitempty"` - - // GlobalFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-globalfilters - GlobalFilters *AWSSSMPatchBaseline_PatchFilterGroup `json:"GlobalFilters,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-name - Name string `json:"Name,omitempty"` - - // OperatingSystem AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-operatingsystem - OperatingSystem string `json:"OperatingSystem,omitempty"` - - // PatchGroups AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-patchgroups - PatchGroups []AWSSSMPatchBaseline_PatchGroup `json:"PatchGroups,omitempty"` - - // RejectedPatches AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ssm-patchbaseline.html#cfn-ssm-patchbaseline-rejectedpatches - RejectedPatches []string `json:"RejectedPatches,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSSSMPatchBaseline) MarshalJSON() ([]byte, error) { - type Properties AWSSSMPatchBaseline - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSSSMPatchBaseline) UnmarshalJSON(b []byte) error { - type Properties AWSSSMPatchBaseline - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSSSMPatchBaseline(*res.Properties) - } - - return nil -} - -// GetAllAWSSSMPatchBaselineResources retrieves all AWSSSMPatchBaseline items from an AWS CloudFormation template -func (t *Template) GetAllAWSSSMPatchBaselineResources() map[string]AWSSSMPatchBaseline { - results := map[string]AWSSSMPatchBaseline{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSSSMPatchBaseline: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::PatchBaseline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMPatchBaseline - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSSSMPatchBaselineWithName retrieves all AWSSSMPatchBaseline items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSSSMPatchBaselineWithName(name string) (AWSSSMPatchBaseline, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSSSMPatchBaseline: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::SSM::PatchBaseline" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSSSMPatchBaseline - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSSSMPatchBaseline{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfilter.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfilter.go deleted file mode 100644 index 2ff1bb0a34..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfilter.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSSSMPatchBaseline_PatchFilter AWS CloudFormation Resource (AWS::SSM::PatchBaseline.PatchFilter) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html -type AWSSSMPatchBaseline_PatchFilter struct { - - // Key AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html#cfn-ssm-patchbaseline-patchfilter-key - Key string `json:"Key,omitempty"` - - // Values AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfilter.html#cfn-ssm-patchbaseline-patchfilter-values - Values []string `json:"Values,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline_PatchFilter) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline.PatchFilter" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfiltergroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfiltergroup.go deleted file mode 100644 index 13e2509a93..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchfiltergroup.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSSSMPatchBaseline_PatchFilterGroup AWS CloudFormation Resource (AWS::SSM::PatchBaseline.PatchFilterGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfiltergroup.html -type AWSSSMPatchBaseline_PatchFilterGroup struct { - - // PatchFilters AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-patchfiltergroup.html#cfn-ssm-patchbaseline-patchfiltergroup-patchfilters - PatchFilters []AWSSSMPatchBaseline_PatchFilter `json:"PatchFilters,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline_PatchFilterGroup) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline.PatchFilterGroup" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchgroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchgroup.go deleted file mode 100644 index 97ee734dd8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_patchgroup.go +++ /dev/null @@ -1,11 +0,0 @@ -package cloudformation - -// AWSSSMPatchBaseline_PatchGroup AWS CloudFormation Resource (AWS::SSM::PatchBaseline.PatchGroup) -// See: -type AWSSSMPatchBaseline_PatchGroup struct { -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline_PatchGroup) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline.PatchGroup" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rule.go deleted file mode 100644 index ce9ecb50b2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rule.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSSSMPatchBaseline_Rule AWS CloudFormation Resource (AWS::SSM::PatchBaseline.Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rule.html -type AWSSSMPatchBaseline_Rule struct { - - // ApproveAfterDays AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rule.html#cfn-ssm-patchbaseline-rule-approveafterdays - ApproveAfterDays int `json:"ApproveAfterDays,omitempty"` - - // ComplianceLevel AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rule.html#cfn-ssm-patchbaseline-rule-compliancelevel - ComplianceLevel string `json:"ComplianceLevel,omitempty"` - - // PatchFilterGroup AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rule.html#cfn-ssm-patchbaseline-rule-patchfiltergroup - PatchFilterGroup *AWSSSMPatchBaseline_PatchFilterGroup `json:"PatchFilterGroup,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline_Rule) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline.Rule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rulegroup.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rulegroup.go deleted file mode 100644 index 6680d6b7cc..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-ssm-patchbaseline_rulegroup.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSSSMPatchBaseline_RuleGroup AWS CloudFormation Resource (AWS::SSM::PatchBaseline.RuleGroup) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rulegroup.html -type AWSSSMPatchBaseline_RuleGroup struct { - - // PatchRules AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ssm-patchbaseline-rulegroup.html#cfn-ssm-patchbaseline-rulegroup-patchrules - PatchRules []AWSSSMPatchBaseline_Rule `json:"PatchRules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSSSMPatchBaseline_RuleGroup) AWSCloudFormationType() string { - return "AWS::SSM::PatchBaseline.RuleGroup" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-activity.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-activity.go deleted file mode 100644 index d2d92416bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-activity.go +++ /dev/null @@ -1,110 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSStepFunctionsActivity AWS CloudFormation Resource (AWS::StepFunctions::Activity) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-activity.html -type AWSStepFunctionsActivity struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-activity.html#cfn-stepfunctions-activity-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSStepFunctionsActivity) AWSCloudFormationType() string { - return "AWS::StepFunctions::Activity" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSStepFunctionsActivity) MarshalJSON() ([]byte, error) { - type Properties AWSStepFunctionsActivity - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSStepFunctionsActivity) UnmarshalJSON(b []byte) error { - type Properties AWSStepFunctionsActivity - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSStepFunctionsActivity(*res.Properties) - } - - return nil -} - -// GetAllAWSStepFunctionsActivityResources retrieves all AWSStepFunctionsActivity items from an AWS CloudFormation template -func (t *Template) GetAllAWSStepFunctionsActivityResources() map[string]AWSStepFunctionsActivity { - results := map[string]AWSStepFunctionsActivity{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSStepFunctionsActivity: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::StepFunctions::Activity" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSStepFunctionsActivity - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSStepFunctionsActivityWithName retrieves all AWSStepFunctionsActivity items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSStepFunctionsActivityWithName(name string) (AWSStepFunctionsActivity, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSStepFunctionsActivity: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::StepFunctions::Activity" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSStepFunctionsActivity - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSStepFunctionsActivity{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-statemachine.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-statemachine.go deleted file mode 100644 index c4dc4ffe02..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-stepfunctions-statemachine.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSStepFunctionsStateMachine AWS CloudFormation Resource (AWS::StepFunctions::StateMachine) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html -type AWSStepFunctionsStateMachine struct { - - // DefinitionString AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html#cfn-stepfunctions-statemachine-definitionstring - DefinitionString string `json:"DefinitionString,omitempty"` - - // RoleArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-stepfunctions-statemachine.html#cfn-stepfunctions-statemachine-rolearn - RoleArn string `json:"RoleArn,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSStepFunctionsStateMachine) AWSCloudFormationType() string { - return "AWS::StepFunctions::StateMachine" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSStepFunctionsStateMachine) MarshalJSON() ([]byte, error) { - type Properties AWSStepFunctionsStateMachine - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSStepFunctionsStateMachine) UnmarshalJSON(b []byte) error { - type Properties AWSStepFunctionsStateMachine - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSStepFunctionsStateMachine(*res.Properties) - } - - return nil -} - -// GetAllAWSStepFunctionsStateMachineResources retrieves all AWSStepFunctionsStateMachine items from an AWS CloudFormation template -func (t *Template) GetAllAWSStepFunctionsStateMachineResources() map[string]AWSStepFunctionsStateMachine { - results := map[string]AWSStepFunctionsStateMachine{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSStepFunctionsStateMachine: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::StepFunctions::StateMachine" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSStepFunctionsStateMachine - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSStepFunctionsStateMachineWithName retrieves all AWSStepFunctionsStateMachine items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSStepFunctionsStateMachineWithName(name string) (AWSStepFunctionsStateMachine, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSStepFunctionsStateMachine: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::StepFunctions::StateMachine" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSStepFunctionsStateMachine - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSStepFunctionsStateMachine{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset.go deleted file mode 100644 index fb8bb7863c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFByteMatchSet AWS CloudFormation Resource (AWS::WAF::ByteMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-bytematchset.html -type AWSWAFByteMatchSet struct { - - // ByteMatchTuples AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-bytematchset.html#cfn-waf-bytematchset-bytematchtuples - ByteMatchTuples []AWSWAFByteMatchSet_ByteMatchTuple `json:"ByteMatchTuples,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-bytematchset.html#cfn-waf-bytematchset-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFByteMatchSet) AWSCloudFormationType() string { - return "AWS::WAF::ByteMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFByteMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFByteMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFByteMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFByteMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFByteMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFByteMatchSetResources retrieves all AWSWAFByteMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFByteMatchSetResources() map[string]AWSWAFByteMatchSet { - results := map[string]AWSWAFByteMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFByteMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::ByteMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFByteMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFByteMatchSetWithName retrieves all AWSWAFByteMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFByteMatchSetWithName(name string) (AWSWAFByteMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFByteMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::ByteMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFByteMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFByteMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_bytematchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_bytematchtuple.go deleted file mode 100644 index 2c747d2d77..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_bytematchtuple.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSWAFByteMatchSet_ByteMatchTuple AWS CloudFormation Resource (AWS::WAF::ByteMatchSet.ByteMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html -type AWSWAFByteMatchSet_ByteMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html#cfn-waf-bytematchset-bytematchtuples-fieldtomatch - FieldToMatch *AWSWAFByteMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // PositionalConstraint AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html#cfn-waf-bytematchset-bytematchtuples-positionalconstraint - PositionalConstraint string `json:"PositionalConstraint,omitempty"` - - // TargetString AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html#cfn-waf-bytematchset-bytematchtuples-targetstring - TargetString string `json:"TargetString,omitempty"` - - // TargetStringBase64 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html#cfn-waf-bytematchset-bytematchtuples-targetstringbase64 - TargetStringBase64 string `json:"TargetStringBase64,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples.html#cfn-waf-bytematchset-bytematchtuples-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFByteMatchSet_ByteMatchTuple) AWSCloudFormationType() string { - return "AWS::WAF::ByteMatchSet.ByteMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_fieldtomatch.go deleted file mode 100644 index 7987f32145..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-bytematchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFByteMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAF::ByteMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html -type AWSWAFByteMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-bytematchset-bytematchtuples-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-bytematchset-bytematchtuples-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFByteMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAF::ByteMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset.go deleted file mode 100644 index 9dc7acff1a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFIPSet AWS CloudFormation Resource (AWS::WAF::IPSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-ipset.html -type AWSWAFIPSet struct { - - // IPSetDescriptors AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-ipset.html#cfn-waf-ipset-ipsetdescriptors - IPSetDescriptors []AWSWAFIPSet_IPSetDescriptor `json:"IPSetDescriptors,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-ipset.html#cfn-waf-ipset-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFIPSet) AWSCloudFormationType() string { - return "AWS::WAF::IPSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFIPSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFIPSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFIPSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFIPSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFIPSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFIPSetResources retrieves all AWSWAFIPSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFIPSetResources() map[string]AWSWAFIPSet { - results := map[string]AWSWAFIPSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFIPSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::IPSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFIPSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFIPSetWithName retrieves all AWSWAFIPSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFIPSetWithName(name string) (AWSWAFIPSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFIPSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::IPSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFIPSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFIPSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset_ipsetdescriptor.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset_ipsetdescriptor.go deleted file mode 100644 index 1f189285bd..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-ipset_ipsetdescriptor.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFIPSet_IPSetDescriptor AWS CloudFormation Resource (AWS::WAF::IPSet.IPSetDescriptor) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-ipset-ipsetdescriptors.html -type AWSWAFIPSet_IPSetDescriptor struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-ipset-ipsetdescriptors.html#cfn-waf-ipset-ipsetdescriptors-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-ipset-ipsetdescriptors.html#cfn-waf-ipset-ipsetdescriptors-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFIPSet_IPSetDescriptor) AWSCloudFormationType() string { - return "AWS::WAF::IPSet.IPSetDescriptor" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule.go deleted file mode 100644 index 37cb430d46..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRule AWS CloudFormation Resource (AWS::WAF::Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-rule.html -type AWSWAFRule struct { - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-rule.html#cfn-waf-rule-metricname - MetricName string `json:"MetricName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-rule.html#cfn-waf-rule-name - Name string `json:"Name,omitempty"` - - // Predicates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-rule.html#cfn-waf-rule-predicates - Predicates []AWSWAFRule_Predicate `json:"Predicates,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRule) AWSCloudFormationType() string { - return "AWS::WAF::Rule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRule) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRule) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRule(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRuleResources retrieves all AWSWAFRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRuleResources() map[string]AWSWAFRule { - results := map[string]AWSWAFRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRuleWithName retrieves all AWSWAFRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRuleWithName(name string) (AWSWAFRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule_predicate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule_predicate.go deleted file mode 100644 index eb2971954c..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-rule_predicate.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSWAFRule_Predicate AWS CloudFormation Resource (AWS::WAF::Rule.Predicate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-rule-predicates.html -type AWSWAFRule_Predicate struct { - - // DataId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-rule-predicates.html#cfn-waf-rule-predicates-dataid - DataId string `json:"DataId,omitempty"` - - // Negated AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-rule-predicates.html#cfn-waf-rule-predicates-negated - Negated bool `json:"Negated,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-rule-predicates.html#cfn-waf-rule-predicates-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRule_Predicate) AWSCloudFormationType() string { - return "AWS::WAF::Rule.Predicate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset.go deleted file mode 100644 index 46b2372bca..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFSizeConstraintSet AWS CloudFormation Resource (AWS::WAF::SizeConstraintSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sizeconstraintset.html -type AWSWAFSizeConstraintSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sizeconstraintset.html#cfn-waf-sizeconstraintset-name - Name string `json:"Name,omitempty"` - - // SizeConstraints AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sizeconstraintset.html#cfn-waf-sizeconstraintset-sizeconstraints - SizeConstraints []AWSWAFSizeConstraintSet_SizeConstraint `json:"SizeConstraints,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSizeConstraintSet) AWSCloudFormationType() string { - return "AWS::WAF::SizeConstraintSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFSizeConstraintSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFSizeConstraintSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFSizeConstraintSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFSizeConstraintSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFSizeConstraintSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFSizeConstraintSetResources retrieves all AWSWAFSizeConstraintSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFSizeConstraintSetResources() map[string]AWSWAFSizeConstraintSet { - results := map[string]AWSWAFSizeConstraintSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFSizeConstraintSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::SizeConstraintSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFSizeConstraintSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFSizeConstraintSetWithName retrieves all AWSWAFSizeConstraintSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFSizeConstraintSetWithName(name string) (AWSWAFSizeConstraintSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFSizeConstraintSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::SizeConstraintSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFSizeConstraintSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFSizeConstraintSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_fieldtomatch.go deleted file mode 100644 index 0f617ee354..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFSizeConstraintSet_FieldToMatch AWS CloudFormation Resource (AWS::WAF::SizeConstraintSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint-fieldtomatch.html -type AWSWAFSizeConstraintSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint-fieldtomatch.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint-fieldtomatch.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSizeConstraintSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAF::SizeConstraintSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_sizeconstraint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_sizeconstraint.go deleted file mode 100644 index f93dfa9a58..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sizeconstraintset_sizeconstraint.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSWAFSizeConstraintSet_SizeConstraint AWS CloudFormation Resource (AWS::WAF::SizeConstraintSet.SizeConstraint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html -type AWSWAFSizeConstraintSet_SizeConstraint struct { - - // ComparisonOperator AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-comparisonoperator - ComparisonOperator string `json:"ComparisonOperator,omitempty"` - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch - FieldToMatch *AWSWAFSizeConstraintSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // Size AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-size - Size int `json:"Size,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sizeconstraintset-sizeconstraint.html#cfn-waf-sizeconstraintset-sizeconstraint-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSizeConstraintSet_SizeConstraint) AWSCloudFormationType() string { - return "AWS::WAF::SizeConstraintSet.SizeConstraint" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset.go deleted file mode 100644 index 1288c3b7e6..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFSqlInjectionMatchSet AWS CloudFormation Resource (AWS::WAF::SqlInjectionMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html -type AWSWAFSqlInjectionMatchSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html#cfn-waf-sqlinjectionmatchset-name - Name string `json:"Name,omitempty"` - - // SqlInjectionMatchTuples AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-sqlinjectionmatchset.html#cfn-waf-sqlinjectionmatchset-sqlinjectionmatchtuples - SqlInjectionMatchTuples []AWSWAFSqlInjectionMatchSet_SqlInjectionMatchTuple `json:"SqlInjectionMatchTuples,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSqlInjectionMatchSet) AWSCloudFormationType() string { - return "AWS::WAF::SqlInjectionMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFSqlInjectionMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFSqlInjectionMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFSqlInjectionMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFSqlInjectionMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFSqlInjectionMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFSqlInjectionMatchSetResources retrieves all AWSWAFSqlInjectionMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFSqlInjectionMatchSetResources() map[string]AWSWAFSqlInjectionMatchSet { - results := map[string]AWSWAFSqlInjectionMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFSqlInjectionMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::SqlInjectionMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFSqlInjectionMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFSqlInjectionMatchSetWithName retrieves all AWSWAFSqlInjectionMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFSqlInjectionMatchSetWithName(name string) (AWSWAFSqlInjectionMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFSqlInjectionMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::SqlInjectionMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFSqlInjectionMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFSqlInjectionMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_fieldtomatch.go deleted file mode 100644 index 7e6c0684ac..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFSqlInjectionMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAF::SqlInjectionMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html -type AWSWAFSqlInjectionMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-bytematchset-bytematchtuples-fieldtomatch.html#cfn-waf-sizeconstraintset-sizeconstraint-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSqlInjectionMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAF::SqlInjectionMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_sqlinjectionmatchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_sqlinjectionmatchtuple.go deleted file mode 100644 index 12c25c85db..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-sqlinjectionmatchset_sqlinjectionmatchtuple.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFSqlInjectionMatchSet_SqlInjectionMatchTuple AWS CloudFormation Resource (AWS::WAF::SqlInjectionMatchSet.SqlInjectionMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sqlinjectionmatchset-sqlinjectionmatchtuples.html -type AWSWAFSqlInjectionMatchSet_SqlInjectionMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sqlinjectionmatchset-sqlinjectionmatchtuples.html#cfn-waf-sqlinjectionmatchset-sqlinjectionmatchtuples-fieldtomatch - FieldToMatch *AWSWAFSqlInjectionMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-sqlinjectionmatchset-sqlinjectionmatchtuples.html#cfn-waf-sqlinjectionmatchset-sqlinjectionmatchtuples-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFSqlInjectionMatchSet_SqlInjectionMatchTuple) AWSCloudFormationType() string { - return "AWS::WAF::SqlInjectionMatchSet.SqlInjectionMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl.go deleted file mode 100644 index 8f6939ce2e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFWebACL AWS CloudFormation Resource (AWS::WAF::WebACL) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-webacl.html -type AWSWAFWebACL struct { - - // DefaultAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-webacl.html#cfn-waf-webacl-defaultaction - DefaultAction *AWSWAFWebACL_WafAction `json:"DefaultAction,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-webacl.html#cfn-waf-webacl-metricname - MetricName string `json:"MetricName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-webacl.html#cfn-waf-webacl-name - Name string `json:"Name,omitempty"` - - // Rules AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-webacl.html#cfn-waf-webacl-rules - Rules []AWSWAFWebACL_ActivatedRule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFWebACL) AWSCloudFormationType() string { - return "AWS::WAF::WebACL" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFWebACL) MarshalJSON() ([]byte, error) { - type Properties AWSWAFWebACL - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFWebACL) UnmarshalJSON(b []byte) error { - type Properties AWSWAFWebACL - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFWebACL(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFWebACLResources retrieves all AWSWAFWebACL items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFWebACLResources() map[string]AWSWAFWebACL { - results := map[string]AWSWAFWebACL{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFWebACL: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::WebACL" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFWebACL - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFWebACLWithName retrieves all AWSWAFWebACL items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFWebACLWithName(name string) (AWSWAFWebACL, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFWebACL: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::WebACL" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFWebACL - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFWebACL{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_activatedrule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_activatedrule.go deleted file mode 100644 index f5991eaa11..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_activatedrule.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSWAFWebACL_ActivatedRule AWS CloudFormation Resource (AWS::WAF::WebACL.ActivatedRule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-rules.html -type AWSWAFWebACL_ActivatedRule struct { - - // Action AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-rules.html#cfn-waf-webacl-rules-action - Action *AWSWAFWebACL_WafAction `json:"Action,omitempty"` - - // Priority AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-rules.html#cfn-waf-webacl-rules-priority - Priority int `json:"Priority,omitempty"` - - // RuleId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-rules.html#cfn-waf-webacl-rules-ruleid - RuleId string `json:"RuleId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFWebACL_ActivatedRule) AWSCloudFormationType() string { - return "AWS::WAF::WebACL.ActivatedRule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_wafaction.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_wafaction.go deleted file mode 100644 index aeca85a5b4..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-webacl_wafaction.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSWAFWebACL_WafAction AWS CloudFormation Resource (AWS::WAF::WebACL.WafAction) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-action.html -type AWSWAFWebACL_WafAction struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-webacl-action.html#cfn-waf-webacl-action-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFWebACL_WafAction) AWSCloudFormationType() string { - return "AWS::WAF::WebACL.WafAction" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset.go deleted file mode 100644 index ec2aee4d2b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFXssMatchSet AWS CloudFormation Resource (AWS::WAF::XssMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-xssmatchset.html -type AWSWAFXssMatchSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-xssmatchset.html#cfn-waf-xssmatchset-name - Name string `json:"Name,omitempty"` - - // XssMatchTuples AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-waf-xssmatchset.html#cfn-waf-xssmatchset-xssmatchtuples - XssMatchTuples []AWSWAFXssMatchSet_XssMatchTuple `json:"XssMatchTuples,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFXssMatchSet) AWSCloudFormationType() string { - return "AWS::WAF::XssMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFXssMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFXssMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFXssMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFXssMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFXssMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFXssMatchSetResources retrieves all AWSWAFXssMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFXssMatchSetResources() map[string]AWSWAFXssMatchSet { - results := map[string]AWSWAFXssMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFXssMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::XssMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFXssMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFXssMatchSetWithName retrieves all AWSWAFXssMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFXssMatchSetWithName(name string) (AWSWAFXssMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFXssMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAF::XssMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFXssMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFXssMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_fieldtomatch.go deleted file mode 100644 index 1fbdd0fc7a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFXssMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAF::XssMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple-fieldtomatch.html -type AWSWAFXssMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple-fieldtomatch.html#cfn-waf-xssmatchset-xssmatchtuple-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple-fieldtomatch.html#cfn-waf-xssmatchset-xssmatchtuple-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFXssMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAF::XssMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_xssmatchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_xssmatchtuple.go deleted file mode 100644 index 3f700d0dbf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-waf-xssmatchset_xssmatchtuple.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFXssMatchSet_XssMatchTuple AWS CloudFormation Resource (AWS::WAF::XssMatchSet.XssMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple.html -type AWSWAFXssMatchSet_XssMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple.html#cfn-waf-xssmatchset-xssmatchtuple-fieldtomatch - FieldToMatch *AWSWAFXssMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-waf-xssmatchset-xssmatchtuple.html#cfn-waf-xssmatchset-xssmatchtuple-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFXssMatchSet_XssMatchTuple) AWSCloudFormationType() string { - return "AWS::WAF::XssMatchSet.XssMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset.go deleted file mode 100644 index 44c33e2de2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalByteMatchSet AWS CloudFormation Resource (AWS::WAFRegional::ByteMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-bytematchset.html -type AWSWAFRegionalByteMatchSet struct { - - // ByteMatchTuples AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-bytematchset.html#cfn-wafregional-bytematchset-bytematchtuples - ByteMatchTuples []AWSWAFRegionalByteMatchSet_ByteMatchTuple `json:"ByteMatchTuples,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-bytematchset.html#cfn-wafregional-bytematchset-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalByteMatchSet) AWSCloudFormationType() string { - return "AWS::WAFRegional::ByteMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalByteMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalByteMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalByteMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalByteMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalByteMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalByteMatchSetResources retrieves all AWSWAFRegionalByteMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalByteMatchSetResources() map[string]AWSWAFRegionalByteMatchSet { - results := map[string]AWSWAFRegionalByteMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalByteMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::ByteMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalByteMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalByteMatchSetWithName retrieves all AWSWAFRegionalByteMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalByteMatchSetWithName(name string) (AWSWAFRegionalByteMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalByteMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::ByteMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalByteMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalByteMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_bytematchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_bytematchtuple.go deleted file mode 100644 index b25c0a599b..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_bytematchtuple.go +++ /dev/null @@ -1,36 +0,0 @@ -package cloudformation - -// AWSWAFRegionalByteMatchSet_ByteMatchTuple AWS CloudFormation Resource (AWS::WAFRegional::ByteMatchSet.ByteMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html -type AWSWAFRegionalByteMatchSet_ByteMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html#cfn-wafregional-bytematchset-bytematchtuple-fieldtomatch - FieldToMatch *AWSWAFRegionalByteMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // PositionalConstraint AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html#cfn-wafregional-bytematchset-bytematchtuple-positionalconstraint - PositionalConstraint string `json:"PositionalConstraint,omitempty"` - - // TargetString AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html#cfn-wafregional-bytematchset-bytematchtuple-targetstring - TargetString string `json:"TargetString,omitempty"` - - // TargetStringBase64 AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html#cfn-wafregional-bytematchset-bytematchtuple-targetstringbase64 - TargetStringBase64 string `json:"TargetStringBase64,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-bytematchtuple.html#cfn-wafregional-bytematchset-bytematchtuple-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalByteMatchSet_ByteMatchTuple) AWSCloudFormationType() string { - return "AWS::WAFRegional::ByteMatchSet.ByteMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_fieldtomatch.go deleted file mode 100644 index 4d4a24cadf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-bytematchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalByteMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAFRegional::ByteMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html -type AWSWAFRegionalByteMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html#cfn-wafregional-bytematchset-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-bytematchset-fieldtomatch.html#cfn-wafregional-bytematchset-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalByteMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAFRegional::ByteMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset.go deleted file mode 100644 index 45b2fa7772..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalIPSet AWS CloudFormation Resource (AWS::WAFRegional::IPSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html -type AWSWAFRegionalIPSet struct { - - // IPSetDescriptors AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-ipsetdescriptors - IPSetDescriptors []AWSWAFRegionalIPSet_IPSetDescriptor `json:"IPSetDescriptors,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-ipset.html#cfn-wafregional-ipset-name - Name string `json:"Name,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalIPSet) AWSCloudFormationType() string { - return "AWS::WAFRegional::IPSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalIPSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalIPSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalIPSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalIPSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalIPSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalIPSetResources retrieves all AWSWAFRegionalIPSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalIPSetResources() map[string]AWSWAFRegionalIPSet { - results := map[string]AWSWAFRegionalIPSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalIPSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::IPSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalIPSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalIPSetWithName retrieves all AWSWAFRegionalIPSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalIPSetWithName(name string) (AWSWAFRegionalIPSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalIPSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::IPSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalIPSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalIPSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset_ipsetdescriptor.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset_ipsetdescriptor.go deleted file mode 100644 index 6f5af5fe8e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-ipset_ipsetdescriptor.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalIPSet_IPSetDescriptor AWS CloudFormation Resource (AWS::WAFRegional::IPSet.IPSetDescriptor) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-ipset-ipsetdescriptor.html -type AWSWAFRegionalIPSet_IPSetDescriptor struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-ipset-ipsetdescriptor.html#cfn-wafregional-ipset-ipsetdescriptor-type - Type string `json:"Type,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-ipset-ipsetdescriptor.html#cfn-wafregional-ipset-ipsetdescriptor-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalIPSet_IPSetDescriptor) AWSCloudFormationType() string { - return "AWS::WAFRegional::IPSet.IPSetDescriptor" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule.go deleted file mode 100644 index a1059d4330..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule.go +++ /dev/null @@ -1,120 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalRule AWS CloudFormation Resource (AWS::WAFRegional::Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-rule.html -type AWSWAFRegionalRule struct { - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-rule.html#cfn-wafregional-rule-metricname - MetricName string `json:"MetricName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-rule.html#cfn-wafregional-rule-name - Name string `json:"Name,omitempty"` - - // Predicates AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-rule.html#cfn-wafregional-rule-predicates - Predicates []AWSWAFRegionalRule_Predicate `json:"Predicates,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalRule) AWSCloudFormationType() string { - return "AWS::WAFRegional::Rule" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalRule) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalRule - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalRule) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalRule - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalRule(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalRuleResources retrieves all AWSWAFRegionalRule items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalRuleResources() map[string]AWSWAFRegionalRule { - results := map[string]AWSWAFRegionalRule{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalRule: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalRule - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalRuleWithName retrieves all AWSWAFRegionalRule items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalRuleWithName(name string) (AWSWAFRegionalRule, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalRule: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::Rule" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalRule - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalRule{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule_predicate.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule_predicate.go deleted file mode 100644 index 5fbbb7d0bf..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-rule_predicate.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSWAFRegionalRule_Predicate AWS CloudFormation Resource (AWS::WAFRegional::Rule.Predicate) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-rule-predicate.html -type AWSWAFRegionalRule_Predicate struct { - - // DataId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-rule-predicate.html#cfn-wafregional-rule-predicate-dataid - DataId string `json:"DataId,omitempty"` - - // Negated AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-rule-predicate.html#cfn-wafregional-rule-predicate-negated - Negated bool `json:"Negated,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-rule-predicate.html#cfn-wafregional-rule-predicate-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalRule_Predicate) AWSCloudFormationType() string { - return "AWS::WAFRegional::Rule.Predicate" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset.go deleted file mode 100644 index 9ed5efc9c2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalSizeConstraintSet AWS CloudFormation Resource (AWS::WAFRegional::SizeConstraintSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sizeconstraintset.html -type AWSWAFRegionalSizeConstraintSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sizeconstraintset.html#cfn-wafregional-sizeconstraintset-name - Name string `json:"Name,omitempty"` - - // SizeConstraints AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sizeconstraintset.html#cfn-wafregional-sizeconstraintset-sizeconstraints - SizeConstraints []AWSWAFRegionalSizeConstraintSet_SizeConstraint `json:"SizeConstraints,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSizeConstraintSet) AWSCloudFormationType() string { - return "AWS::WAFRegional::SizeConstraintSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalSizeConstraintSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalSizeConstraintSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalSizeConstraintSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalSizeConstraintSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalSizeConstraintSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalSizeConstraintSetResources retrieves all AWSWAFRegionalSizeConstraintSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalSizeConstraintSetResources() map[string]AWSWAFRegionalSizeConstraintSet { - results := map[string]AWSWAFRegionalSizeConstraintSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalSizeConstraintSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::SizeConstraintSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalSizeConstraintSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalSizeConstraintSetWithName retrieves all AWSWAFRegionalSizeConstraintSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalSizeConstraintSetWithName(name string) (AWSWAFRegionalSizeConstraintSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalSizeConstraintSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::SizeConstraintSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalSizeConstraintSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalSizeConstraintSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_fieldtomatch.go deleted file mode 100644 index 20729592b8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalSizeConstraintSet_FieldToMatch AWS CloudFormation Resource (AWS::WAFRegional::SizeConstraintSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-fieldtomatch.html -type AWSWAFRegionalSizeConstraintSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-fieldtomatch.html#cfn-wafregional-sizeconstraintset-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-fieldtomatch.html#cfn-wafregional-sizeconstraintset-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSizeConstraintSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAFRegional::SizeConstraintSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_sizeconstraint.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_sizeconstraint.go deleted file mode 100644 index db8499675a..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sizeconstraintset_sizeconstraint.go +++ /dev/null @@ -1,31 +0,0 @@ -package cloudformation - -// AWSWAFRegionalSizeConstraintSet_SizeConstraint AWS CloudFormation Resource (AWS::WAFRegional::SizeConstraintSet.SizeConstraint) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html -type AWSWAFRegionalSizeConstraintSet_SizeConstraint struct { - - // ComparisonOperator AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-comparisonoperator - ComparisonOperator string `json:"ComparisonOperator,omitempty"` - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-fieldtomatch - FieldToMatch *AWSWAFRegionalSizeConstraintSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // Size AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-size - Size int `json:"Size,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sizeconstraintset-sizeconstraint.html#cfn-wafregional-sizeconstraintset-sizeconstraint-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSizeConstraintSet_SizeConstraint) AWSCloudFormationType() string { - return "AWS::WAFRegional::SizeConstraintSet.SizeConstraint" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset.go deleted file mode 100644 index 171efd8e38..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalSqlInjectionMatchSet AWS CloudFormation Resource (AWS::WAFRegional::SqlInjectionMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sqlinjectionmatchset.html -type AWSWAFRegionalSqlInjectionMatchSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sqlinjectionmatchset.html#cfn-wafregional-sqlinjectionmatchset-name - Name string `json:"Name,omitempty"` - - // SqlInjectionMatchTuples AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-sqlinjectionmatchset.html#cfn-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuples - SqlInjectionMatchTuples []AWSWAFRegionalSqlInjectionMatchSet_SqlInjectionMatchTuple `json:"SqlInjectionMatchTuples,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSqlInjectionMatchSet) AWSCloudFormationType() string { - return "AWS::WAFRegional::SqlInjectionMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalSqlInjectionMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalSqlInjectionMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalSqlInjectionMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalSqlInjectionMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalSqlInjectionMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalSqlInjectionMatchSetResources retrieves all AWSWAFRegionalSqlInjectionMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalSqlInjectionMatchSetResources() map[string]AWSWAFRegionalSqlInjectionMatchSet { - results := map[string]AWSWAFRegionalSqlInjectionMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalSqlInjectionMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::SqlInjectionMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalSqlInjectionMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalSqlInjectionMatchSetWithName retrieves all AWSWAFRegionalSqlInjectionMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalSqlInjectionMatchSetWithName(name string) (AWSWAFRegionalSqlInjectionMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalSqlInjectionMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::SqlInjectionMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalSqlInjectionMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalSqlInjectionMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_fieldtomatch.go deleted file mode 100644 index c36884f72f..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalSqlInjectionMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAFRegional::SqlInjectionMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html -type AWSWAFRegionalSqlInjectionMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html#cfn-wafregional-sqlinjectionmatchset-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-fieldtomatch.html#cfn-wafregional-sqlinjectionmatchset-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSqlInjectionMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAFRegional::SqlInjectionMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_sqlinjectionmatchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_sqlinjectionmatchtuple.go deleted file mode 100644 index 45cda15a94..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-sqlinjectionmatchset_sqlinjectionmatchtuple.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalSqlInjectionMatchSet_SqlInjectionMatchTuple AWS CloudFormation Resource (AWS::WAFRegional::SqlInjectionMatchSet.SqlInjectionMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuple.html -type AWSWAFRegionalSqlInjectionMatchSet_SqlInjectionMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuple.html#cfn-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuple-fieldtomatch - FieldToMatch *AWSWAFRegionalSqlInjectionMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuple.html#cfn-wafregional-sqlinjectionmatchset-sqlinjectionmatchtuple-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalSqlInjectionMatchSet_SqlInjectionMatchTuple) AWSCloudFormationType() string { - return "AWS::WAFRegional::SqlInjectionMatchSet.SqlInjectionMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl.go deleted file mode 100644 index aebee7e2a7..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalWebACL AWS CloudFormation Resource (AWS::WAFRegional::WebACL) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html -type AWSWAFRegionalWebACL struct { - - // DefaultAction AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html#cfn-wafregional-webacl-defaultaction - DefaultAction *AWSWAFRegionalWebACL_Action `json:"DefaultAction,omitempty"` - - // MetricName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html#cfn-wafregional-webacl-metricname - MetricName string `json:"MetricName,omitempty"` - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html#cfn-wafregional-webacl-name - Name string `json:"Name,omitempty"` - - // Rules AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webacl.html#cfn-wafregional-webacl-rules - Rules []AWSWAFRegionalWebACL_Rule `json:"Rules,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalWebACL) AWSCloudFormationType() string { - return "AWS::WAFRegional::WebACL" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalWebACL) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalWebACL - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalWebACL) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalWebACL - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalWebACL(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalWebACLResources retrieves all AWSWAFRegionalWebACL items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalWebACLResources() map[string]AWSWAFRegionalWebACL { - results := map[string]AWSWAFRegionalWebACL{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalWebACL: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::WebACL" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalWebACL - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalWebACLWithName retrieves all AWSWAFRegionalWebACL items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalWebACLWithName(name string) (AWSWAFRegionalWebACL, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalWebACL: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::WebACL" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalWebACL - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalWebACL{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_action.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_action.go deleted file mode 100644 index c801f9c432..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_action.go +++ /dev/null @@ -1,16 +0,0 @@ -package cloudformation - -// AWSWAFRegionalWebACL_Action AWS CloudFormation Resource (AWS::WAFRegional::WebACL.Action) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html -type AWSWAFRegionalWebACL_Action struct { - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-action.html#cfn-wafregional-webacl-action-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalWebACL_Action) AWSCloudFormationType() string { - return "AWS::WAFRegional::WebACL.Action" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_rule.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_rule.go deleted file mode 100644 index ca2056942e..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webacl_rule.go +++ /dev/null @@ -1,26 +0,0 @@ -package cloudformation - -// AWSWAFRegionalWebACL_Rule AWS CloudFormation Resource (AWS::WAFRegional::WebACL.Rule) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html -type AWSWAFRegionalWebACL_Rule struct { - - // Action AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-action - Action *AWSWAFRegionalWebACL_Action `json:"Action,omitempty"` - - // Priority AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-priority - Priority int `json:"Priority,omitempty"` - - // RuleId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-webacl-rule.html#cfn-wafregional-webacl-rule-ruleid - RuleId string `json:"RuleId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalWebACL_Rule) AWSCloudFormationType() string { - return "AWS::WAFRegional::WebACL.Rule" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webaclassociation.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webaclassociation.go deleted file mode 100644 index 3c4ce87848..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-webaclassociation.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalWebACLAssociation AWS CloudFormation Resource (AWS::WAFRegional::WebACLAssociation) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webaclassociation.html -type AWSWAFRegionalWebACLAssociation struct { - - // ResourceArn AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webaclassociation.html#cfn-wafregional-webaclassociation-resourcearn - ResourceArn string `json:"ResourceArn,omitempty"` - - // WebACLId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-webaclassociation.html#cfn-wafregional-webaclassociation-webaclid - WebACLId string `json:"WebACLId,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalWebACLAssociation) AWSCloudFormationType() string { - return "AWS::WAFRegional::WebACLAssociation" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalWebACLAssociation) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalWebACLAssociation - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalWebACLAssociation) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalWebACLAssociation - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalWebACLAssociation(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalWebACLAssociationResources retrieves all AWSWAFRegionalWebACLAssociation items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalWebACLAssociationResources() map[string]AWSWAFRegionalWebACLAssociation { - results := map[string]AWSWAFRegionalWebACLAssociation{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalWebACLAssociation: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::WebACLAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalWebACLAssociation - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalWebACLAssociationWithName retrieves all AWSWAFRegionalWebACLAssociation items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalWebACLAssociationWithName(name string) (AWSWAFRegionalWebACLAssociation, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalWebACLAssociation: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::WebACLAssociation" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalWebACLAssociation - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalWebACLAssociation{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset.go deleted file mode 100644 index 2e288bee11..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset.go +++ /dev/null @@ -1,115 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWAFRegionalXssMatchSet AWS CloudFormation Resource (AWS::WAFRegional::XssMatchSet) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-xssmatchset.html -type AWSWAFRegionalXssMatchSet struct { - - // Name AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-xssmatchset.html#cfn-wafregional-xssmatchset-name - Name string `json:"Name,omitempty"` - - // XssMatchTuples AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-wafregional-xssmatchset.html#cfn-wafregional-xssmatchset-xssmatchtuples - XssMatchTuples []AWSWAFRegionalXssMatchSet_XssMatchTuple `json:"XssMatchTuples,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalXssMatchSet) AWSCloudFormationType() string { - return "AWS::WAFRegional::XssMatchSet" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWAFRegionalXssMatchSet) MarshalJSON() ([]byte, error) { - type Properties AWSWAFRegionalXssMatchSet - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWAFRegionalXssMatchSet) UnmarshalJSON(b []byte) error { - type Properties AWSWAFRegionalXssMatchSet - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWAFRegionalXssMatchSet(*res.Properties) - } - - return nil -} - -// GetAllAWSWAFRegionalXssMatchSetResources retrieves all AWSWAFRegionalXssMatchSet items from an AWS CloudFormation template -func (t *Template) GetAllAWSWAFRegionalXssMatchSetResources() map[string]AWSWAFRegionalXssMatchSet { - results := map[string]AWSWAFRegionalXssMatchSet{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWAFRegionalXssMatchSet: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::XssMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalXssMatchSet - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWAFRegionalXssMatchSetWithName retrieves all AWSWAFRegionalXssMatchSet items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWAFRegionalXssMatchSetWithName(name string) (AWSWAFRegionalXssMatchSet, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWAFRegionalXssMatchSet: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WAFRegional::XssMatchSet" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWAFRegionalXssMatchSet - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWAFRegionalXssMatchSet{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_fieldtomatch.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_fieldtomatch.go deleted file mode 100644 index 4cdb38e100..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_fieldtomatch.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalXssMatchSet_FieldToMatch AWS CloudFormation Resource (AWS::WAFRegional::XssMatchSet.FieldToMatch) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-fieldtomatch.html -type AWSWAFRegionalXssMatchSet_FieldToMatch struct { - - // Data AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-fieldtomatch.html#cfn-wafregional-xssmatchset-fieldtomatch-data - Data string `json:"Data,omitempty"` - - // Type AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-fieldtomatch.html#cfn-wafregional-xssmatchset-fieldtomatch-type - Type string `json:"Type,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalXssMatchSet_FieldToMatch) AWSCloudFormationType() string { - return "AWS::WAFRegional::XssMatchSet.FieldToMatch" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_xssmatchtuple.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_xssmatchtuple.go deleted file mode 100644 index 85fe6ef553..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-wafregional-xssmatchset_xssmatchtuple.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// AWSWAFRegionalXssMatchSet_XssMatchTuple AWS CloudFormation Resource (AWS::WAFRegional::XssMatchSet.XssMatchTuple) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-xssmatchtuple.html -type AWSWAFRegionalXssMatchSet_XssMatchTuple struct { - - // FieldToMatch AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-xssmatchtuple.html#cfn-wafregional-xssmatchset-xssmatchtuple-fieldtomatch - FieldToMatch *AWSWAFRegionalXssMatchSet_FieldToMatch `json:"FieldToMatch,omitempty"` - - // TextTransformation AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-wafregional-xssmatchset-xssmatchtuple.html#cfn-wafregional-xssmatchset-xssmatchtuple-texttransformation - TextTransformation string `json:"TextTransformation,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWAFRegionalXssMatchSet_XssMatchTuple) AWSCloudFormationType() string { - return "AWS::WAFRegional::XssMatchSet.XssMatchTuple" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/aws-workspaces-workspace.go b/vendor/github.com/awslabs/goformation/cloudformation/aws-workspaces-workspace.go deleted file mode 100644 index 1f0f8d5892..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/aws-workspaces-workspace.go +++ /dev/null @@ -1,135 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - "errors" - "fmt" -) - -// AWSWorkSpacesWorkspace AWS CloudFormation Resource (AWS::WorkSpaces::Workspace) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html -type AWSWorkSpacesWorkspace struct { - - // BundleId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-bundleid - BundleId string `json:"BundleId,omitempty"` - - // DirectoryId AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-directoryid - DirectoryId string `json:"DirectoryId,omitempty"` - - // RootVolumeEncryptionEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-rootvolumeencryptionenabled - RootVolumeEncryptionEnabled bool `json:"RootVolumeEncryptionEnabled,omitempty"` - - // UserName AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-username - UserName string `json:"UserName,omitempty"` - - // UserVolumeEncryptionEnabled AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-uservolumeencryptionenabled - UserVolumeEncryptionEnabled bool `json:"UserVolumeEncryptionEnabled,omitempty"` - - // VolumeEncryptionKey AWS CloudFormation Property - // Required: false - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-workspaces-workspace.html#cfn-workspaces-workspace-volumeencryptionkey - VolumeEncryptionKey string `json:"VolumeEncryptionKey,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *AWSWorkSpacesWorkspace) AWSCloudFormationType() string { - return "AWS::WorkSpaces::Workspace" -} - -// MarshalJSON is a custom JSON marshalling hook that embeds this object into -// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'. -func (r *AWSWorkSpacesWorkspace) MarshalJSON() ([]byte, error) { - type Properties AWSWorkSpacesWorkspace - return json.Marshal(&struct { - Type string - Properties Properties - }{ - Type: r.AWSCloudFormationType(), - Properties: (Properties)(*r), - }) -} - -// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer -// AWS CloudFormation resource object, and just keeps the 'Properties' field. -func (r *AWSWorkSpacesWorkspace) UnmarshalJSON(b []byte) error { - type Properties AWSWorkSpacesWorkspace - res := &struct { - Type string - Properties *Properties - }{} - if err := json.Unmarshal(b, &res); err != nil { - fmt.Printf("ERROR: %s\n", err) - return err - } - - // If the resource has no Properties set, it could be nil - if res.Properties != nil { - *r = AWSWorkSpacesWorkspace(*res.Properties) - } - - return nil -} - -// GetAllAWSWorkSpacesWorkspaceResources retrieves all AWSWorkSpacesWorkspace items from an AWS CloudFormation template -func (t *Template) GetAllAWSWorkSpacesWorkspaceResources() map[string]AWSWorkSpacesWorkspace { - results := map[string]AWSWorkSpacesWorkspace{} - for name, untyped := range t.Resources { - switch resource := untyped.(type) { - case AWSWorkSpacesWorkspace: - // We found a strongly typed resource of the correct type; use it - results[name] = resource - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WorkSpaces::Workspace" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWorkSpacesWorkspace - if err := json.Unmarshal(b, &result); err == nil { - results[name] = result - } - } - } - } - } - } - return results -} - -// GetAWSWorkSpacesWorkspaceWithName retrieves all AWSWorkSpacesWorkspace items from an AWS CloudFormation template -// whose logical ID matches the provided name. Returns an error if not found. -func (t *Template) GetAWSWorkSpacesWorkspaceWithName(name string) (AWSWorkSpacesWorkspace, error) { - if untyped, ok := t.Resources[name]; ok { - switch resource := untyped.(type) { - case AWSWorkSpacesWorkspace: - // We found a strongly typed resource of the correct type; use it - return resource, nil - case map[string]interface{}: - // We found an untyped resource (likely from JSON) which *might* be - // the correct type, but we need to check it's 'Type' field - if resType, ok := resource["Type"]; ok { - if resType == "AWS::WorkSpaces::Workspace" { - // The resource is correct, unmarshal it into the results - if b, err := json.Marshal(resource); err == nil { - var result AWSWorkSpacesWorkspace - if err := json.Unmarshal(b, &result); err == nil { - return result, nil - } - } - } - } - } - } - return AWSWorkSpacesWorkspace{}, errors.New("resource not found") -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessapi_definitionuri.go b/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessapi_definitionuri.go deleted file mode 100644 index 474fd70485..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessapi_definitionuri.go +++ /dev/null @@ -1,57 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/mitchellh/mapstructure" -) - -// AWSServerlessApi_DefinitionUri is a helper struct that can hold either a String or S3Location value -type AWSServerlessApi_DefinitionUri struct { - String *string - - S3Location *AWSServerlessApi_S3Location -} - -func (r AWSServerlessApi_DefinitionUri) value() interface{} { - - if r.String != nil { - return r.String - } - - if r.S3Location != nil { - return r.S3Location - } - - return nil - -} - -func (r *AWSServerlessApi_DefinitionUri) MarshalJSON() ([]byte, error) { - return json.Marshal(r.value()) -} - -// Hook into the marshaller -func (r *AWSServerlessApi_DefinitionUri) UnmarshalJSON(b []byte) error { - - // Unmarshal into interface{} to check it's type - var typecheck interface{} - if err := json.Unmarshal(b, &typecheck); err != nil { - return err - } - - switch val := typecheck.(type) { - - case string: - r.String = &val - - case map[string]interface{}: - - mapstructure.Decode(val, &r.S3Location) - - case []interface{}: - - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_codeuri.go b/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_codeuri.go deleted file mode 100644 index f522f9f4f2..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_codeuri.go +++ /dev/null @@ -1,57 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/mitchellh/mapstructure" -) - -// AWSServerlessFunction_CodeUri is a helper struct that can hold either a String or S3Location value -type AWSServerlessFunction_CodeUri struct { - String *string - - S3Location *AWSServerlessFunction_S3Location -} - -func (r AWSServerlessFunction_CodeUri) value() interface{} { - - if r.String != nil { - return r.String - } - - if r.S3Location != nil { - return r.S3Location - } - - return nil - -} - -func (r *AWSServerlessFunction_CodeUri) MarshalJSON() ([]byte, error) { - return json.Marshal(r.value()) -} - -// Hook into the marshaller -func (r *AWSServerlessFunction_CodeUri) UnmarshalJSON(b []byte) error { - - // Unmarshal into interface{} to check it's type - var typecheck interface{} - if err := json.Unmarshal(b, &typecheck); err != nil { - return err - } - - switch val := typecheck.(type) { - - case string: - r.String = &val - - case map[string]interface{}: - - mapstructure.Decode(val, &r.S3Location) - - case []interface{}: - - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_events.go b/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_events.go deleted file mode 100644 index 399d838e94..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_events.go +++ /dev/null @@ -1,60 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/mitchellh/mapstructure" -) - -// AWSServerlessFunction_Events is a helper struct that can hold either a String or String value -type AWSServerlessFunction_Events struct { - String *string - - StringArray *[]string -} - -func (r AWSServerlessFunction_Events) value() interface{} { - - if r.String != nil { - return r.String - } - - if r.StringArray != nil { - return r.StringArray - } - - return nil - -} - -func (r *AWSServerlessFunction_Events) MarshalJSON() ([]byte, error) { - return json.Marshal(r.value()) -} - -// Hook into the marshaller -func (r *AWSServerlessFunction_Events) UnmarshalJSON(b []byte) error { - - // Unmarshal into interface{} to check it's type - var typecheck interface{} - if err := json.Unmarshal(b, &typecheck); err != nil { - return err - } - - switch val := typecheck.(type) { - - case string: - r.String = &val - - case []string: - r.StringArray = &val - - case map[string]interface{}: - - case []interface{}: - - mapstructure.Decode(val, &r.StringArray) - - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_policies.go b/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_policies.go deleted file mode 100644 index 73d7b71d87..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_policies.go +++ /dev/null @@ -1,76 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/mitchellh/mapstructure" -) - -// AWSServerlessFunction_Policies is a helper struct that can hold either a String, String, IAMPolicyDocument, or IAMPolicyDocument value -type AWSServerlessFunction_Policies struct { - String *string - - StringArray *[]string - - IAMPolicyDocument *AWSServerlessFunction_IAMPolicyDocument - - IAMPolicyDocumentArray *[]AWSServerlessFunction_IAMPolicyDocument -} - -func (r AWSServerlessFunction_Policies) value() interface{} { - - if r.String != nil { - return r.String - } - - if r.StringArray != nil { - return r.StringArray - } - - if r.IAMPolicyDocument != nil { - return r.IAMPolicyDocument - } - - if r.IAMPolicyDocumentArray != nil { - return r.IAMPolicyDocumentArray - } - - return nil - -} - -func (r *AWSServerlessFunction_Policies) MarshalJSON() ([]byte, error) { - return json.Marshal(r.value()) -} - -// Hook into the marshaller -func (r *AWSServerlessFunction_Policies) UnmarshalJSON(b []byte) error { - - // Unmarshal into interface{} to check it's type - var typecheck interface{} - if err := json.Unmarshal(b, &typecheck); err != nil { - return err - } - - switch val := typecheck.(type) { - - case string: - r.String = &val - - case []string: - r.StringArray = &val - - case map[string]interface{}: - - mapstructure.Decode(val, &r.IAMPolicyDocument) - - case []interface{}: - - mapstructure.Decode(val, &r.StringArray) - - mapstructure.Decode(val, &r.IAMPolicyDocumentArray) - - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_properties.go b/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_properties.go deleted file mode 100644 index 593ac8c478..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/awsserverlessfunction_properties.go +++ /dev/null @@ -1,104 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/mitchellh/mapstructure" -) - -// AWSServerlessFunction_Properties is a helper struct that can hold either a S3Event, SNSEvent, KinesisEvent, DynamoDBEvent, ApiEvent, ScheduleEvent, CloudWatchEventEvent, IoTRuleEvent, or AlexaSkillEvent value -type AWSServerlessFunction_Properties struct { - S3Event *AWSServerlessFunction_S3Event - SNSEvent *AWSServerlessFunction_SNSEvent - KinesisEvent *AWSServerlessFunction_KinesisEvent - DynamoDBEvent *AWSServerlessFunction_DynamoDBEvent - ApiEvent *AWSServerlessFunction_ApiEvent - ScheduleEvent *AWSServerlessFunction_ScheduleEvent - CloudWatchEventEvent *AWSServerlessFunction_CloudWatchEventEvent - IoTRuleEvent *AWSServerlessFunction_IoTRuleEvent - AlexaSkillEvent *AWSServerlessFunction_AlexaSkillEvent -} - -func (r AWSServerlessFunction_Properties) value() interface{} { - - if r.S3Event != nil { - return r.S3Event - } - - if r.SNSEvent != nil { - return r.SNSEvent - } - - if r.KinesisEvent != nil { - return r.KinesisEvent - } - - if r.DynamoDBEvent != nil { - return r.DynamoDBEvent - } - - if r.ApiEvent != nil { - return r.ApiEvent - } - - if r.ScheduleEvent != nil { - return r.ScheduleEvent - } - - if r.CloudWatchEventEvent != nil { - return r.CloudWatchEventEvent - } - - if r.IoTRuleEvent != nil { - return r.IoTRuleEvent - } - - if r.AlexaSkillEvent != nil { - return r.AlexaSkillEvent - } - - return nil - -} - -func (r *AWSServerlessFunction_Properties) MarshalJSON() ([]byte, error) { - return json.Marshal(r.value()) -} - -// Hook into the marshaller -func (r *AWSServerlessFunction_Properties) UnmarshalJSON(b []byte) error { - - // Unmarshal into interface{} to check it's type - var typecheck interface{} - if err := json.Unmarshal(b, &typecheck); err != nil { - return err - } - - switch val := typecheck.(type) { - - case map[string]interface{}: - - mapstructure.Decode(val, &r.S3Event) - - mapstructure.Decode(val, &r.SNSEvent) - - mapstructure.Decode(val, &r.KinesisEvent) - - mapstructure.Decode(val, &r.DynamoDBEvent) - - mapstructure.Decode(val, &r.ApiEvent) - - mapstructure.Decode(val, &r.ScheduleEvent) - - mapstructure.Decode(val, &r.CloudWatchEventEvent) - - mapstructure.Decode(val, &r.IoTRuleEvent) - - mapstructure.Decode(val, &r.AlexaSkillEvent) - - case []interface{}: - - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/tag.go b/vendor/github.com/awslabs/goformation/cloudformation/tag.go deleted file mode 100644 index 5ea56c85c8..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/tag.go +++ /dev/null @@ -1,21 +0,0 @@ -package cloudformation - -// Tag AWS CloudFormation Resource (Tag) -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html -type Tag struct { - - // Key AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html#cfn-resource-tags-key - Key string `json:"Key,omitempty"` - - // Value AWS CloudFormation Property - // Required: true - // See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-resource-tags.html#cfn-resource-tags-value - Value string `json:"Value,omitempty"` -} - -// AWSCloudFormationType returns the AWS CloudFormation resource type -func (r *Tag) AWSCloudFormationType() string { - return "Tag" -} diff --git a/vendor/github.com/awslabs/goformation/cloudformation/template.go b/vendor/github.com/awslabs/goformation/cloudformation/template.go deleted file mode 100644 index 21e3cc0b88..0000000000 --- a/vendor/github.com/awslabs/goformation/cloudformation/template.go +++ /dev/null @@ -1,44 +0,0 @@ -package cloudformation - -import ( - "encoding/json" - - "github.com/sanathkr/yaml" -) - -// Template represents an AWS CloudFormation template -// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html -type Template struct { - AWSTemplateFormatVersion string `json:"AWSTemplateFormatVersion,omitempty"` - Description string `json:"Description,omitempty"` - Metadata map[string]interface{} `json:"Metadata,omitempty"` - Parameters map[string]interface{} `json:"Parameters,omitempty"` - Mappings map[string]interface{} `json:"Mappings,omitempty"` - Conditions map[string]interface{} `json:"Conditions,omitempty"` - Resources map[string]interface{} `json:"Resources,omitempty"` - Outputs map[string]interface{} `json:"Outputs,omitempty"` -} - -// NewTemplate creates a new AWS CloudFormation template struct -func NewTemplate() *Template { - return &Template{ - AWSTemplateFormatVersion: "2010-09-09", - Description: "", - Metadata: map[string]interface{}{}, - Parameters: map[string]interface{}{}, - Mappings: map[string]interface{}{}, - Conditions: map[string]interface{}{}, - Resources: map[string]interface{}{}, - Outputs: map[string]interface{}{}, - } -} - -// JSON converts an AWS CloudFormation template object to JSON -func (t *Template) JSON() ([]byte, error) { - return json.Marshal(t) -} - -// YAML converts an AWS CloudFormation template object to YAML -func (t *Template) YAML() ([]byte, error) { - return yaml.Marshal(t) -} diff --git a/vendor/github.com/awslabs/goformation/goformation.go b/vendor/github.com/awslabs/goformation/goformation.go deleted file mode 100644 index 589f31ce08..0000000000 --- a/vendor/github.com/awslabs/goformation/goformation.go +++ /dev/null @@ -1,84 +0,0 @@ -package goformation - -import ( - "encoding/json" - "io/ioutil" - "strings" - - "github.com/awslabs/goformation/cloudformation" - "github.com/awslabs/goformation/intrinsics" -) - -//go:generate generate/generate.sh - -// Open and parse a AWS CloudFormation template from file. -// Works with either JSON or YAML formatted templates. -func Open(filename string) (*cloudformation.Template, error) { - return OpenWithOptions(filename, nil) -} - -// OpenWithOptions opens and parse a AWS CloudFormation template from file. -// Works with either JSON or YAML formatted templates. -// Parsing can be tweaked via the specified options. -func OpenWithOptions(filename string, options *intrinsics.ProcessorOptions) (*cloudformation.Template, error) { - - data, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - - if strings.HasSuffix(filename, ".yaml") || strings.HasSuffix(filename, ".yml") { - return ParseYAMLWithOptions(data, options) - } - - return ParseJSONWithOptions(data, options) - -} - -// ParseYAML an AWS CloudFormation template (expects a []byte of valid YAML) -func ParseYAML(data []byte) (*cloudformation.Template, error) { - return ParseYAMLWithOptions(data, nil) -} - -// ParseYAMLWithOptions an AWS CloudFormation template (expects a []byte of valid YAML) -// Parsing can be tweaked via the specified options. -func ParseYAMLWithOptions(data []byte, options *intrinsics.ProcessorOptions) (*cloudformation.Template, error) { - // Process all AWS CloudFormation intrinsic functions (e.g. Fn::Join) - intrinsified, err := intrinsics.ProcessYAML(data, options) - if err != nil { - return nil, err - } - - return unmarshal(intrinsified) - -} - -// ParseJSON an AWS CloudFormation template (expects a []byte of valid JSON) -func ParseJSON(data []byte) (*cloudformation.Template, error) { - return ParseJSONWithOptions(data, nil) -} - -// ParseJSONWithOptions an AWS CloudFormation template (expects a []byte of valid JSON) -// Parsing can be tweaked via the specified options. -func ParseJSONWithOptions(data []byte, options *intrinsics.ProcessorOptions) (*cloudformation.Template, error) { - - // Process all AWS CloudFormation intrinsic functions (e.g. Fn::Join) - intrinsified, err := intrinsics.ProcessJSON(data, options) - if err != nil { - return nil, err - } - - return unmarshal(intrinsified) - -} - -func unmarshal(data []byte) (*cloudformation.Template, error) { - - template := &cloudformation.Template{} - if err := json.Unmarshal(data, template); err != nil { - return nil, err - } - - return template, nil - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/conditions.go b/vendor/github.com/awslabs/goformation/intrinsics/conditions.go deleted file mode 100644 index 65bddfdcbd..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/conditions.go +++ /dev/null @@ -1,65 +0,0 @@ -package intrinsics - -// condition evaluates a condition -func condition(name string, input interface{}, template interface{}, options *ProcessorOptions) interface{} { - if v, ok := input.(string); ok { - - if v, ok := retrieveCondition(input, template); ok { - return v - } - - if c := getCondition(v, template); c != nil { - res := search(c, template, options) - // replace the value in the template so the value can be reused - setCondition(v, res, template) - - return res - } - } - - return nil -} - -func setCondition(name string, val interface{}, template interface{}) { - if template, ok := template.(map[string]interface{}); ok { - // Check there is a conditions section - if uconditions, ok := template["Conditions"]; ok { - // Check the conditions section is a map - if conditions, ok := uconditions.(map[string]interface{}); ok { - // Check there is a condition with the same name as the condition - if _, ok := conditions[name]; ok { - conditions[name] = val - } - } - } - } -} - -func getCondition(name string, template interface{}) interface{} { - if template, ok := template.(map[string]interface{}); ok { - // Check there is a conditions section - if uconditions, ok := template["Conditions"]; ok { - // Check the conditions section is a map - if conditions, ok := uconditions.(map[string]interface{}); ok { - // Check there is a condition with the same name as the condition - if ucondition, ok := conditions[name]; ok { - return ucondition - } - } - } - } - - return nil -} - -func retrieveCondition(cName interface{}, template interface{}) (value bool, found bool) { - - switch v := cName.(type) { - case string: - value, found = getCondition(v, template).(bool) - case bool: - value, found = v, true - } - - return -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnand.go b/vendor/github.com/awslabs/goformation/intrinsics/fnand.go deleted file mode 100644 index cc18ccc52d..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnand.go +++ /dev/null @@ -1,28 +0,0 @@ -package intrinsics - -// FnAnd resolves the 'Fn::And' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-and -func FnAnd(name string, input interface{}, template interface{}) interface{} { - // "Fn::And": [{condition}, ...] - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - if len(arr) < 2 || len(arr) > 10 { - return nil - } - - for _, c := range arr { - if value, ok := retrieveCondition(c, template); ok { - if !value { - return false - } - } else { - return nil - } - } - - return true - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnbase64.go b/vendor/github.com/awslabs/goformation/intrinsics/fnbase64.go deleted file mode 100644 index e24ecc2417..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnbase64.go +++ /dev/null @@ -1,18 +0,0 @@ -package intrinsics - -import "encoding/base64" - -// FnBase64 resolves the 'Fn::Base64' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-base64.htmlpackage intrinsics -func FnBase64(name string, input interface{}, template interface{}) interface{} { - - // { "Fn::Base64" : valueToEncode } - - // Check the input is a string - if src, ok := input.(string); ok { - return base64.StdEncoding.EncodeToString([]byte(src)) - } - - return nil - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnequals.go b/vendor/github.com/awslabs/goformation/intrinsics/fnequals.go deleted file mode 100644 index b3c48455c2..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnequals.go +++ /dev/null @@ -1,22 +0,0 @@ -package intrinsics - -import ( - "reflect" -) - -// FnEquals resolves the 'Fn::Equals' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-equals -func FnEquals(name string, input interface{}, template interface{}) interface{} { - // "Fn::Equals" : ["value_1", "value_2"] - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - if len(arr) != 2 { - return nil - } - - return reflect.DeepEqual(arr[0], arr[1]) - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnfindinmap.go b/vendor/github.com/awslabs/goformation/intrinsics/fnfindinmap.go deleted file mode 100644 index 29f98a9f19..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnfindinmap.go +++ /dev/null @@ -1,55 +0,0 @@ -package intrinsics - -// FnFindInMap resolves the 'Fn::FindInMap' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-findinmap.html -func FnFindInMap(name string, input interface{}, template interface{}) interface{} { - - // { "Fn::FindInMap" : [ "MapName", "TopLevelKey", "SecondLevelKey"] } - - // "Mappings" : { - // "RegionMap" : { - // "us-east-1" : { "32" : "ami-6411e20d", "64" : "ami-7a11e213" }, - // "us-west-1" : { "32" : "ami-c9c7978c", "64" : "ami-cfc7978a" }, - // "eu-west-1" : { "32" : "ami-37c2f643", "64" : "ami-31c2f645" }, - // "ap-southeast-1" : { "32" : "ami-66f28c34", "64" : "ami-60f28c32" }, - // "ap-northeast-1" : { "32" : "ami-9c03a89d", "64" : "ami-a003a8a1" } - // } - // } - - // Holy nesting batman! I'm sure there's a better way to do this... :) - - // Check that the input is an array - if arr, ok := input.([]interface{}); ok { - // The first element should be the map name - if mapname, ok := arr[0].(string); ok { - // The second element should be the first level map key - if key1, ok := arr[1].(string); ok { - // The third element should be the second level map key - if key2, ok := arr[2].(string); ok { - // Check the map exists in the CloudFormation template - if tmpl, ok := template.(map[string]interface{}); ok { - if mappings, ok := tmpl["Mappings"]; ok { - if mapmap, ok := mappings.(map[string]interface{}); ok { - if found, ok := mapmap[mapname]; ok { - if foundmap, ok := found.(map[string]interface{}); ok { - // Ok, we've got the map, check the first key exists - if foundkey1, ok := foundmap[key1]; ok { - if foundkey1map, ok := foundkey1.(map[string]interface{}); ok { - if foundkey2, ok := foundkey1map[key2]; ok { - return foundkey2 - } - } - } - } - } - } - } - } - } - } - } - } - - return nil - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fngetatt.go b/vendor/github.com/awslabs/goformation/intrinsics/fngetatt.go deleted file mode 100644 index d7f64e00e3..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fngetatt.go +++ /dev/null @@ -1,9 +0,0 @@ -package intrinsics - -// FnGetAtt is not implemented, and always returns nil. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html -func FnGetAtt(name string, input interface{}, template interface{}) interface{} { - - // { "Fn::GetAtt" : [ "logicalNameOfResource", "attributeName" ] } - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fngetazs.go b/vendor/github.com/awslabs/goformation/intrinsics/fngetazs.go deleted file mode 100644 index 034259fc87..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fngetazs.go +++ /dev/null @@ -1,36 +0,0 @@ -package intrinsics - -var AZs map[string][]interface{} = make(map[string][]interface{}) - -func buildAZs(region string, zones ...string) (result []interface{}) { - for _, zone := range zones { - result = append(result, region+zone) - } - return -} - -func init() { - AZs["us-east-1"] = buildAZs("us-east-1", "a", "b", "c", "d") - AZs["us-west-1"] = buildAZs("us-west-1", "a", "b") -} - -// FnGetAZs resolves the 'Fn::GetAZs' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getavailabilityzones.html -func FnGetAZs(name string, input interface{}, template interface{}) interface{} { - - // Check the input is a string - if region, ok := input.(string); ok { - if region == "" { - region = "us-east-1" - } - - if azs, ok := AZs[region]; ok { - return azs - } else { - //assume 3 AZs per region - return buildAZs(region, "a", "b", "c") - } - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnif.go b/vendor/github.com/awslabs/goformation/intrinsics/fnif.go deleted file mode 100644 index 985f0b561d..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnif.go +++ /dev/null @@ -1,25 +0,0 @@ -package intrinsics - -// FnIf resolves the 'Fn::If' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if -func FnIf(name string, input interface{}, template interface{}) interface{} { - - // "Fn::If": [condition_name, value_if_true, value_if_false] - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - if len(arr) != 3 { - return nil - } - - if value, ok := retrieveCondition(arr[0], template); ok { - if value { - return arr[1] - } else { - return arr[2] - } - } - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnjoin.go b/vendor/github.com/awslabs/goformation/intrinsics/fnjoin.go deleted file mode 100644 index a063908301..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnjoin.go +++ /dev/null @@ -1,20 +0,0 @@ -package intrinsics - -// FnJoin resolves the 'Fn::Join' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-join.html -func FnJoin(name string, input interface{}, template interface{}) interface{} { - - result := "" - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - for _, value := range arr { - if str, ok := value.(string); ok { - result += str - } - } - } - - return result - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnnot.go b/vendor/github.com/awslabs/goformation/intrinsics/fnnot.go deleted file mode 100644 index 78e8e23029..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnnot.go +++ /dev/null @@ -1,20 +0,0 @@ -package intrinsics - -// FnNot resolves the 'Fn::Not' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-not -func FnNot(name string, input interface{}, template interface{}) interface{} { - // "Fn::Not": [{condition}] - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - if len(arr) != 1 { - return nil - } - - if value, ok := retrieveCondition(arr[0], template); ok { - return !value - } - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnor.go b/vendor/github.com/awslabs/goformation/intrinsics/fnor.go deleted file mode 100644 index 3b0d505dae..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnor.go +++ /dev/null @@ -1,28 +0,0 @@ -package intrinsics - -// FnOr resolves the 'Fn::Or' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-or -func FnOr(name string, input interface{}, template interface{}) interface{} { - // "Fn::Or": [{condition}, ...] - - // Check the input is an array - if arr, ok := input.([]interface{}); ok { - if len(arr) < 2 || len(arr) > 10 { - return nil - } - - for _, c := range arr { - if value, ok := retrieveCondition(c, template); ok { - if value { - return true - } - } else { - return nil - } - } - - return false - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnselect.go b/vendor/github.com/awslabs/goformation/intrinsics/fnselect.go deleted file mode 100644 index b6c56a8db4..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnselect.go +++ /dev/null @@ -1,37 +0,0 @@ -package intrinsics - -import "strconv" - -// FnSelect resolves the 'Fn::Select' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-select.html -func FnSelect(name string, input interface{}, template interface{}) interface{} { - - // { "Fn::Select" : [ index, listOfObjects ] } - - // Check that the input is an array - if arr, ok := input.([]interface{}); ok { - // The first element should be the index - var index int - if index64, ok := arr[0].(float64); ok { - index = int(index64) - } else if indexStr, ok := arr[0].(string); ok { - if c, err := strconv.Atoi(indexStr); err == nil { - index = c - } else { - return nil - } - } else { - return nil - } - - // The second element is the array of objects to search - if objects, ok := arr[1].([]interface{}); ok { - // Check the requested element is in bounds - if index < len(objects) { - return objects[index] - } - } - } - - return nil -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnsplit.go b/vendor/github.com/awslabs/goformation/intrinsics/fnsplit.go deleted file mode 100644 index 64699f8a2c..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnsplit.go +++ /dev/null @@ -1,24 +0,0 @@ -package intrinsics - -import "strings" - -// FnSplit resolves the 'Fn::Split' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-split.html -func FnSplit(name string, input interface{}, template interface{}) interface{} { - - // { "Fn::Split" : [ "delimiter", "source string" ] } - - // Check that the input is an array - if arr, ok := input.([]interface{}); ok { - // The first element should be a string (the delimiter) - if delim, ok := arr[0].(string); ok { - // The second element should be a string (the content to join) - if str, ok := arr[1].(string); ok { - return strings.Split(str, delim) - } - } - } - - return []string{} - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/fnsub.go b/vendor/github.com/awslabs/goformation/intrinsics/fnsub.go deleted file mode 100644 index 70404eb8b3..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/fnsub.go +++ /dev/null @@ -1,66 +0,0 @@ -package intrinsics - -import ( - "regexp" - "strings" -) - -// FnSub resolves the 'Fn::Sub' AWS CloudFormation intrinsic function. -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html -func FnSub(name string, input interface{}, template interface{}) interface{} { - - // Input can either be a string for this type of Fn::Sub call: - // { "Fn::Sub": "some-string-with-a-${variable}" } - - // or it will be an array of length two for named replacements - // { "Fn::Sub": [ "some ${replaced}", { "replaced": "value" } ] } - - switch val := input.(type) { - - case []interface{}: - // Replace each of the variables in element 0 with the items in element 1 - if src, ok := val[0].(string); ok { - // The seconds element is a map of variables to replace - if replacements, ok := val[1].(map[string]interface{}); ok { - // Loop through the replacements - for key, replacement := range replacements { - // Check the replacement is a string - if value, ok := replacement.(string); ok { - src = strings.Replace(src, "${"+key+"}", value, -1) - } - } - return src - } - } - - case string: - // Look up references for each of the variables - regex := regexp.MustCompile(`\$\{([\.0-9A-Za-z]+)\}`) - variables := regex.FindAllStringSubmatch(val, -1) - for _, variable := range variables { - - var resolved interface{} - if strings.Contains(variable[1], ".") { - // If the variable name has a . in it, use Fn::GetAtt to resolve it - resolved = FnGetAtt("Fn::GetAtt", strings.Split(variable[1], "."), template) - } else { - // The variable name doesn't have a . in it, so use Ref - resolved = Ref("Ref", variable[1], template) - } - - if resolved != nil { - if replacement, ok := resolved.(string); ok { - val = strings.Replace(val, variable[0], replacement, -1) - } - } else { - // The reference couldn't be resolved, so just strip the variable - val = strings.Replace(val, variable[0], "", -1) - } - - } - return val - } - - return nil - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/intrinsics.go b/vendor/github.com/awslabs/goformation/intrinsics/intrinsics.go deleted file mode 100644 index 4d155670b5..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/intrinsics.go +++ /dev/null @@ -1,216 +0,0 @@ -package intrinsics - -import ( - "encoding/json" - "fmt" - - yamlwrapper "github.com/sanathkr/yaml" -) - -// IntrinsicHandler is a function that applies an intrinsic function and returns -// the response that should be placed in it's place. An intrinsic handler function -// is passed the name of the intrinsic function (e.g. Fn::Join), and the object -// to apply it to (as an interface{}), and should return the resolved object (as an interface{}). -type IntrinsicHandler func(string, interface{}, interface{}) interface{} - -// IntrinsicFunctionHandlers is a map of all the possible AWS CloudFormation intrinsic -// functions, and a handler function that is invoked to resolve. -var defaultIntrinsicHandlers = map[string]IntrinsicHandler{ - "Fn::Base64": FnBase64, - "Fn::And": FnAnd, - "Fn::Equals": FnEquals, - "Fn::If": FnIf, - "Fn::Not": FnNot, - "Fn::Or": FnOr, - "Fn::FindInMap": FnFindInMap, - "Fn::GetAtt": nonResolvingHandler, - "Fn::GetAZs": FnGetAZs, - "Fn::ImportValue": nonResolvingHandler, - "Fn::Join": FnJoin, - "Fn::Select": FnSelect, - "Fn::Split": FnSplit, - "Fn::Sub": FnSub, - "Ref": Ref, -} - -// ProcessorOptions allows customisation of the intrinsic function processor behaviour. -// Initially, this only allows overriding of the handlers for each intrinsic function type -// and overriding template paramters. -type ProcessorOptions struct { - IntrinsicHandlerOverrides map[string]IntrinsicHandler - ParameterOverrides map[string]interface{} -} - -// nonResolvingHandler is a simple example of an intrinsic function handler function -// that refuses to resolve any intrinsic functions, and just returns a basic string. -func nonResolvingHandler(name string, input interface{}, template interface{}) interface{} { - return nil -} - -// ProcessYAML recursively searches through a byte array of JSON data for all -// AWS CloudFormation intrinsic functions, resolves them, and then returns -// the resulting interface{} object. -func ProcessYAML(input []byte, options *ProcessorOptions) ([]byte, error) { - - // Convert short form intrinsic functions (e.g. !Sub) to long form - registerTagMarshallers() - - data, err := yamlwrapper.YAMLToJSON(input) - if err != nil { - return nil, fmt.Errorf("invalid YAML template: %s", err) - } - - return ProcessJSON(data, options) - -} - -// ProcessJSON recursively searches through a byte array of JSON data for all -// AWS CloudFormation intrinsic functions, resolves them, and then returns -// the resulting interface{} object. -func ProcessJSON(input []byte, options *ProcessorOptions) ([]byte, error) { - - // First, unmarshal the JSON to a generic interface{} type - var unmarshalled interface{} - if err := json.Unmarshal(input, &unmarshalled); err != nil { - return nil, fmt.Errorf("invalid JSON: %s", err) - } - - overrideParameters(unmarshalled, options) - - evaluateConditions(unmarshalled, options) - - // Process all of the intrinsic functions - processed := search(unmarshalled, unmarshalled, options) - - // And return the result back as a []byte of JSON - result, err := json.MarshalIndent(processed, "", " ") - if err != nil { - return nil, fmt.Errorf("invalid JSON: %s", err) - } - - return result, nil -} - -// overrideParameters replaces the default values of Parameters with the specified ones -func overrideParameters(input interface{}, options *ProcessorOptions) { - if options == nil || len(options.ParameterOverrides) == 0 { - return - } - - // Check the template is a map - if template, ok := input.(map[string]interface{}); ok { - // Check there is a parameters section - if uparameters, ok := template["Parameters"]; ok { - // Check the parameters section is a map - if parameters, ok := uparameters.(map[string]interface{}); ok { - for name, value := range options.ParameterOverrides { - // Check there is a parameter with the same name as the Ref - if uparameter, ok := parameters[name]; ok { - // Check the parameter is a map - if parameter, ok := uparameter.(map[string]interface{}); ok { - // Set the default value - parameter["Default"] = value - } - } - } - } - } - } -} - -// evaluateConditions replaces each condition in the template with its corresponding -// value -func evaluateConditions(input interface{}, options *ProcessorOptions) { - if template, ok := input.(map[string]interface{}); ok { - // Check there is a conditions section - if uconditions, ok := template["Conditions"]; ok { - // Check the conditions section is a map - if conditions, ok := uconditions.(map[string]interface{}); ok { - for name, expr := range conditions { - conditions[name] = search(expr, input, options) - } - } - } - } -} - -// Search is a recursive function, that will search through an interface{} looking for -// an intrinsic function. If it finds one, it calls the provided handler function, passing -// it the type of intrinsic function (e.g. 'Fn::Join'), and the contents. The intrinsic -// handler is expected to return the value that is supposed to be there. -func search(input interface{}, template interface{}, options *ProcessorOptions) interface{} { - - switch value := input.(type) { - - case map[string]interface{}: - - // We've found an object in the JSON, it might be an intrinsic, it might not. - // To check, we need to see if it contains a specific key that matches the name - // of an intrinsic function. As golang maps do not guarentee ordering, we need - // to check every key, not just the first. - processed := map[string]interface{}{} - for key, val := range value { - - // See if we have an intrinsic handler function for this object key provided in the - if h, ok := handler(key, options); ok { - // This is an intrinsic function, so replace the intrinsic function object - // with the result of calling the intrinsic function handler for this type - return h(key, search(val, template, options), template) - } - - if key == "Condition" { - // This can lead to infinite recursion A -> B; B -> A; - // pass state of the conditions that we're evaluating so we can detect cycles - // in case of cycle, return nil - return condition(key, search(val, template, options), template, options) - } - - // This is not an intrinsic function, recurse through it normally - processed[key] = search(val, template, options) - - } - return processed - - case []interface{}: - - // We found an array in the JSON - recurse through it's elements looking for intrinsic functions - processed := []interface{}{} - for _, val := range value { - processed = append(processed, search(val, template, options)) - } - return processed - - case nil: - return value - case bool: - return value - case float64: - return value - case string: - return value - default: - return nil - - } - -} - -// handler looks up the correct intrinsic function handler for an object key, if there is one. -// If not, it returns nil, false. -func handler(name string, options *ProcessorOptions) (IntrinsicHandler, bool) { - - // Check if we have a handler for this intrinsic type in the instrinsic handler - // overrides in the options provided to Process() - if options != nil { - if h, ok := options.IntrinsicHandlerOverrides[name]; ok { - return h, true - } - } - - if h, ok := defaultIntrinsicHandlers[name]; ok { - return h, true - } - - return nil, false - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/ref.go b/vendor/github.com/awslabs/goformation/intrinsics/ref.go deleted file mode 100644 index 6310efd99d..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/ref.go +++ /dev/null @@ -1,58 +0,0 @@ -package intrinsics - -// Ref resolves the 'Ref' AWS CloudFormation intrinsic function. -// Currently, this only resolves against CloudFormation Parameter default values -// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html -func Ref(name string, input interface{}, template interface{}) interface{} { - - // Dang son, this has got more nest than a bald eagle - // Check the input is a string - if name, ok := input.(string); ok { - - switch name { - - case "AWS::AccountId": - return "123456789012" - case "AWS::NotificationARNs": // - return []string{"arn:aws:sns:us-east-1:123456789012:MyTopic"} - case "AWS::NoValue": - return nil - case "AWS::Region": - return "us-east-1" - case "AWS::StackId": - return "arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/1c2fa620-982a-11e3-aff7-50e2416294e0" - case "AWS::StackName": - return "goformation-stack" - - default: - - // This isn't a pseudo 'Ref' paramater, so we need to look inside the CloudFormation template - // to see if we can resolve the reference. This implementation just looks at the Parameters section - // to see if there is a parameter matching the name, and if so, return the default value. - - // Check the template is a map - if template, ok := template.(map[string]interface{}); ok { - // Check there is a parameters section - if uparameters, ok := template["Parameters"]; ok { - // Check the parameters section is a map - if parameters, ok := uparameters.(map[string]interface{}); ok { - // Check there is a parameter with the same name as the Ref - if uparameter, ok := parameters[name]; ok { - // Check the parameter is a map - if parameter, ok := uparameter.(map[string]interface{}); ok { - // Check the parameter has a default - if def, ok := parameter["Default"]; ok { - return def - } - } - } - } - } - } - } - - } - - return nil - -} diff --git a/vendor/github.com/awslabs/goformation/intrinsics/tags.go b/vendor/github.com/awslabs/goformation/intrinsics/tags.go deleted file mode 100644 index e153b7aca8..0000000000 --- a/vendor/github.com/awslabs/goformation/intrinsics/tags.go +++ /dev/null @@ -1,45 +0,0 @@ -package intrinsics - -import ( - "reflect" - - yaml "github.com/sanathkr/go-yaml" -) - -var allTags = []string{"Ref", "GetAtt", "Base64", "FindInMap", "GetAZs", - "ImportValue", "Join", "Select", "Split", "Sub", -} - -type tagUnmarshalerType struct { -} - -func (t *tagUnmarshalerType) UnmarshalYAMLTag(tag string, fieldValue reflect.Value) reflect.Value { - - prefix := "Fn::" - if tag == "Ref" || tag == "Condition" { - prefix = "" - } - - tag = prefix + tag - - output := reflect.ValueOf(make(map[string]interface{})) - key := reflect.ValueOf(tag) - - output.SetMapIndex(key, fieldValue) - - return output -} - -var tagUnmarshaller = &tagUnmarshalerType{} - -func registerTagMarshallers() { - for _, tag := range allTags { - yaml.RegisterTagUnmarshaler("!"+tag, tagUnmarshaller) - } -} - -func unregisterTagMarshallers() { - for _, tag := range allTags { - yaml.RegisterTagUnmarshaler("!"+tag, tagUnmarshaller) - } -} diff --git a/vendor/github.com/codegangsta/cli/CHANGELOG.md b/vendor/github.com/codegangsta/cli/CHANGELOG.md deleted file mode 100644 index 07f75464b4..0000000000 --- a/vendor/github.com/codegangsta/cli/CHANGELOG.md +++ /dev/null @@ -1,392 +0,0 @@ -# Change Log - -**ATTN**: This project uses [semantic versioning](http://semver.org/). - -## [Unreleased] - -## [1.19.1] - 2016-11-21 - -### Fixed - -- Fixes regression introduced in 1.19.0 where using an `ActionFunc` as - the `Action` for a command would cause it to error rather than calling the - function. Should not have a affected declarative cases using `func(c - *cli.Context) err)`. -- Shell completion now handles the case where the user specifies - `--generate-bash-completion` immediately after a flag that takes an argument. - Previously it call the application with `--generate-bash-completion` as the - flag value. - -## [1.19.0] - 2016-11-19 -### Added -- `FlagsByName` was added to make it easy to sort flags (e.g. `sort.Sort(cli.FlagsByName(app.Flags))`) -- A `Description` field was added to `App` for a more detailed description of - the application (similar to the existing `Description` field on `Command`) -- Flag type code generation via `go generate` -- Write to stderr and exit 1 if action returns non-nil error -- Added support for TOML to the `altsrc` loader -- `SkipArgReorder` was added to allow users to skip the argument reordering. - This is useful if you want to consider all "flags" after an argument as - arguments rather than flags (the default behavior of the stdlib `flag` - library). This is backported functionality from the [removal of the flag - reordering](https://github.com/urfave/cli/pull/398) in the unreleased version - 2 -- For formatted errors (those implementing `ErrorFormatter`), the errors will - be formatted during output. Compatible with `pkg/errors`. - -### Changed -- Raise minimum tested/supported Go version to 1.2+ - -### Fixed -- Consider empty environment variables as set (previously environment variables - with the equivalent of `""` would be skipped rather than their value used). -- Return an error if the value in a given environment variable cannot be parsed - as the flag type. Previously these errors were silently swallowed. -- Print full error when an invalid flag is specified (which includes the invalid flag) -- `App.Writer` defaults to `stdout` when `nil` -- If no action is specified on a command or app, the help is now printed instead of `panic`ing -- `App.Metadata` is initialized automatically now (previously was `nil` unless initialized) -- Correctly show help message if `-h` is provided to a subcommand -- `context.(Global)IsSet` now respects environment variables. Previously it - would return `false` if a flag was specified in the environment rather than - as an argument -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user -- `altsrc`s import paths were updated to use `gopkg.in/urfave/cli.v1`. This - fixes issues that occurred when `gopkg.in/urfave/cli.v1` was imported as well - as `altsrc` where Go would complain that the types didn't match - -## [1.18.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user (backported) - -## [1.18.0] - 2016-06-27 -### Added -- `./runtests` test runner with coverage tracking by default -- testing on OS X -- testing on Windows -- `UintFlag`, `Uint64Flag`, and `Int64Flag` types and supporting code - -### Changed -- Use spaces for alignment in help/usage output instead of tabs, making the - output alignment consistent regardless of tab width - -### Fixed -- Printing of command aliases in help text -- Printing of visible flags for both struct and struct pointer flags -- Display the `help` subcommand when using `CommandCategories` -- No longer swallows `panic`s that occur within the `Action`s themselves when - detecting the signature of the `Action` field - -## [1.17.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user - -## [1.17.0] - 2016-05-09 -### Added -- Pluggable flag-level help text rendering via `cli.DefaultFlagStringFunc` -- `context.GlobalBoolT` was added as an analogue to `context.GlobalBool` -- Support for hiding commands by setting `Hidden: true` -- this will hide the - commands in help output - -### Changed -- `Float64Flag`, `IntFlag`, and `DurationFlag` default values are no longer - quoted in help text output. -- All flag types now include `(default: {value})` strings following usage when a - default value can be (reasonably) detected. -- `IntSliceFlag` and `StringSliceFlag` usage strings are now more consistent - with non-slice flag types -- Apps now exit with a code of 3 if an unknown subcommand is specified - (previously they printed "No help topic for...", but still exited 0. This - makes it easier to script around apps built using `cli` since they can trust - that a 0 exit code indicated a successful execution. -- cleanups based on [Go Report Card - feedback](https://goreportcard.com/report/github.com/urfave/cli) - -## [1.16.1] - 2016-08-28 -### Fixed -- Removed deprecation warnings to STDERR to avoid them leaking to the end-user - -## [1.16.0] - 2016-05-02 -### Added -- `Hidden` field on all flag struct types to omit from generated help text - -### Changed -- `BashCompletionFlag` (`--enable-bash-completion`) is now omitted from -generated help text via the `Hidden` field - -### Fixed -- handling of error values in `HandleAction` and `HandleExitCoder` - -## [1.15.0] - 2016-04-30 -### Added -- This file! -- Support for placeholders in flag usage strings -- `App.Metadata` map for arbitrary data/state management -- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after -parsing. -- Support for nested lookup of dot-delimited keys in structures loaded from -YAML. - -### Changed -- The `App.Action` and `Command.Action` now prefer a return signature of -`func(*cli.Context) error`, as defined by `cli.ActionFunc`. If a non-nil -`error` is returned, there may be two outcomes: - - If the error fulfills `cli.ExitCoder`, then `os.Exit` will be called - automatically - - Else the error is bubbled up and returned from `App.Run` -- Specifying an `Action` with the legacy return signature of -`func(*cli.Context)` will produce a deprecation message to stderr -- Specifying an `Action` that is not a `func` type will produce a non-zero exit -from `App.Run` -- Specifying an `Action` func that has an invalid (input) signature will -produce a non-zero exit from `App.Run` - -### Deprecated -- -`cli.App.RunAndExitOnError`, which should now be done by returning an error -that fulfills `cli.ExitCoder` to `cli.App.Run`. -- the legacy signature for -`cli.App.Action` of `func(*cli.Context)`, which should now have a return -signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`. - -### Fixed -- Added missing `*cli.Context.GlobalFloat64` method - -## [1.14.0] - 2016-04-03 (backfilled 2016-04-25) -### Added -- Codebeat badge -- Support for categorization via `CategorizedHelp` and `Categories` on app. - -### Changed -- Use `filepath.Base` instead of `path.Base` in `Name` and `HelpName`. - -### Fixed -- Ensure version is not shown in help text when `HideVersion` set. - -## [1.13.0] - 2016-03-06 (backfilled 2016-04-25) -### Added -- YAML file input support. -- `NArg` method on context. - -## [1.12.0] - 2016-02-17 (backfilled 2016-04-25) -### Added -- Custom usage error handling. -- Custom text support in `USAGE` section of help output. -- Improved help messages for empty strings. -- AppVeyor CI configuration. - -### Changed -- Removed `panic` from default help printer func. -- De-duping and optimizations. - -### Fixed -- Correctly handle `Before`/`After` at command level when no subcommands. -- Case of literal `-` argument causing flag reordering. -- Environment variable hints on Windows. -- Docs updates. - -## [1.11.1] - 2015-12-21 (backfilled 2016-04-25) -### Changed -- Use `path.Base` in `Name` and `HelpName` -- Export `GetName` on flag types. - -### Fixed -- Flag parsing when skipping is enabled. -- Test output cleanup. -- Move completion check to account for empty input case. - -## [1.11.0] - 2015-11-15 (backfilled 2016-04-25) -### Added -- Destination scan support for flags. -- Testing against `tip` in Travis CI config. - -### Changed -- Go version in Travis CI config. - -### Fixed -- Removed redundant tests. -- Use correct example naming in tests. - -## [1.10.2] - 2015-10-29 (backfilled 2016-04-25) -### Fixed -- Remove unused var in bash completion. - -## [1.10.1] - 2015-10-21 (backfilled 2016-04-25) -### Added -- Coverage and reference logos in README. - -### Fixed -- Use specified values in help and version parsing. -- Only display app version and help message once. - -## [1.10.0] - 2015-10-06 (backfilled 2016-04-25) -### Added -- More tests for existing functionality. -- `ArgsUsage` at app and command level for help text flexibility. - -### Fixed -- Honor `HideHelp` and `HideVersion` in `App.Run`. -- Remove juvenile word from README. - -## [1.9.0] - 2015-09-08 (backfilled 2016-04-25) -### Added -- `FullName` on command with accompanying help output update. -- Set default `$PROG` in bash completion. - -### Changed -- Docs formatting. - -### Fixed -- Removed self-referential imports in tests. - -## [1.8.0] - 2015-06-30 (backfilled 2016-04-25) -### Added -- Support for `Copyright` at app level. -- `Parent` func at context level to walk up context lineage. - -### Fixed -- Global flag processing at top level. - -## [1.7.1] - 2015-06-11 (backfilled 2016-04-25) -### Added -- Aggregate errors from `Before`/`After` funcs. -- Doc comments on flag structs. -- Include non-global flags when checking version and help. -- Travis CI config updates. - -### Fixed -- Ensure slice type flags have non-nil values. -- Collect global flags from the full command hierarchy. -- Docs prose. - -## [1.7.0] - 2015-05-03 (backfilled 2016-04-25) -### Changed -- `HelpPrinter` signature includes output writer. - -### Fixed -- Specify go 1.1+ in docs. -- Set `Writer` when running command as app. - -## [1.6.0] - 2015-03-23 (backfilled 2016-04-25) -### Added -- Multiple author support. -- `NumFlags` at context level. -- `Aliases` at command level. - -### Deprecated -- `ShortName` at command level. - -### Fixed -- Subcommand help output. -- Backward compatible support for deprecated `Author` and `Email` fields. -- Docs regarding `Names`/`Aliases`. - -## [1.5.0] - 2015-02-20 (backfilled 2016-04-25) -### Added -- `After` hook func support at app and command level. - -### Fixed -- Use parsed context when running command as subcommand. -- Docs prose. - -## [1.4.1] - 2015-01-09 (backfilled 2016-04-25) -### Added -- Support for hiding `-h / --help` flags, but not `help` subcommand. -- Stop flag parsing after `--`. - -### Fixed -- Help text for generic flags to specify single value. -- Use double quotes in output for defaults. -- Use `ParseInt` instead of `ParseUint` for int environment var values. -- Use `0` as base when parsing int environment var values. - -## [1.4.0] - 2014-12-12 (backfilled 2016-04-25) -### Added -- Support for environment variable lookup "cascade". -- Support for `Stdout` on app for output redirection. - -### Fixed -- Print command help instead of app help in `ShowCommandHelp`. - -## [1.3.1] - 2014-11-13 (backfilled 2016-04-25) -### Added -- Docs and example code updates. - -### Changed -- Default `-v / --version` flag made optional. - -## [1.3.0] - 2014-08-10 (backfilled 2016-04-25) -### Added -- `FlagNames` at context level. -- Exposed `VersionPrinter` var for more control over version output. -- Zsh completion hook. -- `AUTHOR` section in default app help template. -- Contribution guidelines. -- `DurationFlag` type. - -## [1.2.0] - 2014-08-02 -### Added -- Support for environment variable defaults on flags plus tests. - -## [1.1.0] - 2014-07-15 -### Added -- Bash completion. -- Optional hiding of built-in help command. -- Optional skipping of flag parsing at command level. -- `Author`, `Email`, and `Compiled` metadata on app. -- `Before` hook func support at app and command level. -- `CommandNotFound` func support at app level. -- Command reference available on context. -- `GenericFlag` type. -- `Float64Flag` type. -- `BoolTFlag` type. -- `IsSet` flag helper on context. -- More flag lookup funcs at context level. -- More tests & docs. - -### Changed -- Help template updates to account for presence/absence of flags. -- Separated subcommand help template. -- Exposed `HelpPrinter` var for more control over help output. - -## [1.0.0] - 2013-11-01 -### Added -- `help` flag in default app flag set and each command flag set. -- Custom handling of argument parsing errors. -- Command lookup by name at app level. -- `StringSliceFlag` type and supporting `StringSlice` type. -- `IntSliceFlag` type and supporting `IntSlice` type. -- Slice type flag lookups by name at context level. -- Export of app and command help functions. -- More tests & docs. - -## 0.1.0 - 2013-07-22 -### Added -- Initial implementation. - -[Unreleased]: https://github.com/urfave/cli/compare/v1.18.0...HEAD -[1.18.0]: https://github.com/urfave/cli/compare/v1.17.0...v1.18.0 -[1.17.0]: https://github.com/urfave/cli/compare/v1.16.0...v1.17.0 -[1.16.0]: https://github.com/urfave/cli/compare/v1.15.0...v1.16.0 -[1.15.0]: https://github.com/urfave/cli/compare/v1.14.0...v1.15.0 -[1.14.0]: https://github.com/urfave/cli/compare/v1.13.0...v1.14.0 -[1.13.0]: https://github.com/urfave/cli/compare/v1.12.0...v1.13.0 -[1.12.0]: https://github.com/urfave/cli/compare/v1.11.1...v1.12.0 -[1.11.1]: https://github.com/urfave/cli/compare/v1.11.0...v1.11.1 -[1.11.0]: https://github.com/urfave/cli/compare/v1.10.2...v1.11.0 -[1.10.2]: https://github.com/urfave/cli/compare/v1.10.1...v1.10.2 -[1.10.1]: https://github.com/urfave/cli/compare/v1.10.0...v1.10.1 -[1.10.0]: https://github.com/urfave/cli/compare/v1.9.0...v1.10.0 -[1.9.0]: https://github.com/urfave/cli/compare/v1.8.0...v1.9.0 -[1.8.0]: https://github.com/urfave/cli/compare/v1.7.1...v1.8.0 -[1.7.1]: https://github.com/urfave/cli/compare/v1.7.0...v1.7.1 -[1.7.0]: https://github.com/urfave/cli/compare/v1.6.0...v1.7.0 -[1.6.0]: https://github.com/urfave/cli/compare/v1.5.0...v1.6.0 -[1.5.0]: https://github.com/urfave/cli/compare/v1.4.1...v1.5.0 -[1.4.1]: https://github.com/urfave/cli/compare/v1.4.0...v1.4.1 -[1.4.0]: https://github.com/urfave/cli/compare/v1.3.1...v1.4.0 -[1.3.1]: https://github.com/urfave/cli/compare/v1.3.0...v1.3.1 -[1.3.0]: https://github.com/urfave/cli/compare/v1.2.0...v1.3.0 -[1.2.0]: https://github.com/urfave/cli/compare/v1.1.0...v1.2.0 -[1.1.0]: https://github.com/urfave/cli/compare/v1.0.0...v1.1.0 -[1.0.0]: https://github.com/urfave/cli/compare/v0.1.0...v1.0.0 diff --git a/vendor/github.com/codegangsta/cli/LICENSE b/vendor/github.com/codegangsta/cli/LICENSE deleted file mode 100644 index 42a597e29b..0000000000 --- a/vendor/github.com/codegangsta/cli/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Jeremy Saenz & Contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/codegangsta/cli/README.md b/vendor/github.com/codegangsta/cli/README.md deleted file mode 100644 index 2bbbd8ea97..0000000000 --- a/vendor/github.com/codegangsta/cli/README.md +++ /dev/null @@ -1,1381 +0,0 @@ -cli -=== - -[![Build Status](https://travis-ci.org/urfave/cli.svg?branch=master)](https://travis-ci.org/urfave/cli) -[![Windows Build Status](https://ci.appveyor.com/api/projects/status/rtgk5xufi932pb2v?svg=true)](https://ci.appveyor.com/project/urfave/cli) -[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://godoc.org/github.com/urfave/cli) -[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli) -[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli) -[![top level coverage](https://gocover.io/_badge/github.com/urfave/cli?0 "top level coverage")](http://gocover.io/github.com/urfave/cli) / -[![altsrc coverage](https://gocover.io/_badge/github.com/urfave/cli/altsrc?0 "altsrc coverage")](http://gocover.io/github.com/urfave/cli/altsrc) - -**Notice:** This is the library formerly known as -`github.com/codegangsta/cli` -- Github will automatically redirect requests -to this repository, but we recommend updating your references for clarity. - -cli is a simple, fast, and fun package for building command line apps in Go. The -goal is to enable developers to write fast and distributable command line -applications in an expressive way. - - - -- [Overview](#overview) -- [Installation](#installation) - * [Supported platforms](#supported-platforms) - * [Using the `v2` branch](#using-the-v2-branch) - * [Pinning to the `v1` releases](#pinning-to-the-v1-releases) -- [Getting Started](#getting-started) -- [Examples](#examples) - * [Arguments](#arguments) - * [Flags](#flags) - + [Placeholder Values](#placeholder-values) - + [Alternate Names](#alternate-names) - + [Ordering](#ordering) - + [Values from the Environment](#values-from-the-environment) - + [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others) - * [Subcommands](#subcommands) - * [Subcommands categories](#subcommands-categories) - * [Exit code](#exit-code) - * [Bash Completion](#bash-completion) - + [Enabling](#enabling) - + [Distribution](#distribution) - + [Customization](#customization) - * [Generated Help Text](#generated-help-text) - + [Customization](#customization-1) - * [Version Flag](#version-flag) - + [Customization](#customization-2) - + [Full API Example](#full-api-example) -- [Contribution Guidelines](#contribution-guidelines) - - - -## Overview - -Command line apps are usually so tiny that there is absolutely no reason why -your code should *not* be self-documenting. Things like generating help text and -parsing command flags/options should not hinder productivity when writing a -command line app. - -**This is where cli comes into play.** cli makes command line programming fun, -organized, and expressive! - -## Installation - -Make sure you have a working Go environment. Go version 1.2+ is supported. [See -the install instructions for Go](http://golang.org/doc/install.html). - -To install cli, simply run: -``` -$ go get github.com/urfave/cli -``` - -Make sure your `PATH` includes the `$GOPATH/bin` directory so your commands can -be easily used: -``` -export PATH=$PATH:$GOPATH/bin -``` - -### Supported platforms - -cli is tested against multiple versions of Go on Linux, and against the latest -released version of Go on OS X and Windows. For full details, see -[`./.travis.yml`](./.travis.yml) and [`./appveyor.yml`](./appveyor.yml). - -### Using the `v2` branch - -**Warning**: The `v2` branch is currently unreleased and considered unstable. - -There is currently a long-lived branch named `v2` that is intended to land as -the new `master` branch once development there has settled down. The current -`master` branch (mirrored as `v1`) is being manually merged into `v2` on -an irregular human-based schedule, but generally if one wants to "upgrade" to -`v2` *now* and accept the volatility (read: "awesomeness") that comes along with -that, please use whatever version pinning of your preference, such as via -`gopkg.in`: - -``` -$ go get gopkg.in/urfave/cli.v2 -``` - -``` go -... -import ( - "gopkg.in/urfave/cli.v2" // imports as package "cli" -) -... -``` - -### Pinning to the `v1` releases - -Similarly to the section above describing use of the `v2` branch, if one wants -to avoid any unexpected compatibility pains once `v2` becomes `master`, then -pinning to `v1` is an acceptable option, e.g.: - -``` -$ go get gopkg.in/urfave/cli.v1 -``` - -``` go -... -import ( - "gopkg.in/urfave/cli.v1" // imports as package "cli" -) -... -``` - -This will pull the latest tagged `v1` release (e.g. `v1.18.1` at the time of writing). - -## Getting Started - -One of the philosophies behind cli is that an API should be playful and full of -discovery. So a cli app can be as little as one line of code in `main()`. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.NewApp().Run(os.Args) -} -``` - -This app will run and show help text, but is not very useful. Let's give an -action to execute and some help documentation: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Name = "boom" - app.Usage = "make an explosive entrance" - app.Action = func(c *cli.Context) error { - fmt.Println("boom! I say!") - return nil - } - - app.Run(os.Args) -} -``` - -Running this already gives you a ton of functionality, plus support for things -like subcommands and flags, which are covered below. - -## Examples - -Being a programmer can be a lonely job. Thankfully by the power of automation -that is not the case! Let's create a greeter app to fend off our demons of -loneliness! - -Start by creating a directory named `greet`, and within it, add a file, -`greet.go` with the following code in it: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Name = "greet" - app.Usage = "fight the loneliness!" - app.Action = func(c *cli.Context) error { - fmt.Println("Hello friend!") - return nil - } - - app.Run(os.Args) -} -``` - -Install our command to the `$GOPATH/bin` directory: - -``` -$ go install -``` - -Finally run our new command: - -``` -$ greet -Hello friend! -``` - -cli also generates neat help text: - -``` -$ greet help -NAME: - greet - fight the loneliness! - -USAGE: - greet [global options] command [command options] [arguments...] - -VERSION: - 0.0.0 - -COMMANDS: - help, h Shows a list of commands or help for one command - -GLOBAL OPTIONS - --version Shows version information -``` - -### Arguments - -You can lookup arguments by calling the `Args` function on `cli.Context`, e.g.: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Action = func(c *cli.Context) error { - fmt.Printf("Hello %q", c.Args().Get(0)) - return nil - } - - app.Run(os.Args) -} -``` - -### Flags - -Setting and querying flags is simple. - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang", - Value: "english", - Usage: "language for the greeting", - }, - } - - app.Action = func(c *cli.Context) error { - name := "Nefertiti" - if c.NArg() > 0 { - name = c.Args().Get(0) - } - if c.String("lang") == "spanish" { - fmt.Println("Hola", name) - } else { - fmt.Println("Hello", name) - } - return nil - } - - app.Run(os.Args) -} -``` - -You can also set a destination variable for a flag, to which the content will be -scanned. - - -``` go -package main - -import ( - "os" - "fmt" - - "github.com/urfave/cli" -) - -func main() { - var language string - - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang", - Value: "english", - Usage: "language for the greeting", - Destination: &language, - }, - } - - app.Action = func(c *cli.Context) error { - name := "someone" - if c.NArg() > 0 { - name = c.Args()[0] - } - if language == "spanish" { - fmt.Println("Hola", name) - } else { - fmt.Println("Hello", name) - } - return nil - } - - app.Run(os.Args) -} -``` - -See full list of flags at http://godoc.org/github.com/urfave/cli - -#### Placeholder Values - -Sometimes it's useful to specify a flag's value within the usage string itself. -Such placeholders are indicated with back quotes. - -For example this: - - -```go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag{ - cli.StringFlag{ - Name: "config, c", - Usage: "Load configuration from `FILE`", - }, - } - - app.Run(os.Args) -} -``` - -Will result in help output like: - -``` ---config FILE, -c FILE Load configuration from FILE -``` - -Note that only the first placeholder is used. Subsequent back-quoted words will -be left as-is. - -#### Alternate Names - -You can set alternate (or short) names for flags by providing a comma-delimited -list for the `Name`. e.g. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - }, - } - - app.Run(os.Args) -} -``` - -That flag can then be set with `--lang spanish` or `-l spanish`. Note that -giving two different forms of the same flag in the same command invocation is an -error. - -#### Ordering - -Flags for the application and commands are shown in the order they are defined. -However, it's possible to sort them from outside this library by using `FlagsByName` -or `CommandsByName` with `sort`. - -For example this: - - -``` go -package main - -import ( - "os" - "sort" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "Language for the greeting", - }, - cli.StringFlag{ - Name: "config, c", - Usage: "Load configuration from `FILE`", - }, - } - - app.Commands = []cli.Command{ - { - Name: "complete", - Aliases: []string{"c"}, - Usage: "complete a task on the list", - Action: func(c *cli.Context) error { - return nil - }, - }, - { - Name: "add", - Aliases: []string{"a"}, - Usage: "add a task to the list", - Action: func(c *cli.Context) error { - return nil - }, - }, - } - - sort.Sort(cli.FlagsByName(app.Flags)) - sort.Sort(cli.CommandsByName(app.Commands)) - - app.Run(os.Args) -} -``` - -Will result in help output like: - -``` ---config FILE, -c FILE Load configuration from FILE ---lang value, -l value Language for the greeting (default: "english") -``` - -#### Values from the Environment - -You can also have the default value set from the environment via `EnvVar`. e.g. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - EnvVar: "APP_LANG", - }, - } - - app.Run(os.Args) -} -``` - -The `EnvVar` may also be given as a comma-delimited "cascade", where the first -environment variable that resolves is used as the default. - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Flags = []cli.Flag { - cli.StringFlag{ - Name: "lang, l", - Value: "english", - Usage: "language for the greeting", - EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG", - }, - } - - app.Run(os.Args) -} -``` - -#### Values from alternate input sources (YAML, TOML, and others) - -There is a separate package altsrc that adds support for getting flag values -from other file input sources. - -Currently supported input source formats: -* YAML -* TOML - -In order to get values for a flag from an alternate input source the following -code would be added to wrap an existing cli.Flag like below: - -``` go - altsrc.NewIntFlag(cli.IntFlag{Name: "test"}) -``` - -Initialization must also occur for these flags. Below is an example initializing -getting data from a yaml file below. - -``` go - command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load")) -``` - -The code above will use the "load" string as a flag name to get the file name of -a yaml file from the cli.Context. It will then use that file name to initialize -the yaml input source for any flags that are defined on that command. As a note -the "load" flag used would also have to be defined on the command flags in order -for this code snipped to work. - -Currently only the aboved specified formats are supported but developers can -add support for other input sources by implementing the -altsrc.InputSourceContext for their given sources. - -Here is a more complete sample of a command using YAML support: - - -``` go -package notmain - -import ( - "fmt" - "os" - - "github.com/urfave/cli" - "github.com/urfave/cli/altsrc" -) - -func main() { - app := cli.NewApp() - - flags := []cli.Flag{ - altsrc.NewIntFlag(cli.IntFlag{Name: "test"}), - cli.StringFlag{Name: "load"}, - } - - app.Action = func(c *cli.Context) error { - fmt.Println("yaml ist rad") - return nil - } - - app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load")) - app.Flags = flags - - app.Run(os.Args) -} -``` - -### Subcommands - -Subcommands can be defined for a more git-like command line app. - - -```go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Commands = []cli.Command{ - { - Name: "add", - Aliases: []string{"a"}, - Usage: "add a task to the list", - Action: func(c *cli.Context) error { - fmt.Println("added task: ", c.Args().First()) - return nil - }, - }, - { - Name: "complete", - Aliases: []string{"c"}, - Usage: "complete a task on the list", - Action: func(c *cli.Context) error { - fmt.Println("completed task: ", c.Args().First()) - return nil - }, - }, - { - Name: "template", - Aliases: []string{"t"}, - Usage: "options for task templates", - Subcommands: []cli.Command{ - { - Name: "add", - Usage: "add a new template", - Action: func(c *cli.Context) error { - fmt.Println("new task template: ", c.Args().First()) - return nil - }, - }, - { - Name: "remove", - Usage: "remove an existing template", - Action: func(c *cli.Context) error { - fmt.Println("removed task template: ", c.Args().First()) - return nil - }, - }, - }, - }, - } - - app.Run(os.Args) -} -``` - -### Subcommands categories - -For additional organization in apps that have many subcommands, you can -associate a category for each command to group them together in the help -output. - -E.g. - -```go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - - app.Commands = []cli.Command{ - { - Name: "noop", - }, - { - Name: "add", - Category: "template", - }, - { - Name: "remove", - Category: "template", - }, - } - - app.Run(os.Args) -} -``` - -Will include: - -``` -COMMANDS: - noop - - Template actions: - add - remove -``` - -### Exit code - -Calling `App.Run` will not automatically call `os.Exit`, which means that by -default the exit code will "fall through" to being `0`. An explicit exit code -may be set by returning a non-nil error that fulfills `cli.ExitCoder`, *or* a -`cli.MultiError` that includes an error that fulfills `cli.ExitCoder`, e.g.: - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - app := cli.NewApp() - app.Flags = []cli.Flag{ - cli.BoolTFlag{ - Name: "ginger-crouton", - Usage: "is it in the soup?", - }, - } - app.Action = func(ctx *cli.Context) error { - if !ctx.Bool("ginger-crouton") { - return cli.NewExitError("it is not in the soup", 86) - } - return nil - } - - app.Run(os.Args) -} -``` - -### Bash Completion - -You can enable completion commands by setting the `EnableBashCompletion` -flag on the `App` object. By default, this setting will only auto-complete to -show an app's subcommands, but you can write your own completion methods for -the App or its subcommands. - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -func main() { - tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"} - - app := cli.NewApp() - app.EnableBashCompletion = true - app.Commands = []cli.Command{ - { - Name: "complete", - Aliases: []string{"c"}, - Usage: "complete a task on the list", - Action: func(c *cli.Context) error { - fmt.Println("completed task: ", c.Args().First()) - return nil - }, - BashComplete: func(c *cli.Context) { - // This will complete if no args are passed - if c.NArg() > 0 { - return - } - for _, t := range tasks { - fmt.Println(t) - } - }, - }, - } - - app.Run(os.Args) -} -``` - -#### Enabling - -Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while -setting the `PROG` variable to the name of your program: - -`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete` - -#### Distribution - -Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename -it to the name of the program you wish to add autocomplete support for (or -automatically install it there if you are distributing a package). Don't forget -to source the file to make it active in the current shell. - -``` -sudo cp src/bash_autocomplete /etc/bash_completion.d/ -source /etc/bash_completion.d/ -``` - -Alternatively, you can just document that users should source the generic -`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set -to the name of their program (as above). - -#### Customization - -The default bash completion flag (`--generate-bash-completion`) is defined as -`cli.BashCompletionFlag`, and may be redefined if desired, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.BashCompletionFlag = cli.BoolFlag{ - Name: "compgen", - Hidden: true, - } - - app := cli.NewApp() - app.EnableBashCompletion = true - app.Commands = []cli.Command{ - { - Name: "wat", - }, - } - app.Run(os.Args) -} -``` - -### Generated Help Text - -The default help flag (`-h/--help`) is defined as `cli.HelpFlag` and is checked -by the cli internals in order to print generated help text for the app, command, -or subcommand, and break execution. - -#### Customization - -All of the help text generation may be customized, and at multiple levels. The -templates are exposed as variables `AppHelpTemplate`, `CommandHelpTemplate`, and -`SubcommandHelpTemplate` which may be reassigned or augmented, and full override -is possible by assigning a compatible func to the `cli.HelpPrinter` variable, -e.g.: - - -``` go -package main - -import ( - "fmt" - "io" - "os" - - "github.com/urfave/cli" -) - -func main() { - // EXAMPLE: Append to an existing template - cli.AppHelpTemplate = fmt.Sprintf(`%s - -WEBSITE: http://awesometown.example.com - -SUPPORT: support@awesometown.example.com - -`, cli.AppHelpTemplate) - - // EXAMPLE: Override a template - cli.AppHelpTemplate = `NAME: - {{.Name}} - {{.Usage}} -USAGE: - {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} - {{if len .Authors}} -AUTHOR: - {{range .Authors}}{{ . }}{{end}} - {{end}}{{if .Commands}} -COMMANDS: -{{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t"}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}} -GLOBAL OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}}{{if .Copyright }} -COPYRIGHT: - {{.Copyright}} - {{end}}{{if .Version}} -VERSION: - {{.Version}} - {{end}} -` - - // EXAMPLE: Replace the `HelpPrinter` func - cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { - fmt.Println("Ha HA. I pwnd the help!!1") - } - - cli.NewApp().Run(os.Args) -} -``` - -The default flag may be customized to something other than `-h/--help` by -setting `cli.HelpFlag`, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.HelpFlag = cli.BoolFlag{ - Name: "halp, haaaaalp", - Usage: "HALP", - EnvVar: "SHOW_HALP,HALPPLZ", - } - - cli.NewApp().Run(os.Args) -} -``` - -### Version Flag - -The default version flag (`-v/--version`) is defined as `cli.VersionFlag`, which -is checked by the cli internals in order to print the `App.Version` via -`cli.VersionPrinter` and break execution. - -#### Customization - -The default flag may be customized to something other than `-v/--version` by -setting `cli.VersionFlag`, e.g.: - - -``` go -package main - -import ( - "os" - - "github.com/urfave/cli" -) - -func main() { - cli.VersionFlag = cli.BoolFlag{ - Name: "print-version, V", - Usage: "print only the version", - } - - app := cli.NewApp() - app.Name = "partay" - app.Version = "19.99.0" - app.Run(os.Args) -} -``` - -Alternatively, the version printer at `cli.VersionPrinter` may be overridden, e.g.: - - -``` go -package main - -import ( - "fmt" - "os" - - "github.com/urfave/cli" -) - -var ( - Revision = "fafafaf" -) - -func main() { - cli.VersionPrinter = func(c *cli.Context) { - fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision) - } - - app := cli.NewApp() - app.Name = "partay" - app.Version = "19.99.0" - app.Run(os.Args) -} -``` - -#### Full API Example - -**Notice**: This is a contrived (functioning) example meant strictly for API -demonstration purposes. Use of one's imagination is encouraged. - - -``` go -package main - -import ( - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "time" - - "github.com/urfave/cli" -) - -func init() { - cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" - cli.CommandHelpTemplate += "\nYMMV\n" - cli.SubcommandHelpTemplate += "\nor something\n" - - cli.HelpFlag = cli.BoolFlag{Name: "halp"} - cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true} - cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"} - - cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { - fmt.Fprintf(w, "best of luck to you\n") - } - cli.VersionPrinter = func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version) - } - cli.OsExiter = func(c int) { - fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c) - } - cli.ErrWriter = ioutil.Discard - cli.FlagStringer = func(fl cli.Flag) string { - return fmt.Sprintf("\t\t%s", fl.GetName()) - } -} - -type hexWriter struct{} - -func (w *hexWriter) Write(p []byte) (int, error) { - for _, b := range p { - fmt.Printf("%x", b) - } - fmt.Printf("\n") - - return len(p), nil -} - -type genericType struct{ - s string -} - -func (g *genericType) Set(value string) error { - g.s = value - return nil -} - -func (g *genericType) String() string { - return g.s -} - -func main() { - app := cli.NewApp() - app.Name = "kənˈtrīv" - app.Version = "19.99.0" - app.Compiled = time.Now() - app.Authors = []cli.Author{ - cli.Author{ - Name: "Example Human", - Email: "human@example.com", - }, - } - app.Copyright = "(c) 1999 Serious Enterprise" - app.HelpName = "contrive" - app.Usage = "demonstrate available API" - app.UsageText = "contrive - demonstrating the available API" - app.ArgsUsage = "[args and such]" - app.Commands = []cli.Command{ - cli.Command{ - Name: "doo", - Aliases: []string{"do"}, - Category: "motion", - Usage: "do the doo", - UsageText: "doo - does the dooing", - Description: "no really, there is a lot of dooing to be done", - ArgsUsage: "[arrgh]", - Flags: []cli.Flag{ - cli.BoolFlag{Name: "forever, forevvarr"}, - }, - Subcommands: cli.Commands{ - cli.Command{ - Name: "wop", - Action: wopAction, - }, - }, - SkipFlagParsing: false, - HideHelp: false, - Hidden: false, - HelpName: "doo!", - BashComplete: func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "--better\n") - }, - Before: func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "brace for impact\n") - return nil - }, - After: func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") - return nil - }, - Action: func(c *cli.Context) error { - c.Command.FullName() - c.Command.HasName("wop") - c.Command.Names() - c.Command.VisibleFlags() - fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") - if c.Bool("forever") { - c.Command.Run(c) - } - return nil - }, - OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { - fmt.Fprintf(c.App.Writer, "for shame\n") - return err - }, - }, - } - app.Flags = []cli.Flag{ - cli.BoolFlag{Name: "fancy"}, - cli.BoolTFlag{Name: "fancier"}, - cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, - cli.Float64Flag{Name: "howmuch"}, - cli.GenericFlag{Name: "wat", Value: &genericType{}}, - cli.Int64Flag{Name: "longdistance"}, - cli.Int64SliceFlag{Name: "intervals"}, - cli.IntFlag{Name: "distance"}, - cli.IntSliceFlag{Name: "times"}, - cli.StringFlag{Name: "dance-move, d"}, - cli.StringSliceFlag{Name: "names, N"}, - cli.UintFlag{Name: "age"}, - cli.Uint64Flag{Name: "bigage"}, - } - app.EnableBashCompletion = true - app.HideHelp = false - app.HideVersion = false - app.BashComplete = func(c *cli.Context) { - fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") - } - app.Before = func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") - return nil - } - app.After = func(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, "Phew!\n") - return nil - } - app.CommandNotFound = func(c *cli.Context, command string) { - fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) - } - app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { - if isSubcommand { - return err - } - - fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) - return nil - } - app.Action = func(c *cli.Context) error { - cli.DefaultAppComplete(c) - cli.HandleExitCoder(errors.New("not an exit coder, though")) - cli.ShowAppHelp(c) - cli.ShowCommandCompletions(c, "nope") - cli.ShowCommandHelp(c, "also-nope") - cli.ShowCompletions(c) - cli.ShowSubcommandHelp(c) - cli.ShowVersion(c) - - categories := c.App.Categories() - categories.AddCommand("sounds", cli.Command{ - Name: "bloop", - }) - - for _, category := range c.App.Categories() { - fmt.Fprintf(c.App.Writer, "%s\n", category.Name) - fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands) - fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands()) - } - - fmt.Printf("%#v\n", c.App.Command("doo")) - if c.Bool("infinite") { - c.App.Run([]string{"app", "doo", "wop"}) - } - - if c.Bool("forevar") { - c.App.RunAsSubcommand(c) - } - c.App.Setup() - fmt.Printf("%#v\n", c.App.VisibleCategories()) - fmt.Printf("%#v\n", c.App.VisibleCommands()) - fmt.Printf("%#v\n", c.App.VisibleFlags()) - - fmt.Printf("%#v\n", c.Args().First()) - if len(c.Args()) > 0 { - fmt.Printf("%#v\n", c.Args()[1]) - } - fmt.Printf("%#v\n", c.Args().Present()) - fmt.Printf("%#v\n", c.Args().Tail()) - - set := flag.NewFlagSet("contrive", 0) - nc := cli.NewContext(c.App, set, c) - - fmt.Printf("%#v\n", nc.Args()) - fmt.Printf("%#v\n", nc.Bool("nope")) - fmt.Printf("%#v\n", nc.BoolT("nerp")) - fmt.Printf("%#v\n", nc.Duration("howlong")) - fmt.Printf("%#v\n", nc.Float64("hay")) - fmt.Printf("%#v\n", nc.Generic("bloop")) - fmt.Printf("%#v\n", nc.Int64("bonk")) - fmt.Printf("%#v\n", nc.Int64Slice("burnks")) - fmt.Printf("%#v\n", nc.Int("bips")) - fmt.Printf("%#v\n", nc.IntSlice("blups")) - fmt.Printf("%#v\n", nc.String("snurt")) - fmt.Printf("%#v\n", nc.StringSlice("snurkles")) - fmt.Printf("%#v\n", nc.Uint("flub")) - fmt.Printf("%#v\n", nc.Uint64("florb")) - fmt.Printf("%#v\n", nc.GlobalBool("global-nope")) - fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp")) - fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong")) - fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay")) - fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop")) - fmt.Printf("%#v\n", nc.GlobalInt("global-bips")) - fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups")) - fmt.Printf("%#v\n", nc.GlobalString("global-snurt")) - fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles")) - - fmt.Printf("%#v\n", nc.FlagNames()) - fmt.Printf("%#v\n", nc.GlobalFlagNames()) - fmt.Printf("%#v\n", nc.GlobalIsSet("wat")) - fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope")) - fmt.Printf("%#v\n", nc.NArg()) - fmt.Printf("%#v\n", nc.NumFlags()) - fmt.Printf("%#v\n", nc.Parent()) - - nc.Set("wat", "also-nope") - - ec := cli.NewExitError("ohwell", 86) - fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode()) - fmt.Printf("made it!\n") - return ec - } - - if os.Getenv("HEXY") != "" { - app.Writer = &hexWriter{} - app.ErrWriter = &hexWriter{} - } - - app.Metadata = map[string]interface{}{ - "layers": "many", - "explicable": false, - "whatever-values": 19.99, - } - - app.Run(os.Args) -} - -func wopAction(c *cli.Context) error { - fmt.Fprintf(c.App.Writer, ":wave: over here, eh\n") - return nil -} -``` - -## Contribution Guidelines - -Feel free to put up a pull request to fix a bug or maybe add a feature. I will -give it a code review and make sure that it does not break backwards -compatibility. If I or any other collaborators agree that it is in line with -the vision of the project, we will work with you to get the code into -a mergeable state and merge it into the master branch. - -If you have contributed something significant to the project, we will most -likely add you as a collaborator. As a collaborator you are given the ability -to merge others pull requests. It is very important that new code does not -break existing code, so be careful about what code you do choose to merge. - -If you feel like you have contributed to the project but have not yet been -added as a collaborator, we probably forgot to add you, please open an issue. diff --git a/vendor/github.com/codegangsta/cli/app.go b/vendor/github.com/codegangsta/cli/app.go deleted file mode 100644 index 95ffc0b976..0000000000 --- a/vendor/github.com/codegangsta/cli/app.go +++ /dev/null @@ -1,492 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "time" -) - -var ( - changeLogURL = "https://github.com/urfave/cli/blob/master/CHANGELOG.md" - appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL) - runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL) - - contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you." - - errInvalidActionType = NewExitError("ERROR invalid Action type. "+ - fmt.Sprintf("Must be `func(*Context`)` or `func(*Context) error). %s", contactSysadmin)+ - fmt.Sprintf("See %s", appActionDeprecationURL), 2) -) - -// App is the main structure of a cli application. It is recommended that -// an app be created with the cli.NewApp() function -type App struct { - // The name of the program. Defaults to path.Base(os.Args[0]) - Name string - // Full name of command for help, defaults to Name - HelpName string - // Description of the program. - Usage string - // Text to override the USAGE section of help - UsageText string - // Description of the program argument format. - ArgsUsage string - // Version of the program - Version string - // Description of the program - Description string - // List of commands to execute - Commands []Command - // List of flags to parse - Flags []Flag - // Boolean to enable bash completion commands - EnableBashCompletion bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide built-in version flag and the VERSION section of help - HideVersion bool - // Populate on app startup, only gettable through method Categories() - categories CommandCategories - // An action to execute when the bash-completion flag is set - BashComplete BashCompleteFunc - // An action to execute before any subcommands are run, but after the context is ready - // If a non-nil error is returned, no subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - - // The action to execute when no subcommands are specified - // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}` - // *Note*: support for the deprecated `Action` signature will be removed in a future version - Action interface{} - - // Execute this function if the proper command cannot be found - CommandNotFound CommandNotFoundFunc - // Execute this function if an usage error occurs - OnUsageError OnUsageErrorFunc - // Compilation date - Compiled time.Time - // List of all authors who contributed - Authors []Author - // Copyright of the binary if any - Copyright string - // Name of Author (Note: Use App.Authors, this is deprecated) - Author string - // Email of Author (Note: Use App.Authors, this is deprecated) - Email string - // Writer writer to write output to - Writer io.Writer - // ErrWriter writes error output - ErrWriter io.Writer - // Other custom info - Metadata map[string]interface{} - - didSetup bool -} - -// Tries to find out when this binary was compiled. -// Returns the current time if it fails to find it. -func compileTime() time.Time { - info, err := os.Stat(os.Args[0]) - if err != nil { - return time.Now() - } - return info.ModTime() -} - -// NewApp creates a new cli Application with some reasonable defaults for Name, -// Usage, Version and Action. -func NewApp() *App { - return &App{ - Name: filepath.Base(os.Args[0]), - HelpName: filepath.Base(os.Args[0]), - Usage: "A new cli application", - UsageText: "", - Version: "0.0.0", - BashComplete: DefaultAppComplete, - Action: helpCommand.Action, - Compiled: compileTime(), - Writer: os.Stdout, - } -} - -// Setup runs initialization code to ensure all data structures are ready for -// `Run` or inspection prior to `Run`. It is internally called by `Run`, but -// will return early if setup has already happened. -func (a *App) Setup() { - if a.didSetup { - return - } - - a.didSetup = true - - if a.Author != "" || a.Email != "" { - a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email}) - } - - newCmds := []Command{} - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - - if !a.HideVersion { - a.appendFlag(VersionFlag) - } - - a.categories = CommandCategories{} - for _, command := range a.Commands { - a.categories = a.categories.AddCommand(command.Category, command) - } - sort.Sort(a.categories) - - if a.Metadata == nil { - a.Metadata = make(map[string]interface{}) - } - - if a.Writer == nil { - a.Writer = os.Stdout - } -} - -// Run is the entry point to the cli app. Parses the arguments slice and routes -// to the proper flag/args combination -func (a *App) Run(arguments []string) (err error) { - a.Setup() - - // handle the completion flag separately from the flagset since - // completion could be attempted after a flag, but before its value was put - // on the command line. this causes the flagset to interpret the completion - // flag name as the value of the flag before it which is undesirable - // note that we can only do this because the shell autocomplete function - // always appends the completion flag at the end of the command - shellComplete, arguments := checkShellCompleteFlag(a, arguments) - - // parse flags - set, err := flagSet(a.Name, a.Flags) - if err != nil { - return err - } - - set.SetOutput(ioutil.Discard) - err = set.Parse(arguments[1:]) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, nil) - if nerr != nil { - fmt.Fprintln(a.Writer, nerr) - ShowAppHelp(context) - return nerr - } - context.shellComplete = shellComplete - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err := a.OnUsageError(context, err, false) - HandleExitCoder(err) - return err - } - fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - ShowAppHelp(context) - return err - } - - if !a.HideHelp && checkHelp(context) { - ShowAppHelp(context) - return nil - } - - if !a.HideVersion && checkVersion(context) { - ShowVersion(context) - return nil - } - - if a.After != nil { - defer func() { - if afterErr := a.After(context); afterErr != nil { - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil { - beforeErr := a.Before(context) - if beforeErr != nil { - fmt.Fprintf(a.Writer, "%v\n\n", beforeErr) - ShowAppHelp(context) - HandleExitCoder(beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - if a.Action == nil { - a.Action = helpCommand.Action - } - - // Run default Action - err = HandleAction(a.Action, context) - - HandleExitCoder(err) - return err -} - -// RunAndExitOnError calls .Run() and exits non-zero if an error was returned -// -// Deprecated: instead you should return an error that fulfills cli.ExitCoder -// to cli.App.Run. This will cause the application to exit with the given eror -// code in the cli.ExitCoder -func (a *App) RunAndExitOnError() { - if err := a.Run(os.Args); err != nil { - fmt.Fprintln(a.errWriter(), err) - OsExiter(1) - } -} - -// RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to -// generate command-specific flags -func (a *App) RunAsSubcommand(ctx *Context) (err error) { - // append help to commands - if len(a.Commands) > 0 { - if a.Command(helpCommand.Name) == nil && !a.HideHelp { - a.Commands = append(a.Commands, helpCommand) - if (HelpFlag != BoolFlag{}) { - a.appendFlag(HelpFlag) - } - } - } - - newCmds := []Command{} - for _, c := range a.Commands { - if c.HelpName == "" { - c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name) - } - newCmds = append(newCmds, c) - } - a.Commands = newCmds - - // parse flags - set, err := flagSet(a.Name, a.Flags) - if err != nil { - return err - } - - set.SetOutput(ioutil.Discard) - err = set.Parse(ctx.Args().Tail()) - nerr := normalizeFlags(a.Flags, set) - context := NewContext(a, set, ctx) - - if nerr != nil { - fmt.Fprintln(a.Writer, nerr) - fmt.Fprintln(a.Writer) - if len(a.Commands) > 0 { - ShowSubcommandHelp(context) - } else { - ShowCommandHelp(ctx, context.Args().First()) - } - return nerr - } - - if checkCompletions(context) { - return nil - } - - if err != nil { - if a.OnUsageError != nil { - err = a.OnUsageError(context, err, true) - HandleExitCoder(err) - return err - } - fmt.Fprintf(a.Writer, "%s %s\n\n", "Incorrect Usage.", err.Error()) - ShowSubcommandHelp(context) - return err - } - - if len(a.Commands) > 0 { - if checkSubcommandHelp(context) { - return nil - } - } else { - if checkCommandHelp(ctx, context.Args().First()) { - return nil - } - } - - if a.After != nil { - defer func() { - afterErr := a.After(context) - if afterErr != nil { - HandleExitCoder(err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if a.Before != nil { - beforeErr := a.Before(context) - if beforeErr != nil { - HandleExitCoder(beforeErr) - err = beforeErr - return err - } - } - - args := context.Args() - if args.Present() { - name := args.First() - c := a.Command(name) - if c != nil { - return c.Run(context) - } - } - - // Run default Action - err = HandleAction(a.Action, context) - - HandleExitCoder(err) - return err -} - -// Command returns the named command on App. Returns nil if the command does not exist -func (a *App) Command(name string) *Command { - for _, c := range a.Commands { - if c.HasName(name) { - return &c - } - } - - return nil -} - -// Categories returns a slice containing all the categories with the commands they contain -func (a *App) Categories() CommandCategories { - return a.categories -} - -// VisibleCategories returns a slice of categories and commands that are -// Hidden=false -func (a *App) VisibleCategories() []*CommandCategory { - ret := []*CommandCategory{} - for _, category := range a.categories { - if visible := func() *CommandCategory { - for _, command := range category.Commands { - if !command.Hidden { - return category - } - } - return nil - }(); visible != nil { - ret = append(ret, visible) - } - } - return ret -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (a *App) VisibleCommands() []Command { - ret := []Command{} - for _, command := range a.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (a *App) VisibleFlags() []Flag { - return visibleFlags(a.Flags) -} - -func (a *App) hasFlag(flag Flag) bool { - for _, f := range a.Flags { - if flag == f { - return true - } - } - - return false -} - -func (a *App) errWriter() io.Writer { - - // When the app ErrWriter is nil use the package level one. - if a.ErrWriter == nil { - return ErrWriter - } - - return a.ErrWriter -} - -func (a *App) appendFlag(flag Flag) { - if !a.hasFlag(flag) { - a.Flags = append(a.Flags, flag) - } -} - -// Author represents someone who has contributed to a cli project. -type Author struct { - Name string // The Authors name - Email string // The Authors email -} - -// String makes Author comply to the Stringer interface, to allow an easy print in the templating process -func (a Author) String() string { - e := "" - if a.Email != "" { - e = " <" + a.Email + ">" - } - - return fmt.Sprintf("%v%v", a.Name, e) -} - -// HandleAction attempts to figure out which Action signature was used. If -// it's an ActionFunc or a func with the legacy signature for Action, the func -// is run! -func HandleAction(action interface{}, context *Context) (err error) { - if a, ok := action.(ActionFunc); ok { - return a(context) - } else if a, ok := action.(func(*Context) error); ok { - return a(context) - } else if a, ok := action.(func(*Context)); ok { // deprecated function signature - a(context) - return nil - } else { - return errInvalidActionType - } -} diff --git a/vendor/github.com/codegangsta/cli/appveyor.yml b/vendor/github.com/codegangsta/cli/appveyor.yml deleted file mode 100644 index 698b188e12..0000000000 --- a/vendor/github.com/codegangsta/cli/appveyor.yml +++ /dev/null @@ -1,24 +0,0 @@ -version: "{build}" - -os: Windows Server 2012 R2 - -clone_folder: c:\gopath\src\github.com\urfave\cli - -environment: - GOPATH: C:\gopath - GOVERSION: 1.6 - PYTHON: C:\Python27-x64 - PYTHON_VERSION: 2.7.x - PYTHON_ARCH: 64 - -install: -- set PATH=%GOPATH%\bin;C:\go\bin;%PATH% -- go version -- go env -- go get github.com/urfave/gfmrun/... -- go get -v -t ./... - -build_script: -- python runtests vet -- python runtests test -- python runtests gfmrun diff --git a/vendor/github.com/codegangsta/cli/category.go b/vendor/github.com/codegangsta/cli/category.go deleted file mode 100644 index 1a6055023e..0000000000 --- a/vendor/github.com/codegangsta/cli/category.go +++ /dev/null @@ -1,44 +0,0 @@ -package cli - -// CommandCategories is a slice of *CommandCategory. -type CommandCategories []*CommandCategory - -// CommandCategory is a category containing commands. -type CommandCategory struct { - Name string - Commands Commands -} - -func (c CommandCategories) Less(i, j int) bool { - return c[i].Name < c[j].Name -} - -func (c CommandCategories) Len() int { - return len(c) -} - -func (c CommandCategories) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// AddCommand adds a command to a category. -func (c CommandCategories) AddCommand(category string, command Command) CommandCategories { - for _, commandCategory := range c { - if commandCategory.Name == category { - commandCategory.Commands = append(commandCategory.Commands, command) - return c - } - } - return append(c, &CommandCategory{Name: category, Commands: []Command{command}}) -} - -// VisibleCommands returns a slice of the Commands with Hidden=false -func (c *CommandCategory) VisibleCommands() []Command { - ret := []Command{} - for _, command := range c.Commands { - if !command.Hidden { - ret = append(ret, command) - } - } - return ret -} diff --git a/vendor/github.com/codegangsta/cli/cli.go b/vendor/github.com/codegangsta/cli/cli.go deleted file mode 100644 index 74fd101f45..0000000000 --- a/vendor/github.com/codegangsta/cli/cli.go +++ /dev/null @@ -1,21 +0,0 @@ -// Package cli provides a minimal framework for creating and organizing command line -// Go applications. cli is designed to be easy to understand and write, the most simple -// cli application can be written as follows: -// func main() { -// cli.NewApp().Run(os.Args) -// } -// -// Of course this application does not do much, so let's make this an actual application: -// func main() { -// app := cli.NewApp() -// app.Name = "greet" -// app.Usage = "say a greeting" -// app.Action = func(c *cli.Context) error { -// println("Greetings") -// } -// -// app.Run(os.Args) -// } -package cli - -//go:generate python ./generate-flag-types cli -i flag-types.json -o flag_generated.go diff --git a/vendor/github.com/codegangsta/cli/command.go b/vendor/github.com/codegangsta/cli/command.go deleted file mode 100644 index 40ebdb64f3..0000000000 --- a/vendor/github.com/codegangsta/cli/command.go +++ /dev/null @@ -1,299 +0,0 @@ -package cli - -import ( - "fmt" - "io/ioutil" - "sort" - "strings" -) - -// Command is a subcommand for a cli.App. -type Command struct { - // The name of the command - Name string - // short name of the command. Typically one character (deprecated, use `Aliases`) - ShortName string - // A list of aliases for the command - Aliases []string - // A short description of the usage of this command - Usage string - // Custom text to show on USAGE section of help - UsageText string - // A longer explanation of how the command works - Description string - // A short description of the arguments of this command - ArgsUsage string - // The category the command is part of - Category string - // The function to call when checking for bash command completions - BashComplete BashCompleteFunc - // An action to execute before any sub-subcommands are run, but after the context is ready - // If a non-nil error is returned, no sub-subcommands are run - Before BeforeFunc - // An action to execute after any subcommands are run, but after the subcommand has finished - // It is run even if Action() panics - After AfterFunc - // The function to call when this command is invoked - Action interface{} - // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind - // of deprecation period has passed, maybe? - - // Execute this function if a usage error occurs. - OnUsageError OnUsageErrorFunc - // List of child commands - Subcommands Commands - // List of flags to parse - Flags []Flag - // Treat all flags as normal arguments if true - SkipFlagParsing bool - // Skip argument reordering which attempts to move flags before arguments, - // but only works if all flags appear after all arguments. This behavior was - // removed n version 2 since it only works under specific conditions so we - // backport here by exposing it as an option for compatibility. - SkipArgReorder bool - // Boolean to hide built-in help command - HideHelp bool - // Boolean to hide this command from help or completion - Hidden bool - - // Full name of command for help, defaults to full command name, including parent commands. - HelpName string - commandNamePath []string -} - -type CommandsByName []Command - -func (c CommandsByName) Len() int { - return len(c) -} - -func (c CommandsByName) Less(i, j int) bool { - return c[i].Name < c[j].Name -} - -func (c CommandsByName) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -// FullName returns the full name of the command. -// For subcommands this ensures that parent commands are part of the command path -func (c Command) FullName() string { - if c.commandNamePath == nil { - return c.Name - } - return strings.Join(c.commandNamePath, " ") -} - -// Commands is a slice of Command -type Commands []Command - -// Run invokes the command given the context, parses ctx.Args() to generate command-specific flags -func (c Command) Run(ctx *Context) (err error) { - if len(c.Subcommands) > 0 { - return c.startApp(ctx) - } - - if !c.HideHelp && (HelpFlag != BoolFlag{}) { - // append help to flags - c.Flags = append( - c.Flags, - HelpFlag, - ) - } - - set, err := flagSet(c.Name, c.Flags) - if err != nil { - return err - } - set.SetOutput(ioutil.Discard) - - if c.SkipFlagParsing { - err = set.Parse(append([]string{"--"}, ctx.Args().Tail()...)) - } else if !c.SkipArgReorder { - firstFlagIndex := -1 - terminatorIndex := -1 - for index, arg := range ctx.Args() { - if arg == "--" { - terminatorIndex = index - break - } else if arg == "-" { - // Do nothing. A dash alone is not really a flag. - continue - } else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 { - firstFlagIndex = index - } - } - - if firstFlagIndex > -1 { - args := ctx.Args() - regularArgs := make([]string, len(args[1:firstFlagIndex])) - copy(regularArgs, args[1:firstFlagIndex]) - - var flagArgs []string - if terminatorIndex > -1 { - flagArgs = args[firstFlagIndex:terminatorIndex] - regularArgs = append(regularArgs, args[terminatorIndex:]...) - } else { - flagArgs = args[firstFlagIndex:] - } - - err = set.Parse(append(flagArgs, regularArgs...)) - } else { - err = set.Parse(ctx.Args().Tail()) - } - } else { - err = set.Parse(ctx.Args().Tail()) - } - - nerr := normalizeFlags(c.Flags, set) - if nerr != nil { - fmt.Fprintln(ctx.App.Writer, nerr) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - return nerr - } - - context := NewContext(ctx.App, set, ctx) - if checkCommandCompletions(context, c.Name) { - return nil - } - - if err != nil { - if c.OnUsageError != nil { - err := c.OnUsageError(ctx, err, false) - HandleExitCoder(err) - return err - } - fmt.Fprintln(ctx.App.Writer, "Incorrect Usage:", err.Error()) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - return err - } - - if checkCommandHelp(context, c.Name) { - return nil - } - - if c.After != nil { - defer func() { - afterErr := c.After(context) - if afterErr != nil { - HandleExitCoder(err) - if err != nil { - err = NewMultiError(err, afterErr) - } else { - err = afterErr - } - } - }() - } - - if c.Before != nil { - err = c.Before(context) - if err != nil { - fmt.Fprintln(ctx.App.Writer, err) - fmt.Fprintln(ctx.App.Writer) - ShowCommandHelp(ctx, c.Name) - HandleExitCoder(err) - return err - } - } - - if c.Action == nil { - c.Action = helpSubcommand.Action - } - - context.Command = c - err = HandleAction(c.Action, context) - - if err != nil { - HandleExitCoder(err) - } - return err -} - -// Names returns the names including short names and aliases. -func (c Command) Names() []string { - names := []string{c.Name} - - if c.ShortName != "" { - names = append(names, c.ShortName) - } - - return append(names, c.Aliases...) -} - -// HasName returns true if Command.Name or Command.ShortName matches given name -func (c Command) HasName(name string) bool { - for _, n := range c.Names() { - if n == name { - return true - } - } - return false -} - -func (c Command) startApp(ctx *Context) error { - app := NewApp() - app.Metadata = ctx.App.Metadata - // set the name and usage - app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name) - if c.HelpName == "" { - app.HelpName = c.HelpName - } else { - app.HelpName = app.Name - } - - app.Usage = c.Usage - app.Description = c.Description - app.ArgsUsage = c.ArgsUsage - - // set CommandNotFound - app.CommandNotFound = ctx.App.CommandNotFound - - // set the flags and commands - app.Commands = c.Subcommands - app.Flags = c.Flags - app.HideHelp = c.HideHelp - - app.Version = ctx.App.Version - app.HideVersion = ctx.App.HideVersion - app.Compiled = ctx.App.Compiled - app.Author = ctx.App.Author - app.Email = ctx.App.Email - app.Writer = ctx.App.Writer - app.ErrWriter = ctx.App.ErrWriter - - app.categories = CommandCategories{} - for _, command := range c.Subcommands { - app.categories = app.categories.AddCommand(command.Category, command) - } - - sort.Sort(app.categories) - - // bash completion - app.EnableBashCompletion = ctx.App.EnableBashCompletion - if c.BashComplete != nil { - app.BashComplete = c.BashComplete - } - - // set the actions - app.Before = c.Before - app.After = c.After - if c.Action != nil { - app.Action = c.Action - } else { - app.Action = helpSubcommand.Action - } - - for index, cc := range app.Commands { - app.Commands[index].commandNamePath = []string{c.Name, cc.Name} - } - - return app.RunAsSubcommand(ctx) -} - -// VisibleFlags returns a slice of the Flags with Hidden=false -func (c Command) VisibleFlags() []Flag { - return visibleFlags(c.Flags) -} diff --git a/vendor/github.com/codegangsta/cli/context.go b/vendor/github.com/codegangsta/cli/context.go deleted file mode 100644 index cb89e92a08..0000000000 --- a/vendor/github.com/codegangsta/cli/context.go +++ /dev/null @@ -1,276 +0,0 @@ -package cli - -import ( - "errors" - "flag" - "reflect" - "strings" - "syscall" -) - -// Context is a type that is passed through to -// each Handler action in a cli application. Context -// can be used to retrieve context-specific Args and -// parsed command-line options. -type Context struct { - App *App - Command Command - shellComplete bool - flagSet *flag.FlagSet - setFlags map[string]bool - parentContext *Context -} - -// NewContext creates a new context. For use in when invoking an App or Command action. -func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context { - c := &Context{App: app, flagSet: set, parentContext: parentCtx} - - if parentCtx != nil { - c.shellComplete = parentCtx.shellComplete - } - - return c -} - -// NumFlags returns the number of flags set -func (c *Context) NumFlags() int { - return c.flagSet.NFlag() -} - -// Set sets a context flag to a value. -func (c *Context) Set(name, value string) error { - return c.flagSet.Set(name, value) -} - -// GlobalSet sets a context flag to a value on the global flagset -func (c *Context) GlobalSet(name, value string) error { - return globalContext(c).flagSet.Set(name, value) -} - -// IsSet determines if the flag was actually set -func (c *Context) IsSet(name string) bool { - if c.setFlags == nil { - c.setFlags = make(map[string]bool) - - c.flagSet.Visit(func(f *flag.Flag) { - c.setFlags[f.Name] = true - }) - - c.flagSet.VisitAll(func(f *flag.Flag) { - if _, ok := c.setFlags[f.Name]; ok { - return - } - c.setFlags[f.Name] = false - }) - - // XXX hack to support IsSet for flags with EnvVar - // - // There isn't an easy way to do this with the current implementation since - // whether a flag was set via an environment variable is very difficult to - // determine here. Instead, we intend to introduce a backwards incompatible - // change in version 2 to add `IsSet` to the Flag interface to push the - // responsibility closer to where the information required to determine - // whether a flag is set by non-standard means such as environment - // variables is avaliable. - // - // See https://github.com/urfave/cli/issues/294 for additional discussion - flags := c.Command.Flags - if c.Command.Name == "" { // cannot == Command{} since it contains slice types - if c.App != nil { - flags = c.App.Flags - } - } - for _, f := range flags { - eachName(f.GetName(), func(name string) { - if isSet, ok := c.setFlags[name]; isSet || !ok { - return - } - - val := reflect.ValueOf(f) - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - - envVarValue := val.FieldByName("EnvVar") - if !envVarValue.IsValid() { - return - } - - eachName(envVarValue.String(), func(envVar string) { - envVar = strings.TrimSpace(envVar) - if _, ok := syscall.Getenv(envVar); ok { - c.setFlags[name] = true - return - } - }) - }) - } - } - - return c.setFlags[name] -} - -// GlobalIsSet determines if the global flag was actually set -func (c *Context) GlobalIsSet(name string) bool { - ctx := c - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - - for ; ctx != nil; ctx = ctx.parentContext { - if ctx.IsSet(name) { - return true - } - } - return false -} - -// FlagNames returns a slice of flag names used in this context. -func (c *Context) FlagNames() (names []string) { - for _, flag := range c.Command.Flags { - name := strings.Split(flag.GetName(), ",")[0] - if name == "help" { - continue - } - names = append(names, name) - } - return -} - -// GlobalFlagNames returns a slice of global flag names used by the app. -func (c *Context) GlobalFlagNames() (names []string) { - for _, flag := range c.App.Flags { - name := strings.Split(flag.GetName(), ",")[0] - if name == "help" || name == "version" { - continue - } - names = append(names, name) - } - return -} - -// Parent returns the parent context, if any -func (c *Context) Parent() *Context { - return c.parentContext -} - -// value returns the value of the flag coressponding to `name` -func (c *Context) value(name string) interface{} { - return c.flagSet.Lookup(name).Value.(flag.Getter).Get() -} - -// Args contains apps console arguments -type Args []string - -// Args returns the command line arguments associated with the context. -func (c *Context) Args() Args { - args := Args(c.flagSet.Args()) - return args -} - -// NArg returns the number of the command line arguments. -func (c *Context) NArg() int { - return len(c.Args()) -} - -// Get returns the nth argument, or else a blank string -func (a Args) Get(n int) string { - if len(a) > n { - return a[n] - } - return "" -} - -// First returns the first argument, or else a blank string -func (a Args) First() string { - return a.Get(0) -} - -// Tail returns the rest of the arguments (not the first one) -// or else an empty string slice -func (a Args) Tail() []string { - if len(a) >= 2 { - return []string(a)[1:] - } - return []string{} -} - -// Present checks if there are any arguments present -func (a Args) Present() bool { - return len(a) != 0 -} - -// Swap swaps arguments at the given indexes -func (a Args) Swap(from, to int) error { - if from >= len(a) || to >= len(a) { - return errors.New("index out of range") - } - a[from], a[to] = a[to], a[from] - return nil -} - -func globalContext(ctx *Context) *Context { - if ctx == nil { - return nil - } - - for { - if ctx.parentContext == nil { - return ctx - } - ctx = ctx.parentContext - } -} - -func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet { - if ctx.parentContext != nil { - ctx = ctx.parentContext - } - for ; ctx != nil; ctx = ctx.parentContext { - if f := ctx.flagSet.Lookup(name); f != nil { - return ctx.flagSet - } - } - return nil -} - -func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) { - switch ff.Value.(type) { - case *StringSlice: - default: - set.Set(name, ff.Value.String()) - } -} - -func normalizeFlags(flags []Flag, set *flag.FlagSet) error { - visited := make(map[string]bool) - set.Visit(func(f *flag.Flag) { - visited[f.Name] = true - }) - for _, f := range flags { - parts := strings.Split(f.GetName(), ",") - if len(parts) == 1 { - continue - } - var ff *flag.Flag - for _, name := range parts { - name = strings.Trim(name, " ") - if visited[name] { - if ff != nil { - return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name) - } - ff = set.Lookup(name) - } - } - if ff == nil { - continue - } - for _, name := range parts { - name = strings.Trim(name, " ") - if !visited[name] { - copyFlag(name, ff, set) - } - } - } - return nil -} diff --git a/vendor/github.com/codegangsta/cli/errors.go b/vendor/github.com/codegangsta/cli/errors.go deleted file mode 100644 index 562b2953cf..0000000000 --- a/vendor/github.com/codegangsta/cli/errors.go +++ /dev/null @@ -1,115 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" -) - -// OsExiter is the function used when the app exits. If not set defaults to os.Exit. -var OsExiter = os.Exit - -// ErrWriter is used to write errors to the user. This can be anything -// implementing the io.Writer interface and defaults to os.Stderr. -var ErrWriter io.Writer = os.Stderr - -// MultiError is an error that wraps multiple errors. -type MultiError struct { - Errors []error -} - -// NewMultiError creates a new MultiError. Pass in one or more errors. -func NewMultiError(err ...error) MultiError { - return MultiError{Errors: err} -} - -// Error implements the error interface. -func (m MultiError) Error() string { - errs := make([]string, len(m.Errors)) - for i, err := range m.Errors { - errs[i] = err.Error() - } - - return strings.Join(errs, "\n") -} - -type ErrorFormatter interface { - Format(s fmt.State, verb rune) -} - -// ExitCoder is the interface checked by `App` and `Command` for a custom exit -// code -type ExitCoder interface { - error - ExitCode() int -} - -// ExitError fulfills both the builtin `error` interface and `ExitCoder` -type ExitError struct { - exitCode int - message interface{} -} - -// NewExitError makes a new *ExitError -func NewExitError(message interface{}, exitCode int) *ExitError { - return &ExitError{ - exitCode: exitCode, - message: message, - } -} - -// Error returns the string message, fulfilling the interface required by -// `error` -func (ee *ExitError) Error() string { - return fmt.Sprintf("%v", ee.message) -} - -// ExitCode returns the exit code, fulfilling the interface required by -// `ExitCoder` -func (ee *ExitError) ExitCode() int { - return ee.exitCode -} - -// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if -// so prints the error to stderr (if it is non-empty) and calls OsExiter with the -// given exit code. If the given error is a MultiError, then this func is -// called on all members of the Errors slice and calls OsExiter with the last exit code. -func HandleExitCoder(err error) { - if err == nil { - return - } - - if exitErr, ok := err.(ExitCoder); ok { - if err.Error() != "" { - if _, ok := exitErr.(ErrorFormatter); ok { - fmt.Fprintf(ErrWriter, "%+v\n", err) - } else { - fmt.Fprintln(ErrWriter, err) - } - } - OsExiter(exitErr.ExitCode()) - return - } - - if multiErr, ok := err.(MultiError); ok { - code := handleMultiError(multiErr) - OsExiter(code) - return - } -} - -func handleMultiError(multiErr MultiError) int { - code := 1 - for _, merr := range multiErr.Errors { - if multiErr2, ok := merr.(MultiError); ok { - code = handleMultiError(multiErr2) - } else { - fmt.Fprintln(ErrWriter, merr) - if exitErr, ok := merr.(ExitCoder); ok { - code = exitErr.ExitCode() - } - } - } - return code -} diff --git a/vendor/github.com/codegangsta/cli/flag-types.json b/vendor/github.com/codegangsta/cli/flag-types.json deleted file mode 100644 index 1223107859..0000000000 --- a/vendor/github.com/codegangsta/cli/flag-types.json +++ /dev/null @@ -1,93 +0,0 @@ -[ - { - "name": "Bool", - "type": "bool", - "value": false, - "context_default": "false", - "parser": "strconv.ParseBool(f.Value.String())" - }, - { - "name": "BoolT", - "type": "bool", - "value": false, - "doctail": " that is true by default", - "context_default": "false", - "parser": "strconv.ParseBool(f.Value.String())" - }, - { - "name": "Duration", - "type": "time.Duration", - "doctail": " (see https://golang.org/pkg/time/#ParseDuration)", - "context_default": "0", - "parser": "time.ParseDuration(f.Value.String())" - }, - { - "name": "Float64", - "type": "float64", - "context_default": "0", - "parser": "strconv.ParseFloat(f.Value.String(), 64)" - }, - { - "name": "Generic", - "type": "Generic", - "dest": false, - "context_default": "nil", - "context_type": "interface{}" - }, - { - "name": "Int64", - "type": "int64", - "context_default": "0", - "parser": "strconv.ParseInt(f.Value.String(), 0, 64)" - }, - { - "name": "Int", - "type": "int", - "context_default": "0", - "parser": "strconv.ParseInt(f.Value.String(), 0, 64)", - "parser_cast": "int(parsed)" - }, - { - "name": "IntSlice", - "type": "*IntSlice", - "dest": false, - "context_default": "nil", - "context_type": "[]int", - "parser": "(f.Value.(*IntSlice)).Value(), error(nil)" - }, - { - "name": "Int64Slice", - "type": "*Int64Slice", - "dest": false, - "context_default": "nil", - "context_type": "[]int64", - "parser": "(f.Value.(*Int64Slice)).Value(), error(nil)" - }, - { - "name": "String", - "type": "string", - "context_default": "\"\"", - "parser": "f.Value.String(), error(nil)" - }, - { - "name": "StringSlice", - "type": "*StringSlice", - "dest": false, - "context_default": "nil", - "context_type": "[]string", - "parser": "(f.Value.(*StringSlice)).Value(), error(nil)" - }, - { - "name": "Uint64", - "type": "uint64", - "context_default": "0", - "parser": "strconv.ParseUint(f.Value.String(), 0, 64)" - }, - { - "name": "Uint", - "type": "uint", - "context_default": "0", - "parser": "strconv.ParseUint(f.Value.String(), 0, 64)", - "parser_cast": "uint(parsed)" - } -] diff --git a/vendor/github.com/codegangsta/cli/flag.go b/vendor/github.com/codegangsta/cli/flag.go deleted file mode 100644 index 7dd8a2c4ab..0000000000 --- a/vendor/github.com/codegangsta/cli/flag.go +++ /dev/null @@ -1,799 +0,0 @@ -package cli - -import ( - "flag" - "fmt" - "reflect" - "runtime" - "strconv" - "strings" - "syscall" - "time" -) - -const defaultPlaceholder = "value" - -// BashCompletionFlag enables bash-completion for all commands and subcommands -var BashCompletionFlag = BoolFlag{ - Name: "generate-bash-completion", - Hidden: true, -} - -// VersionFlag prints the version for the application -var VersionFlag = BoolFlag{ - Name: "version, v", - Usage: "print the version", -} - -// HelpFlag prints the help for all commands and subcommands -// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand -// unless HideHelp is set to true) -var HelpFlag = BoolFlag{ - Name: "help, h", - Usage: "show help", -} - -// FlagStringer converts a flag definition to a string. This is used by help -// to display a flag. -var FlagStringer FlagStringFunc = stringifyFlag - -// FlagsByName is a slice of Flag. -type FlagsByName []Flag - -func (f FlagsByName) Len() int { - return len(f) -} - -func (f FlagsByName) Less(i, j int) bool { - return f[i].GetName() < f[j].GetName() -} - -func (f FlagsByName) Swap(i, j int) { - f[i], f[j] = f[j], f[i] -} - -// Flag is a common interface related to parsing flags in cli. -// For more advanced flag parsing techniques, it is recommended that -// this interface be implemented. -type Flag interface { - fmt.Stringer - // Apply Flag settings to the given flag set - Apply(*flag.FlagSet) - GetName() string -} - -// errorableFlag is an interface that allows us to return errors during apply -// it allows flags defined in this library to return errors in a fashion backwards compatible -// TODO remove in v2 and modify the existing Flag interface to return errors -type errorableFlag interface { - Flag - - ApplyWithError(*flag.FlagSet) error -} - -func flagSet(name string, flags []Flag) (*flag.FlagSet, error) { - set := flag.NewFlagSet(name, flag.ContinueOnError) - - for _, f := range flags { - //TODO remove in v2 when errorableFlag is removed - if ef, ok := f.(errorableFlag); ok { - if err := ef.ApplyWithError(set); err != nil { - return nil, err - } - } else { - f.Apply(set) - } - } - return set, nil -} - -func eachName(longName string, fn func(string)) { - parts := strings.Split(longName, ",") - for _, name := range parts { - name = strings.Trim(name, " ") - fn(name) - } -} - -// Generic is a generic parseable type identified by a specific flag -type Generic interface { - Set(value string) error - String() string -} - -// Apply takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -// Ignores parsing errors -func (f GenericFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError takes the flagset and calls Set on the generic flag with the value -// provided by the user for parsing by the flag -func (f GenericFlag) ApplyWithError(set *flag.FlagSet) error { - val := f.Value - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if err := val.Set(envVal); err != nil { - return fmt.Errorf("could not parse %s as value for flag %s: %s", envVal, f.Name, err) - } - break - } - } - } - - eachName(f.Name, func(name string) { - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// StringSlice is an opaque type for []string to satisfy flag.Value and flag.Getter -type StringSlice []string - -// Set appends the string value to the list of values -func (f *StringSlice) Set(value string) error { - *f = append(*f, value) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *StringSlice) String() string { - return fmt.Sprintf("%s", *f) -} - -// Value returns the slice of strings set by this flag -func (f *StringSlice) Value() []string { - return *f -} - -// Get returns the slice of strings set by this flag -func (f *StringSlice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringSliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &StringSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as string value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &StringSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// IntSlice is an opaque type for []int to satisfy flag.Value and flag.Getter -type IntSlice []int - -// Set parses the value into an integer and appends it to the list of values -func (f *IntSlice) Set(value string) error { - tmp, err := strconv.Atoi(value) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *IntSlice) String() string { - return fmt.Sprintf("%#v", *f) -} - -// Value returns the slice of ints set by this flag -func (f *IntSlice) Value() []int { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *IntSlice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntSliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntSliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &IntSlice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int slice value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &IntSlice{} - } - set.Var(f.Value, name, f.Usage) - }) - - return nil -} - -// Int64Slice is an opaque type for []int to satisfy flag.Value and flag.Getter -type Int64Slice []int64 - -// Set parses the value into an integer and appends it to the list of values -func (f *Int64Slice) Set(value string) error { - tmp, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - *f = append(*f, tmp) - return nil -} - -// String returns a readable representation of this value (for usage defaults) -func (f *Int64Slice) String() string { - return fmt.Sprintf("%#v", *f) -} - -// Value returns the slice of ints set by this flag -func (f *Int64Slice) Value() []int64 { - return *f -} - -// Get returns the slice of ints set by this flag -func (f *Int64Slice) Get() interface{} { - return *f -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64SliceFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64SliceFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - newVal := &Int64Slice{} - for _, s := range strings.Split(envVal, ",") { - s = strings.TrimSpace(s) - if err := newVal.Set(s); err != nil { - return fmt.Errorf("could not parse %s as int64 slice value for flag %s: %s", envVal, f.Name, err) - } - } - f.Value = newVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Value == nil { - f.Value = &Int64Slice{} - } - set.Var(f.Value, name, f.Usage) - }) - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolFlag) ApplyWithError(set *flag.FlagSet) error { - val := false - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if envVal == "" { - val = false - break - } - - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - - val = envValBool - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f BoolTFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f BoolTFlag) ApplyWithError(set *flag.FlagSet) error { - val := true - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - if envVal == "" { - val = false - break - } - - envValBool, err := strconv.ParseBool(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as bool value for flag %s: %s", envVal, f.Name, err) - } - - val = envValBool - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.BoolVar(f.Destination, name, val, f.Usage) - return - } - set.Bool(name, val, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f StringFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f StringFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - f.Value = envVal - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.StringVar(f.Destination, name, f.Value, f.Usage) - return - } - set.String(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f IntFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f IntFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - f.Value = int(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.IntVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Int(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Int64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Int64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseInt(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValInt - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Int64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Int64(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f UintFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f UintFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = uint(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.UintVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Uint64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Uint64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValInt, err := strconv.ParseUint(envVal, 0, 64) - if err != nil { - return fmt.Errorf("could not parse %s as uint64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = uint64(envValInt) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Uint64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Uint64(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f DurationFlag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f DurationFlag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValDuration, err := time.ParseDuration(envVal) - if err != nil { - return fmt.Errorf("could not parse %s as duration for flag %s: %s", envVal, f.Name, err) - } - - f.Value = envValDuration - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.DurationVar(f.Destination, name, f.Value, f.Usage) - return - } - set.Duration(name, f.Value, f.Usage) - }) - - return nil -} - -// Apply populates the flag given the flag set and environment -// Ignores errors -func (f Float64Flag) Apply(set *flag.FlagSet) { - f.ApplyWithError(set) -} - -// ApplyWithError populates the flag given the flag set and environment -func (f Float64Flag) ApplyWithError(set *flag.FlagSet) error { - if f.EnvVar != "" { - for _, envVar := range strings.Split(f.EnvVar, ",") { - envVar = strings.TrimSpace(envVar) - if envVal, ok := syscall.Getenv(envVar); ok { - envValFloat, err := strconv.ParseFloat(envVal, 10) - if err != nil { - return fmt.Errorf("could not parse %s as float64 value for flag %s: %s", envVal, f.Name, err) - } - - f.Value = float64(envValFloat) - break - } - } - } - - eachName(f.Name, func(name string) { - if f.Destination != nil { - set.Float64Var(f.Destination, name, f.Value, f.Usage) - return - } - set.Float64(name, f.Value, f.Usage) - }) - - return nil -} - -func visibleFlags(fl []Flag) []Flag { - visible := []Flag{} - for _, flag := range fl { - if !flagValue(flag).FieldByName("Hidden").Bool() { - visible = append(visible, flag) - } - } - return visible -} - -func prefixFor(name string) (prefix string) { - if len(name) == 1 { - prefix = "-" - } else { - prefix = "--" - } - - return -} - -// Returns the placeholder, if any, and the unquoted usage string. -func unquoteUsage(usage string) (string, string) { - for i := 0; i < len(usage); i++ { - if usage[i] == '`' { - for j := i + 1; j < len(usage); j++ { - if usage[j] == '`' { - name := usage[i+1 : j] - usage = usage[:i] + name + usage[j+1:] - return name, usage - } - } - break - } - } - return "", usage -} - -func prefixedNames(fullName, placeholder string) string { - var prefixed string - parts := strings.Split(fullName, ",") - for i, name := range parts { - name = strings.Trim(name, " ") - prefixed += prefixFor(name) + name - if placeholder != "" { - prefixed += " " + placeholder - } - if i < len(parts)-1 { - prefixed += ", " - } - } - return prefixed -} - -func withEnvHint(envVar, str string) string { - envText := "" - if envVar != "" { - prefix := "$" - suffix := "" - sep := ", $" - if runtime.GOOS == "windows" { - prefix = "%" - suffix = "%" - sep = "%, %" - } - envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(strings.Split(envVar, ","), sep), suffix) - } - return str + envText -} - -func flagValue(f Flag) reflect.Value { - fv := reflect.ValueOf(f) - for fv.Kind() == reflect.Ptr { - fv = reflect.Indirect(fv) - } - return fv -} - -func stringifyFlag(f Flag) string { - fv := flagValue(f) - - switch f.(type) { - case IntSliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyIntSliceFlag(f.(IntSliceFlag))) - case Int64SliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyInt64SliceFlag(f.(Int64SliceFlag))) - case StringSliceFlag: - return withEnvHint(fv.FieldByName("EnvVar").String(), - stringifyStringSliceFlag(f.(StringSliceFlag))) - } - - placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String()) - - needsPlaceholder := false - defaultValueString := "" - val := fv.FieldByName("Value") - - if val.IsValid() { - needsPlaceholder = true - defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface()) - - if val.Kind() == reflect.String && val.String() != "" { - defaultValueString = fmt.Sprintf(" (default: %q)", val.String()) - } - } - - if defaultValueString == " (default: )" { - defaultValueString = "" - } - - if needsPlaceholder && placeholder == "" { - placeholder = defaultPlaceholder - } - - usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultValueString)) - - return withEnvHint(fv.FieldByName("EnvVar").String(), - fmt.Sprintf("%s\t%s", prefixedNames(fv.FieldByName("Name").String(), placeholder), usageWithDefault)) -} - -func stringifyIntSliceFlag(f IntSliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, fmt.Sprintf("%d", i)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyInt64SliceFlag(f Int64SliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, i := range f.Value.Value() { - defaultVals = append(defaultVals, fmt.Sprintf("%d", i)) - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifyStringSliceFlag(f StringSliceFlag) string { - defaultVals := []string{} - if f.Value != nil && len(f.Value.Value()) > 0 { - for _, s := range f.Value.Value() { - if len(s) > 0 { - defaultVals = append(defaultVals, fmt.Sprintf("%q", s)) - } - } - } - - return stringifySliceFlag(f.Usage, f.Name, defaultVals) -} - -func stringifySliceFlag(usage, name string, defaultVals []string) string { - placeholder, usage := unquoteUsage(usage) - if placeholder == "" { - placeholder = defaultPlaceholder - } - - defaultVal := "" - if len(defaultVals) > 0 { - defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", ")) - } - - usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal)) - return fmt.Sprintf("%s\t%s", prefixedNames(name, placeholder), usageWithDefault) -} diff --git a/vendor/github.com/codegangsta/cli/flag_generated.go b/vendor/github.com/codegangsta/cli/flag_generated.go deleted file mode 100644 index 491b61956c..0000000000 --- a/vendor/github.com/codegangsta/cli/flag_generated.go +++ /dev/null @@ -1,627 +0,0 @@ -package cli - -import ( - "flag" - "strconv" - "time" -) - -// WARNING: This file is generated! - -// BoolFlag is a flag with type bool -type BoolFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolFlag) GetName() string { - return f.Name -} - -// Bool looks up the value of a local BoolFlag, returns -// false if not found -func (c *Context) Bool(name string) bool { - return lookupBool(name, c.flagSet) -} - -// GlobalBool looks up the value of a global BoolFlag, returns -// false if not found -func (c *Context) GlobalBool(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBool(name, fs) - } - return false -} - -func lookupBool(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} - -// BoolTFlag is a flag with type bool that is true by default -type BoolTFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Destination *bool -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f BoolTFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f BoolTFlag) GetName() string { - return f.Name -} - -// BoolT looks up the value of a local BoolTFlag, returns -// false if not found -func (c *Context) BoolT(name string) bool { - return lookupBoolT(name, c.flagSet) -} - -// GlobalBoolT looks up the value of a global BoolTFlag, returns -// false if not found -func (c *Context) GlobalBoolT(name string) bool { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupBoolT(name, fs) - } - return false -} - -func lookupBoolT(name string, set *flag.FlagSet) bool { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseBool(f.Value.String()) - if err != nil { - return false - } - return parsed - } - return false -} - -// DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) -type DurationFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value time.Duration - Destination *time.Duration -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f DurationFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f DurationFlag) GetName() string { - return f.Name -} - -// Duration looks up the value of a local DurationFlag, returns -// 0 if not found -func (c *Context) Duration(name string) time.Duration { - return lookupDuration(name, c.flagSet) -} - -// GlobalDuration looks up the value of a global DurationFlag, returns -// 0 if not found -func (c *Context) GlobalDuration(name string) time.Duration { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupDuration(name, fs) - } - return 0 -} - -func lookupDuration(name string, set *flag.FlagSet) time.Duration { - f := set.Lookup(name) - if f != nil { - parsed, err := time.ParseDuration(f.Value.String()) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// Float64Flag is a flag with type float64 -type Float64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value float64 - Destination *float64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Float64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Float64Flag) GetName() string { - return f.Name -} - -// Float64 looks up the value of a local Float64Flag, returns -// 0 if not found -func (c *Context) Float64(name string) float64 { - return lookupFloat64(name, c.flagSet) -} - -// GlobalFloat64 looks up the value of a global Float64Flag, returns -// 0 if not found -func (c *Context) GlobalFloat64(name string) float64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupFloat64(name, fs) - } - return 0 -} - -func lookupFloat64(name string, set *flag.FlagSet) float64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseFloat(f.Value.String(), 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// GenericFlag is a flag with type Generic -type GenericFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value Generic -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f GenericFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f GenericFlag) GetName() string { - return f.Name -} - -// Generic looks up the value of a local GenericFlag, returns -// nil if not found -func (c *Context) Generic(name string) interface{} { - return lookupGeneric(name, c.flagSet) -} - -// GlobalGeneric looks up the value of a global GenericFlag, returns -// nil if not found -func (c *Context) GlobalGeneric(name string) interface{} { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupGeneric(name, fs) - } - return nil -} - -func lookupGeneric(name string, set *flag.FlagSet) interface{} { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value, error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Int64Flag is a flag with type int64 -type Int64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value int64 - Destination *int64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64Flag) GetName() string { - return f.Name -} - -// Int64 looks up the value of a local Int64Flag, returns -// 0 if not found -func (c *Context) Int64(name string) int64 { - return lookupInt64(name, c.flagSet) -} - -// GlobalInt64 looks up the value of a global Int64Flag, returns -// 0 if not found -func (c *Context) GlobalInt64(name string) int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64(name, fs) - } - return 0 -} - -func lookupInt64(name string, set *flag.FlagSet) int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// IntFlag is a flag with type int -type IntFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value int - Destination *int -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntFlag) GetName() string { - return f.Name -} - -// Int looks up the value of a local IntFlag, returns -// 0 if not found -func (c *Context) Int(name string) int { - return lookupInt(name, c.flagSet) -} - -// GlobalInt looks up the value of a global IntFlag, returns -// 0 if not found -func (c *Context) GlobalInt(name string) int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt(name, fs) - } - return 0 -} - -func lookupInt(name string, set *flag.FlagSet) int { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return int(parsed) - } - return 0 -} - -// IntSliceFlag is a flag with type *IntSlice -type IntSliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *IntSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f IntSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f IntSliceFlag) GetName() string { - return f.Name -} - -// IntSlice looks up the value of a local IntSliceFlag, returns -// nil if not found -func (c *Context) IntSlice(name string) []int { - return lookupIntSlice(name, c.flagSet) -} - -// GlobalIntSlice looks up the value of a global IntSliceFlag, returns -// nil if not found -func (c *Context) GlobalIntSlice(name string) []int { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupIntSlice(name, fs) - } - return nil -} - -func lookupIntSlice(name string, set *flag.FlagSet) []int { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*IntSlice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Int64SliceFlag is a flag with type *Int64Slice -type Int64SliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *Int64Slice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Int64SliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Int64SliceFlag) GetName() string { - return f.Name -} - -// Int64Slice looks up the value of a local Int64SliceFlag, returns -// nil if not found -func (c *Context) Int64Slice(name string) []int64 { - return lookupInt64Slice(name, c.flagSet) -} - -// GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns -// nil if not found -func (c *Context) GlobalInt64Slice(name string) []int64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupInt64Slice(name, fs) - } - return nil -} - -func lookupInt64Slice(name string, set *flag.FlagSet) []int64 { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*Int64Slice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// StringFlag is a flag with type string -type StringFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value string - Destination *string -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringFlag) GetName() string { - return f.Name -} - -// String looks up the value of a local StringFlag, returns -// "" if not found -func (c *Context) String(name string) string { - return lookupString(name, c.flagSet) -} - -// GlobalString looks up the value of a global StringFlag, returns -// "" if not found -func (c *Context) GlobalString(name string) string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupString(name, fs) - } - return "" -} - -func lookupString(name string, set *flag.FlagSet) string { - f := set.Lookup(name) - if f != nil { - parsed, err := f.Value.String(), error(nil) - if err != nil { - return "" - } - return parsed - } - return "" -} - -// StringSliceFlag is a flag with type *StringSlice -type StringSliceFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value *StringSlice -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f StringSliceFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f StringSliceFlag) GetName() string { - return f.Name -} - -// StringSlice looks up the value of a local StringSliceFlag, returns -// nil if not found -func (c *Context) StringSlice(name string) []string { - return lookupStringSlice(name, c.flagSet) -} - -// GlobalStringSlice looks up the value of a global StringSliceFlag, returns -// nil if not found -func (c *Context) GlobalStringSlice(name string) []string { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupStringSlice(name, fs) - } - return nil -} - -func lookupStringSlice(name string, set *flag.FlagSet) []string { - f := set.Lookup(name) - if f != nil { - parsed, err := (f.Value.(*StringSlice)).Value(), error(nil) - if err != nil { - return nil - } - return parsed - } - return nil -} - -// Uint64Flag is a flag with type uint64 -type Uint64Flag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value uint64 - Destination *uint64 -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f Uint64Flag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f Uint64Flag) GetName() string { - return f.Name -} - -// Uint64 looks up the value of a local Uint64Flag, returns -// 0 if not found -func (c *Context) Uint64(name string) uint64 { - return lookupUint64(name, c.flagSet) -} - -// GlobalUint64 looks up the value of a global Uint64Flag, returns -// 0 if not found -func (c *Context) GlobalUint64(name string) uint64 { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint64(name, fs) - } - return 0 -} - -func lookupUint64(name string, set *flag.FlagSet) uint64 { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return parsed - } - return 0 -} - -// UintFlag is a flag with type uint -type UintFlag struct { - Name string - Usage string - EnvVar string - Hidden bool - Value uint - Destination *uint -} - -// String returns a readable representation of this value -// (for usage defaults) -func (f UintFlag) String() string { - return FlagStringer(f) -} - -// GetName returns the name of the flag -func (f UintFlag) GetName() string { - return f.Name -} - -// Uint looks up the value of a local UintFlag, returns -// 0 if not found -func (c *Context) Uint(name string) uint { - return lookupUint(name, c.flagSet) -} - -// GlobalUint looks up the value of a global UintFlag, returns -// 0 if not found -func (c *Context) GlobalUint(name string) uint { - if fs := lookupGlobalFlagSet(name, c); fs != nil { - return lookupUint(name, fs) - } - return 0 -} - -func lookupUint(name string, set *flag.FlagSet) uint { - f := set.Lookup(name) - if f != nil { - parsed, err := strconv.ParseUint(f.Value.String(), 0, 64) - if err != nil { - return 0 - } - return uint(parsed) - } - return 0 -} diff --git a/vendor/github.com/codegangsta/cli/funcs.go b/vendor/github.com/codegangsta/cli/funcs.go deleted file mode 100644 index cba5e6cb0c..0000000000 --- a/vendor/github.com/codegangsta/cli/funcs.go +++ /dev/null @@ -1,28 +0,0 @@ -package cli - -// BashCompleteFunc is an action to execute when the bash-completion flag is set -type BashCompleteFunc func(*Context) - -// BeforeFunc is an action to execute before any subcommands are run, but after -// the context is ready if a non-nil error is returned, no subcommands are run -type BeforeFunc func(*Context) error - -// AfterFunc is an action to execute after any subcommands are run, but after the -// subcommand has finished it is run even if Action() panics -type AfterFunc func(*Context) error - -// ActionFunc is the action to execute when no subcommands are specified -type ActionFunc func(*Context) error - -// CommandNotFoundFunc is executed if the proper command cannot be found -type CommandNotFoundFunc func(*Context, string) - -// OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying -// customized usage error messages. This function is able to replace the -// original error messages. If this function is not set, the "Incorrect usage" -// is displayed and the execution is interrupted. -type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error - -// FlagStringFunc is used by the help generation to display a flag, which is -// expected to be a single line. -type FlagStringFunc func(Flag) string diff --git a/vendor/github.com/codegangsta/cli/generate-flag-types b/vendor/github.com/codegangsta/cli/generate-flag-types deleted file mode 100755 index 7147381ce3..0000000000 --- a/vendor/github.com/codegangsta/cli/generate-flag-types +++ /dev/null @@ -1,255 +0,0 @@ -#!/usr/bin/env python -""" -The flag types that ship with the cli library have many things in common, and -so we can take advantage of the `go generate` command to create much of the -source code from a list of definitions. These definitions attempt to cover -the parts that vary between flag types, and should evolve as needed. - -An example of the minimum definition needed is: - - { - "name": "SomeType", - "type": "sometype", - "context_default": "nil" - } - -In this example, the code generated for the `cli` package will include a type -named `SomeTypeFlag` that is expected to wrap a value of type `sometype`. -Fetching values by name via `*cli.Context` will default to a value of `nil`. - -A more complete, albeit somewhat redundant, example showing all available -definition keys is: - - { - "name": "VeryMuchType", - "type": "*VeryMuchType", - "value": true, - "dest": false, - "doctail": " which really only wraps a []float64, oh well!", - "context_type": "[]float64", - "context_default": "nil", - "parser": "parseVeryMuchType(f.Value.String())", - "parser_cast": "[]float64(parsed)" - } - -The meaning of each field is as follows: - - name (string) - The type "name", which will be suffixed with - `Flag` when generating the type definition - for `cli` and the wrapper type for `altsrc` - type (string) - The type that the generated `Flag` type for `cli` - is expected to "contain" as its `.Value` member - value (bool) - Should the generated `cli` type have a `Value` - member? - dest (bool) - Should the generated `cli` type support a - destination pointer? - doctail (string) - Additional docs for the `cli` flag type comment - context_type (string) - The literal type used in the `*cli.Context` - reader func signature - context_default (string) - The literal value used as the default by the - `*cli.Context` reader funcs when no value is - present - parser (string) - Literal code used to parse the flag `f`, - expected to have a return signature of - (value, error) - parser_cast (string) - Literal code used to cast the `parsed` value - returned from the `parser` code -""" - -from __future__ import print_function, unicode_literals - -import argparse -import json -import os -import subprocess -import sys -import tempfile -import textwrap - - -class _FancyFormatter(argparse.ArgumentDefaultsHelpFormatter, - argparse.RawDescriptionHelpFormatter): - pass - - -def main(sysargs=sys.argv[:]): - parser = argparse.ArgumentParser( - description='Generate flag type code!', - formatter_class=_FancyFormatter) - parser.add_argument( - 'package', - type=str, default='cli', choices=_WRITEFUNCS.keys(), - help='Package for which flag types will be generated' - ) - parser.add_argument( - '-i', '--in-json', - type=argparse.FileType('r'), - default=sys.stdin, - help='Input JSON file which defines each type to be generated' - ) - parser.add_argument( - '-o', '--out-go', - type=argparse.FileType('w'), - default=sys.stdout, - help='Output file/stream to which generated source will be written' - ) - parser.epilog = __doc__ - - args = parser.parse_args(sysargs[1:]) - _generate_flag_types(_WRITEFUNCS[args.package], args.out_go, args.in_json) - return 0 - - -def _generate_flag_types(writefunc, output_go, input_json): - types = json.load(input_json) - - tmp = tempfile.NamedTemporaryFile(suffix='.go', delete=False) - writefunc(tmp, types) - tmp.close() - - new_content = subprocess.check_output( - ['goimports', tmp.name] - ).decode('utf-8') - - print(new_content, file=output_go, end='') - output_go.flush() - os.remove(tmp.name) - - -def _set_typedef_defaults(typedef): - typedef.setdefault('doctail', '') - typedef.setdefault('context_type', typedef['type']) - typedef.setdefault('dest', True) - typedef.setdefault('value', True) - typedef.setdefault('parser', 'f.Value, error(nil)') - typedef.setdefault('parser_cast', 'parsed') - - -def _write_cli_flag_types(outfile, types): - _fwrite(outfile, """\ - package cli - - // WARNING: This file is generated! - - """) - - for typedef in types: - _set_typedef_defaults(typedef) - - _fwrite(outfile, """\ - // {name}Flag is a flag with type {type}{doctail} - type {name}Flag struct {{ - Name string - Usage string - EnvVar string - Hidden bool - """.format(**typedef)) - - if typedef['value']: - _fwrite(outfile, """\ - Value {type} - """.format(**typedef)) - - if typedef['dest']: - _fwrite(outfile, """\ - Destination *{type} - """.format(**typedef)) - - _fwrite(outfile, "\n}\n\n") - - _fwrite(outfile, """\ - // String returns a readable representation of this value - // (for usage defaults) - func (f {name}Flag) String() string {{ - return FlagStringer(f) - }} - - // GetName returns the name of the flag - func (f {name}Flag) GetName() string {{ - return f.Name - }} - - // {name} looks up the value of a local {name}Flag, returns - // {context_default} if not found - func (c *Context) {name}(name string) {context_type} {{ - return lookup{name}(name, c.flagSet) - }} - - // Global{name} looks up the value of a global {name}Flag, returns - // {context_default} if not found - func (c *Context) Global{name}(name string) {context_type} {{ - if fs := lookupGlobalFlagSet(name, c); fs != nil {{ - return lookup{name}(name, fs) - }} - return {context_default} - }} - - func lookup{name}(name string, set *flag.FlagSet) {context_type} {{ - f := set.Lookup(name) - if f != nil {{ - parsed, err := {parser} - if err != nil {{ - return {context_default} - }} - return {parser_cast} - }} - return {context_default} - }} - """.format(**typedef)) - - -def _write_altsrc_flag_types(outfile, types): - _fwrite(outfile, """\ - package altsrc - - import ( - "gopkg.in/urfave/cli.v1" - ) - - // WARNING: This file is generated! - - """) - - for typedef in types: - _set_typedef_defaults(typedef) - - _fwrite(outfile, """\ - // {name}Flag is the flag type that wraps cli.{name}Flag to allow - // for other values to be specified - type {name}Flag struct {{ - cli.{name}Flag - set *flag.FlagSet - }} - - // New{name}Flag creates a new {name}Flag - func New{name}Flag(fl cli.{name}Flag) *{name}Flag {{ - return &{name}Flag{{{name}Flag: fl, set: nil}} - }} - - // Apply saves the flagSet for later usage calls, then calls the - // wrapped {name}Flag.Apply - func (f *{name}Flag) Apply(set *flag.FlagSet) {{ - f.set = set - f.{name}Flag.Apply(set) - }} - - // ApplyWithError saves the flagSet for later usage calls, then calls the - // wrapped {name}Flag.ApplyWithError - func (f *{name}Flag) ApplyWithError(set *flag.FlagSet) error {{ - f.set = set - return f.{name}Flag.ApplyWithError(set) - }} - """.format(**typedef)) - - -def _fwrite(outfile, text): - print(textwrap.dedent(text), end='', file=outfile) - - -_WRITEFUNCS = { - 'cli': _write_cli_flag_types, - 'altsrc': _write_altsrc_flag_types -} - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/github.com/codegangsta/cli/help.go b/vendor/github.com/codegangsta/cli/help.go deleted file mode 100644 index d00e4da1b5..0000000000 --- a/vendor/github.com/codegangsta/cli/help.go +++ /dev/null @@ -1,294 +0,0 @@ -package cli - -import ( - "fmt" - "io" - "os" - "strings" - "text/tabwriter" - "text/template" -) - -// AppHelpTemplate is the text template for the Default help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var AppHelpTemplate = `NAME: - {{.Name}}{{if .Usage}} - {{.Usage}}{{end}} - -USAGE: - {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} - -VERSION: - {{.Version}}{{end}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if len .Authors}} - -AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: - {{range $index, $author := .Authors}}{{if $index}} - {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} - -GLOBAL OPTIONS: - {{range $index, $option := .VisibleFlags}}{{if $index}} - {{end}}{{$option}}{{end}}{{end}}{{if .Copyright}} - -COPYRIGHT: - {{.Copyright}}{{end}} -` - -// CommandHelpTemplate is the text template for the command help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var CommandHelpTemplate = `NAME: - {{.HelpName}} - {{.Usage}} - -USAGE: - {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}} - -CATEGORY: - {{.Category}}{{end}}{{if .Description}} - -DESCRIPTION: - {{.Description}}{{end}}{{if .VisibleFlags}} - -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -// SubcommandHelpTemplate is the text template for the subcommand help topic. -// cli.go uses text/template to render templates. You can -// render custom help text by setting this variable. -var SubcommandHelpTemplate = `NAME: - {{.HelpName}} - {{if .Description}}{{.Description}}{{else}}{{.Usage}}{{end}} - -USAGE: - {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} - -COMMANDS:{{range .VisibleCategories}}{{if .Name}} - {{.Name}}:{{end}}{{range .VisibleCommands}} - {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}} -{{end}}{{if .VisibleFlags}} -OPTIONS: - {{range .VisibleFlags}}{{.}} - {{end}}{{end}} -` - -var helpCommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - ShowAppHelp(c) - return nil - }, -} - -var helpSubcommand = Command{ - Name: "help", - Aliases: []string{"h"}, - Usage: "Shows a list of commands or help for one command", - ArgsUsage: "[command]", - Action: func(c *Context) error { - args := c.Args() - if args.Present() { - return ShowCommandHelp(c, args.First()) - } - - return ShowSubcommandHelp(c) - }, -} - -// Prints help for the App or Command -type helpPrinter func(w io.Writer, templ string, data interface{}) - -// HelpPrinter is a function that writes the help output. If not set a default -// is used. The function signature is: -// func(w io.Writer, templ string, data interface{}) -var HelpPrinter helpPrinter = printHelp - -// VersionPrinter prints the version for the App -var VersionPrinter = printVersion - -// ShowAppHelp is an action that displays the help. -func ShowAppHelp(c *Context) error { - HelpPrinter(c.App.Writer, AppHelpTemplate, c.App) - return nil -} - -// DefaultAppComplete prints the list of subcommands as the default app completion method -func DefaultAppComplete(c *Context) { - for _, command := range c.App.Commands { - if command.Hidden { - continue - } - for _, name := range command.Names() { - fmt.Fprintln(c.App.Writer, name) - } - } -} - -// ShowCommandHelp prints help for the given command -func ShowCommandHelp(ctx *Context, command string) error { - // show the subcommand help for a command with subcommands - if command == "" { - HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App) - return nil - } - - for _, c := range ctx.App.Commands { - if c.HasName(command) { - HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c) - return nil - } - } - - if ctx.App.CommandNotFound == nil { - return NewExitError(fmt.Sprintf("No help topic for '%v'", command), 3) - } - - ctx.App.CommandNotFound(ctx, command) - return nil -} - -// ShowSubcommandHelp prints help for the given subcommand -func ShowSubcommandHelp(c *Context) error { - return ShowCommandHelp(c, c.Command.Name) -} - -// ShowVersion prints the version number of the App -func ShowVersion(c *Context) { - VersionPrinter(c) -} - -func printVersion(c *Context) { - fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version) -} - -// ShowCompletions prints the lists of commands within a given context -func ShowCompletions(c *Context) { - a := c.App - if a != nil && a.BashComplete != nil { - a.BashComplete(c) - } -} - -// ShowCommandCompletions prints the custom completions for a given command -func ShowCommandCompletions(ctx *Context, command string) { - c := ctx.App.Command(command) - if c != nil && c.BashComplete != nil { - c.BashComplete(ctx) - } -} - -func printHelp(out io.Writer, templ string, data interface{}) { - funcMap := template.FuncMap{ - "join": strings.Join, - } - - w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) - t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) - err := t.Execute(w, data) - if err != nil { - // If the writer is closed, t.Execute will fail, and there's nothing - // we can do to recover. - if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { - fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) - } - return - } - w.Flush() -} - -func checkVersion(c *Context) bool { - found := false - if VersionFlag.Name != "" { - eachName(VersionFlag.Name, func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkHelp(c *Context) bool { - found := false - if HelpFlag.Name != "" { - eachName(HelpFlag.Name, func(name string) { - if c.GlobalBool(name) || c.Bool(name) { - found = true - } - }) - } - return found -} - -func checkCommandHelp(c *Context, name string) bool { - if c.Bool("h") || c.Bool("help") { - ShowCommandHelp(c, name) - return true - } - - return false -} - -func checkSubcommandHelp(c *Context) bool { - if c.Bool("h") || c.Bool("help") { - ShowSubcommandHelp(c) - return true - } - - return false -} - -func checkShellCompleteFlag(a *App, arguments []string) (bool, []string) { - if !a.EnableBashCompletion { - return false, arguments - } - - pos := len(arguments) - 1 - lastArg := arguments[pos] - - if lastArg != "--"+BashCompletionFlag.Name { - return false, arguments - } - - return true, arguments[:pos] -} - -func checkCompletions(c *Context) bool { - if !c.shellComplete { - return false - } - - if args := c.Args(); args.Present() { - name := args.First() - if cmd := c.App.Command(name); cmd != nil { - // let the command handle the completion - return false - } - } - - ShowCompletions(c) - return true -} - -func checkCommandCompletions(c *Context, name string) bool { - if !c.shellComplete { - return false - } - - ShowCommandCompletions(c, name) - return true -} diff --git a/vendor/github.com/codegangsta/cli/runtests b/vendor/github.com/codegangsta/cli/runtests deleted file mode 100755 index ee22bdeed5..0000000000 --- a/vendor/github.com/codegangsta/cli/runtests +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env python -from __future__ import print_function - -import argparse -import os -import sys -import tempfile - -from subprocess import check_call, check_output - - -PACKAGE_NAME = os.environ.get( - 'CLI_PACKAGE_NAME', 'github.com/urfave/cli' -) - - -def main(sysargs=sys.argv[:]): - targets = { - 'vet': _vet, - 'test': _test, - 'gfmrun': _gfmrun, - 'toc': _toc, - 'gen': _gen, - } - - parser = argparse.ArgumentParser() - parser.add_argument( - 'target', nargs='?', choices=tuple(targets.keys()), default='test' - ) - args = parser.parse_args(sysargs[1:]) - - targets[args.target]() - return 0 - - -def _test(): - if check_output('go version'.split()).split()[2] < 'go1.2': - _run('go test -v .') - return - - coverprofiles = [] - for subpackage in ['', 'altsrc']: - coverprofile = 'cli.coverprofile' - if subpackage != '': - coverprofile = '{}.coverprofile'.format(subpackage) - - coverprofiles.append(coverprofile) - - _run('go test -v'.split() + [ - '-coverprofile={}'.format(coverprofile), - ('{}/{}'.format(PACKAGE_NAME, subpackage)).rstrip('/') - ]) - - combined_name = _combine_coverprofiles(coverprofiles) - _run('go tool cover -func={}'.format(combined_name)) - os.remove(combined_name) - - -def _gfmrun(): - go_version = check_output('go version'.split()).split()[2] - if go_version < 'go1.3': - print('runtests: skip on {}'.format(go_version), file=sys.stderr) - return - _run(['gfmrun', '-c', str(_gfmrun_count()), '-s', 'README.md']) - - -def _vet(): - _run('go vet ./...') - - -def _toc(): - _run('node_modules/.bin/markdown-toc -i README.md') - _run('git diff --exit-code') - - -def _gen(): - go_version = check_output('go version'.split()).split()[2] - if go_version < 'go1.5': - print('runtests: skip on {}'.format(go_version), file=sys.stderr) - return - - _run('go generate ./...') - _run('git diff --exit-code') - - -def _run(command): - if hasattr(command, 'split'): - command = command.split() - print('runtests: {}'.format(' '.join(command)), file=sys.stderr) - check_call(command) - - -def _gfmrun_count(): - with open('README.md') as infile: - lines = infile.read().splitlines() - return len(filter(_is_go_runnable, lines)) - - -def _is_go_runnable(line): - return line.startswith('package main') - - -def _combine_coverprofiles(coverprofiles): - combined = tempfile.NamedTemporaryFile( - suffix='.coverprofile', delete=False - ) - combined.write('mode: set\n') - - for coverprofile in coverprofiles: - with open(coverprofile, 'r') as infile: - for line in infile.readlines(): - if not line.startswith('mode: '): - combined.write(line) - - combined.flush() - name = combined.name - combined.close() - return name - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/vendor/github.com/docker/distribution/LICENSE b/vendor/github.com/docker/distribution/LICENSE deleted file mode 100644 index e06d208186..0000000000 --- a/vendor/github.com/docker/distribution/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ -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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. - diff --git a/vendor/github.com/docker/distribution/digestset/set.go b/vendor/github.com/docker/distribution/digestset/set.go deleted file mode 100644 index 71327dca72..0000000000 --- a/vendor/github.com/docker/distribution/digestset/set.go +++ /dev/null @@ -1,247 +0,0 @@ -package digestset - -import ( - "errors" - "sort" - "strings" - "sync" - - digest "github.com/opencontainers/go-digest" -) - -var ( - // ErrDigestNotFound is used when a matching digest - // could not be found in a set. - ErrDigestNotFound = errors.New("digest not found") - - // ErrDigestAmbiguous is used when multiple digests - // are found in a set. None of the matching digests - // should be considered valid matches. - ErrDigestAmbiguous = errors.New("ambiguous digest string") -) - -// Set is used to hold a unique set of digests which -// may be easily referenced by easily referenced by a string -// representation of the digest as well as short representation. -// The uniqueness of the short representation is based on other -// digests in the set. If digests are omitted from this set, -// collisions in a larger set may not be detected, therefore it -// is important to always do short representation lookups on -// the complete set of digests. To mitigate collisions, an -// appropriately long short code should be used. -type Set struct { - mutex sync.RWMutex - entries digestEntries -} - -// NewSet creates an empty set of digests -// which may have digests added. -func NewSet() *Set { - return &Set{ - entries: digestEntries{}, - } -} - -// checkShortMatch checks whether two digests match as either whole -// values or short values. This function does not test equality, -// rather whether the second value could match against the first -// value. -func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool { - if len(hex) == len(shortHex) { - if hex != shortHex { - return false - } - if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - } else if !strings.HasPrefix(hex, shortHex) { - return false - } else if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - return true -} - -// Lookup looks for a digest matching the given string representation. -// If no digests could be found ErrDigestNotFound will be returned -// with an empty digest value. If multiple matches are found -// ErrDigestAmbiguous will be returned with an empty digest value. -func (dst *Set) Lookup(d string) (digest.Digest, error) { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - if len(dst.entries) == 0 { - return "", ErrDigestNotFound - } - var ( - searchFunc func(int) bool - alg digest.Algorithm - hex string - ) - dgst, err := digest.Parse(d) - if err == digest.ErrDigestInvalidFormat { - hex = d - searchFunc = func(i int) bool { - return dst.entries[i].val >= d - } - } else { - hex = dgst.Hex() - alg = dgst.Algorithm() - searchFunc = func(i int) bool { - if dst.entries[i].val == hex { - return dst.entries[i].alg >= alg - } - return dst.entries[i].val >= hex - } - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) { - return "", ErrDigestNotFound - } - if dst.entries[idx].alg == alg && dst.entries[idx].val == hex { - return dst.entries[idx].digest, nil - } - if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) { - return "", ErrDigestAmbiguous - } - - return dst.entries[idx].digest, nil -} - -// Add adds the given digest to the set. An error will be returned -// if the given digest is invalid. If the digest already exists in the -// set, this operation will be a no-op. -func (dst *Set) Add(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) { - dst.entries = append(dst.entries, entry) - return nil - } else if dst.entries[idx].digest == d { - return nil - } - - entries := append(dst.entries, nil) - copy(entries[idx+1:], entries[idx:len(entries)-1]) - entries[idx] = entry - dst.entries = entries - return nil -} - -// Remove removes the given digest from the set. An err will be -// returned if the given digest is invalid. If the digest does -// not exist in the set, this operation will be a no-op. -func (dst *Set) Remove(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - // Not found if idx is after or value at idx is not digest - if idx == len(dst.entries) || dst.entries[idx].digest != d { - return nil - } - - entries := dst.entries - copy(entries[idx:], entries[idx+1:]) - entries = entries[:len(entries)-1] - dst.entries = entries - - return nil -} - -// All returns all the digests in the set -func (dst *Set) All() []digest.Digest { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - retValues := make([]digest.Digest, len(dst.entries)) - for i := range dst.entries { - retValues[i] = dst.entries[i].digest - } - - return retValues -} - -// ShortCodeTable returns a map of Digest to unique short codes. The -// length represents the minimum value, the maximum length may be the -// entire value of digest if uniqueness cannot be achieved without the -// full value. This function will attempt to make short codes as short -// as possible to be unique. -func ShortCodeTable(dst *Set, length int) map[digest.Digest]string { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - m := make(map[digest.Digest]string, len(dst.entries)) - l := length - resetIdx := 0 - for i := 0; i < len(dst.entries); i++ { - var short string - extended := true - for extended { - extended = false - if len(dst.entries[i].val) <= l { - short = dst.entries[i].digest.String() - } else { - short = dst.entries[i].val[:l] - for j := i + 1; j < len(dst.entries); j++ { - if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) { - if j > resetIdx { - resetIdx = j - } - extended = true - } else { - break - } - } - if extended { - l++ - } - } - } - m[dst.entries[i].digest] = short - if i >= resetIdx { - l = length - } - } - return m -} - -type digestEntry struct { - alg digest.Algorithm - val string - digest digest.Digest -} - -type digestEntries []*digestEntry - -func (d digestEntries) Len() int { - return len(d) -} - -func (d digestEntries) Less(i, j int) bool { - if d[i].val != d[j].val { - return d[i].val < d[j].val - } - return d[i].alg < d[j].alg -} - -func (d digestEntries) Swap(i, j int) { - d[i], d[j] = d[j], d[i] -} diff --git a/vendor/github.com/docker/distribution/reference/helpers.go b/vendor/github.com/docker/distribution/reference/helpers.go deleted file mode 100644 index 978df7eabb..0000000000 --- a/vendor/github.com/docker/distribution/reference/helpers.go +++ /dev/null @@ -1,42 +0,0 @@ -package reference - -import "path" - -// IsNameOnly returns true if reference only contains a repo name. -func IsNameOnly(ref Named) bool { - if _, ok := ref.(NamedTagged); ok { - return false - } - if _, ok := ref.(Canonical); ok { - return false - } - return true -} - -// FamiliarName returns the familiar name string -// for the given named, familiarizing if needed. -func FamiliarName(ref Named) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().Name() - } - return ref.Name() -} - -// FamiliarString returns the familiar string representation -// for the given reference, familiarizing if needed. -func FamiliarString(ref Reference) string { - if nn, ok := ref.(normalizedNamed); ok { - return nn.Familiar().String() - } - return ref.String() -} - -// FamiliarMatch reports whether ref matches the specified pattern. -// See https://godoc.org/path#Match for supported patterns. -func FamiliarMatch(pattern string, ref Reference) (bool, error) { - matched, err := path.Match(pattern, FamiliarString(ref)) - if namedRef, isNamed := ref.(Named); isNamed && !matched { - matched, _ = path.Match(pattern, FamiliarName(namedRef)) - } - return matched, err -} diff --git a/vendor/github.com/docker/distribution/reference/normalize.go b/vendor/github.com/docker/distribution/reference/normalize.go deleted file mode 100644 index 2d71fc5e9f..0000000000 --- a/vendor/github.com/docker/distribution/reference/normalize.go +++ /dev/null @@ -1,170 +0,0 @@ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/distribution/digestset" - "github.com/opencontainers/go-digest" -) - -var ( - legacyDefaultDomain = "index.docker.io" - defaultDomain = "docker.io" - officialRepoName = "library" - defaultTag = "latest" -) - -// normalizedNamed represents a name which has been -// normalized and has a familiar form. A familiar name -// is what is used in Docker UI. An example normalized -// name is "docker.io/library/ubuntu" and corresponding -// familiar name of "ubuntu". -type normalizedNamed interface { - Named - Familiar() Named -} - -// ParseNormalizedNamed parses a string into a named reference -// transforming a familiar name from Docker UI to a fully -// qualified reference. If the value may be an identifier -// use ParseAnyReference. -func ParseNormalizedNamed(s string) (Named, error) { - if ok := anchoredIdentifierRegexp.MatchString(s); ok { - return nil, fmt.Errorf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings", s) - } - domain, remainder := splitDockerDomain(s) - var remoteName string - if tagSep := strings.IndexRune(remainder, ':'); tagSep > -1 { - remoteName = remainder[:tagSep] - } else { - remoteName = remainder - } - if strings.ToLower(remoteName) != remoteName { - return nil, errors.New("invalid reference format: repository name must be lowercase") - } - - ref, err := Parse(domain + "/" + remainder) - if err != nil { - return nil, err - } - named, isNamed := ref.(Named) - if !isNamed { - return nil, fmt.Errorf("reference %s has no name", ref.String()) - } - return named, nil -} - -// splitDockerDomain splits a repository name to domain and remotename string. -// If no valid domain is found, the default domain is used. Repository name -// needs to be already validated before. -func splitDockerDomain(name string) (domain, remainder string) { - i := strings.IndexRune(name, '/') - if i == -1 || (!strings.ContainsAny(name[:i], ".:") && name[:i] != "localhost") { - domain, remainder = defaultDomain, name - } else { - domain, remainder = name[:i], name[i+1:] - } - if domain == legacyDefaultDomain { - domain = defaultDomain - } - if domain == defaultDomain && !strings.ContainsRune(remainder, '/') { - remainder = officialRepoName + "/" + remainder - } - return -} - -// familiarizeName returns a shortened version of the name familiar -// to to the Docker UI. Familiar names have the default domain -// "docker.io" and "library/" repository prefix removed. -// For example, "docker.io/library/redis" will have the familiar -// name "redis" and "docker.io/dmcgowan/myapp" will be "dmcgowan/myapp". -// Returns a familiarized named only reference. -func familiarizeName(named namedRepository) repository { - repo := repository{ - domain: named.Domain(), - path: named.Path(), - } - - if repo.domain == defaultDomain { - repo.domain = "" - // Handle official repositories which have the pattern "library/" - if split := strings.Split(repo.path, "/"); len(split) == 2 && split[0] == officialRepoName { - repo.path = split[1] - } - } - return repo -} - -func (r reference) Familiar() Named { - return reference{ - namedRepository: familiarizeName(r.namedRepository), - tag: r.tag, - digest: r.digest, - } -} - -func (r repository) Familiar() Named { - return familiarizeName(r) -} - -func (t taggedReference) Familiar() Named { - return taggedReference{ - namedRepository: familiarizeName(t.namedRepository), - tag: t.tag, - } -} - -func (c canonicalReference) Familiar() Named { - return canonicalReference{ - namedRepository: familiarizeName(c.namedRepository), - digest: c.digest, - } -} - -// TagNameOnly adds the default tag "latest" to a reference if it only has -// a repo name. -func TagNameOnly(ref Named) Named { - if IsNameOnly(ref) { - namedTagged, err := WithTag(ref, defaultTag) - if err != nil { - // Default tag must be valid, to create a NamedTagged - // type with non-validated input the WithTag function - // should be used instead - panic(err) - } - return namedTagged - } - return ref -} - -// ParseAnyReference parses a reference string as a possible identifier, -// full digest, or familiar name. -func ParseAnyReference(ref string) (Reference, error) { - if ok := anchoredIdentifierRegexp.MatchString(ref); ok { - return digestReference("sha256:" + ref), nil - } - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - - return ParseNormalizedNamed(ref) -} - -// ParseAnyReferenceWithSet parses a reference string as a possible short -// identifier to be matched in a digest set, a full digest, or familiar name. -func ParseAnyReferenceWithSet(ref string, ds *digestset.Set) (Reference, error) { - if ok := anchoredShortIdentifierRegexp.MatchString(ref); ok { - dgst, err := ds.Lookup(ref) - if err == nil { - return digestReference(dgst), nil - } - } else { - if dgst, err := digest.Parse(ref); err == nil { - return digestReference(dgst), nil - } - } - - return ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/reference.go b/vendor/github.com/docker/distribution/reference/reference.go deleted file mode 100644 index fd3510e9ee..0000000000 --- a/vendor/github.com/docker/distribution/reference/reference.go +++ /dev/null @@ -1,433 +0,0 @@ -// Package reference provides a general type to represent any way of referencing images within the registry. -// Its main purpose is to abstract tags and digests (content-addressable hash). -// -// Grammar -// -// reference := name [ ":" tag ] [ "@" digest ] -// name := [domain '/'] path-component ['/' path-component]* -// domain := domain-component ['.' domain-component]* [':' port-number] -// domain-component := /([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])/ -// port-number := /[0-9]+/ -// path-component := alpha-numeric [separator alpha-numeric]* -// alpha-numeric := /[a-z0-9]+/ -// separator := /[_.]|__|[-]*/ -// -// tag := /[\w][\w.-]{0,127}/ -// -// digest := digest-algorithm ":" digest-hex -// digest-algorithm := digest-algorithm-component [ digest-algorithm-separator digest-algorithm-component ] -// digest-algorithm-separator := /[+.-_]/ -// digest-algorithm-component := /[A-Za-z][A-Za-z0-9]*/ -// digest-hex := /[0-9a-fA-F]{32,}/ ; At least 128 bit digest value -// -// identifier := /[a-f0-9]{64}/ -// short-identifier := /[a-f0-9]{6,64}/ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/opencontainers/go-digest" -) - -const ( - // NameTotalLengthMax is the maximum total number of characters in a repository name. - NameTotalLengthMax = 255 -) - -var ( - // ErrReferenceInvalidFormat represents an error while trying to parse a string as a reference. - ErrReferenceInvalidFormat = errors.New("invalid reference format") - - // ErrTagInvalidFormat represents an error while trying to parse a string as a tag. - ErrTagInvalidFormat = errors.New("invalid tag format") - - // ErrDigestInvalidFormat represents an error while trying to parse a string as a tag. - ErrDigestInvalidFormat = errors.New("invalid digest format") - - // ErrNameContainsUppercase is returned for invalid repository names that contain uppercase characters. - ErrNameContainsUppercase = errors.New("repository name must be lowercase") - - // ErrNameEmpty is returned for empty, invalid repository names. - ErrNameEmpty = errors.New("repository name must have at least one component") - - // ErrNameTooLong is returned when a repository name is longer than NameTotalLengthMax. - ErrNameTooLong = fmt.Errorf("repository name must not be more than %v characters", NameTotalLengthMax) - - // ErrNameNotCanonical is returned when a name is not canonical. - ErrNameNotCanonical = errors.New("repository name must be canonical") -) - -// Reference is an opaque object reference identifier that may include -// modifiers such as a hostname, name, tag, and digest. -type Reference interface { - // String returns the full reference - String() string -} - -// Field provides a wrapper type for resolving correct reference types when -// working with encoding. -type Field struct { - reference Reference -} - -// AsField wraps a reference in a Field for encoding. -func AsField(reference Reference) Field { - return Field{reference} -} - -// Reference unwraps the reference type from the field to -// return the Reference object. This object should be -// of the appropriate type to further check for different -// reference types. -func (f Field) Reference() Reference { - return f.reference -} - -// MarshalText serializes the field to byte text which -// is the string of the reference. -func (f Field) MarshalText() (p []byte, err error) { - return []byte(f.reference.String()), nil -} - -// UnmarshalText parses text bytes by invoking the -// reference parser to ensure the appropriately -// typed reference object is wrapped by field. -func (f *Field) UnmarshalText(p []byte) error { - r, err := Parse(string(p)) - if err != nil { - return err - } - - f.reference = r - return nil -} - -// Named is an object with a full name -type Named interface { - Reference - Name() string -} - -// Tagged is an object which has a tag -type Tagged interface { - Reference - Tag() string -} - -// NamedTagged is an object including a name and tag. -type NamedTagged interface { - Named - Tag() string -} - -// Digested is an object which has a digest -// in which it can be referenced by -type Digested interface { - Reference - Digest() digest.Digest -} - -// Canonical reference is an object with a fully unique -// name including a name with domain and digest -type Canonical interface { - Named - Digest() digest.Digest -} - -// namedRepository is a reference to a repository with a name. -// A namedRepository has both domain and path components. -type namedRepository interface { - Named - Domain() string - Path() string -} - -// Domain returns the domain part of the Named reference -func Domain(named Named) string { - if r, ok := named.(namedRepository); ok { - return r.Domain() - } - domain, _ := splitDomain(named.Name()) - return domain -} - -// Path returns the name without the domain part of the Named reference -func Path(named Named) (name string) { - if r, ok := named.(namedRepository); ok { - return r.Path() - } - _, path := splitDomain(named.Name()) - return path -} - -func splitDomain(name string) (string, string) { - match := anchoredNameRegexp.FindStringSubmatch(name) - if len(match) != 3 { - return "", name - } - return match[1], match[2] -} - -// SplitHostname splits a named reference into a -// hostname and name string. If no valid hostname is -// found, the hostname is empty and the full value -// is returned as name -// DEPRECATED: Use Domain or Path -func SplitHostname(named Named) (string, string) { - if r, ok := named.(namedRepository); ok { - return r.Domain(), r.Path() - } - return splitDomain(named.Name()) -} - -// Parse parses s and returns a syntactically valid Reference. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: Parse will not handle short digests. -func Parse(s string) (Reference, error) { - matches := ReferenceRegexp.FindStringSubmatch(s) - if matches == nil { - if s == "" { - return nil, ErrNameEmpty - } - if ReferenceRegexp.FindStringSubmatch(strings.ToLower(s)) != nil { - return nil, ErrNameContainsUppercase - } - return nil, ErrReferenceInvalidFormat - } - - if len(matches[1]) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - var repo repository - - nameMatch := anchoredNameRegexp.FindStringSubmatch(matches[1]) - if nameMatch != nil && len(nameMatch) == 3 { - repo.domain = nameMatch[1] - repo.path = nameMatch[2] - } else { - repo.domain = "" - repo.path = matches[1] - } - - ref := reference{ - namedRepository: repo, - tag: matches[2], - } - if matches[3] != "" { - var err error - ref.digest, err = digest.Parse(matches[3]) - if err != nil { - return nil, err - } - } - - r := getBestReferenceType(ref) - if r == nil { - return nil, ErrNameEmpty - } - - return r, nil -} - -// ParseNamed parses s and returns a syntactically valid reference implementing -// the Named interface. The reference must have a name and be in the canonical -// form, otherwise an error is returned. -// If an error was encountered it is returned, along with a nil Reference. -// NOTE: ParseNamed will not handle short digests. -func ParseNamed(s string) (Named, error) { - named, err := ParseNormalizedNamed(s) - if err != nil { - return nil, err - } - if named.String() != s { - return nil, ErrNameNotCanonical - } - return named, nil -} - -// WithName returns a named object representing the given string. If the input -// is invalid ErrReferenceInvalidFormat will be returned. -func WithName(name string) (Named, error) { - if len(name) > NameTotalLengthMax { - return nil, ErrNameTooLong - } - - match := anchoredNameRegexp.FindStringSubmatch(name) - if match == nil || len(match) != 3 { - return nil, ErrReferenceInvalidFormat - } - return repository{ - domain: match[1], - path: match[2], - }, nil -} - -// WithTag combines the name from "name" and the tag from "tag" to form a -// reference incorporating both the name and the tag. -func WithTag(name Named, tag string) (NamedTagged, error) { - if !anchoredTagRegexp.MatchString(tag) { - return nil, ErrTagInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if canonical, ok := name.(Canonical); ok { - return reference{ - namedRepository: repo, - tag: tag, - digest: canonical.Digest(), - }, nil - } - return taggedReference{ - namedRepository: repo, - tag: tag, - }, nil -} - -// WithDigest combines the name from "name" and the digest from "digest" to form -// a reference incorporating both the name and the digest. -func WithDigest(name Named, digest digest.Digest) (Canonical, error) { - if !anchoredDigestRegexp.MatchString(digest.String()) { - return nil, ErrDigestInvalidFormat - } - var repo repository - if r, ok := name.(namedRepository); ok { - repo.domain = r.Domain() - repo.path = r.Path() - } else { - repo.path = name.Name() - } - if tagged, ok := name.(Tagged); ok { - return reference{ - namedRepository: repo, - tag: tagged.Tag(), - digest: digest, - }, nil - } - return canonicalReference{ - namedRepository: repo, - digest: digest, - }, nil -} - -// TrimNamed removes any tag or digest from the named reference. -func TrimNamed(ref Named) Named { - domain, path := SplitHostname(ref) - return repository{ - domain: domain, - path: path, - } -} - -func getBestReferenceType(ref reference) Reference { - if ref.Name() == "" { - // Allow digest only references - if ref.digest != "" { - return digestReference(ref.digest) - } - return nil - } - if ref.tag == "" { - if ref.digest != "" { - return canonicalReference{ - namedRepository: ref.namedRepository, - digest: ref.digest, - } - } - return ref.namedRepository - } - if ref.digest == "" { - return taggedReference{ - namedRepository: ref.namedRepository, - tag: ref.tag, - } - } - - return ref -} - -type reference struct { - namedRepository - tag string - digest digest.Digest -} - -func (r reference) String() string { - return r.Name() + ":" + r.tag + "@" + r.digest.String() -} - -func (r reference) Tag() string { - return r.tag -} - -func (r reference) Digest() digest.Digest { - return r.digest -} - -type repository struct { - domain string - path string -} - -func (r repository) String() string { - return r.Name() -} - -func (r repository) Name() string { - if r.domain == "" { - return r.path - } - return r.domain + "/" + r.path -} - -func (r repository) Domain() string { - return r.domain -} - -func (r repository) Path() string { - return r.path -} - -type digestReference digest.Digest - -func (d digestReference) String() string { - return digest.Digest(d).String() -} - -func (d digestReference) Digest() digest.Digest { - return digest.Digest(d) -} - -type taggedReference struct { - namedRepository - tag string -} - -func (t taggedReference) String() string { - return t.Name() + ":" + t.tag -} - -func (t taggedReference) Tag() string { - return t.tag -} - -type canonicalReference struct { - namedRepository - digest digest.Digest -} - -func (c canonicalReference) String() string { - return c.Name() + "@" + c.digest.String() -} - -func (c canonicalReference) Digest() digest.Digest { - return c.digest -} diff --git a/vendor/github.com/docker/distribution/reference/regexp.go b/vendor/github.com/docker/distribution/reference/regexp.go deleted file mode 100644 index 7860349320..0000000000 --- a/vendor/github.com/docker/distribution/reference/regexp.go +++ /dev/null @@ -1,143 +0,0 @@ -package reference - -import "regexp" - -var ( - // alphaNumericRegexp defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumericRegexp = match(`[a-z0-9]+`) - - // separatorRegexp defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. - separatorRegexp = match(`(?:[._]|__|[-]*)`) - - // nameComponentRegexp restricts registry path component names to start - // with at least one letter or number, with following parts able to be - // separated by one period, one or two underscore and multiple dashes. - nameComponentRegexp = expression( - alphaNumericRegexp, - optional(repeated(separatorRegexp, alphaNumericRegexp))) - - // domainComponentRegexp restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp - // and followed by an optional port. - domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])`) - - // DomainRegexp defines the structure of potential domain components - // that may be part of image names. This is purposely a subset of what is - // allowed by DNS to ensure backwards compatibility with Docker image - // names. - DomainRegexp = expression( - domainComponentRegexp, - optional(repeated(literal(`.`), domainComponentRegexp)), - optional(literal(`:`), match(`[0-9]+`))) - - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = match(`[\w][\w.-]{0,127}`) - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = anchored(TagRegexp) - - // DigestRegexp matches valid digests. - DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = anchored(DigestRegexp) - - // NameRegexp is the format for the name component of references. The - // regexp has capturing groups for the domain and name part omitting - // the separating forward slash from either. - NameRegexp = expression( - optional(DomainRegexp, literal(`/`)), - nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp))) - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = anchored( - optional(capture(DomainRegexp), literal(`/`)), - capture(nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp)))) - - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = anchored(capture(NameRegexp), - optional(literal(":"), capture(TagRegexp)), - optional(literal("@"), capture(DigestRegexp))) - - // IdentifierRegexp is the format for string identifier used as a - // content addressable identifier using sha256. These identifiers - // are like digests without the algorithm, since sha256 is used. - IdentifierRegexp = match(`([a-f0-9]{64})`) - - // ShortIdentifierRegexp is the format used to represent a prefix - // of an identifier. A prefix may be used to match a sha256 identifier - // within a list of trusted identifiers. - ShortIdentifierRegexp = match(`([a-f0-9]{6,64})`) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = anchored(IdentifierRegexp) - - // anchoredShortIdentifierRegexp is used to check if a value - // is a possible identifier prefix, anchored at start and end - // of string. - anchoredShortIdentifierRegexp = anchored(ShortIdentifierRegexp) -) - -// match compiles the string to a regular expression. -var match = regexp.MustCompile - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) *regexp.Regexp { - re := match(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...*regexp.Regexp) *regexp.Regexp { - var s string - for _, re := range res { - s += re.String() - } - - return match(s) -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `?`) -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `+`) -} - -// group wraps the regexp in a non-capturing group. -func group(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(?:` + expression(res...).String() + `)`) -} - -// capture wraps the expression in a capturing group. -func capture(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(` + expression(res...).String() + `)`) -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...*regexp.Regexp) *regexp.Regexp { - return match(`^` + expression(res...).String() + `$`) -} diff --git a/vendor/github.com/docker/docker/LICENSE b/vendor/github.com/docker/docker/LICENSE deleted file mode 100644 index 9c8e20ab85..0000000000 --- a/vendor/github.com/docker/docker/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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. - - END OF TERMS AND CONDITIONS - - Copyright 2013-2017 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/docker/docker/NOTICE b/vendor/github.com/docker/docker/NOTICE deleted file mode 100644 index 0c74e15b05..0000000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/kr/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/api/README.md b/vendor/github.com/docker/docker/api/README.md deleted file mode 100644 index 8954ed0174..0000000000 --- a/vendor/github.com/docker/docker/api/README.md +++ /dev/null @@ -1,42 +0,0 @@ -# Working on the Engine API - -The Engine API is an HTTP API used by the command-line client to communicate with the daemon. It can also be used by third-party software to control the daemon. - -It consists of various components in this repository: - -- `api/swagger.yaml` A Swagger definition of the API. -- `api/types/` Types shared by both the client and server, representing various objects, options, responses, etc. Most are written manually, but some are automatically generated from the Swagger definition. See [#27919](https://github.com/docker/docker/issues/27919) for progress on this. -- `cli/` The command-line client. -- `client/` The Go client used by the command-line client. It can also be used by third-party Go programs. -- `daemon/` The daemon, which serves the API. - -## Swagger definition - -The API is defined by the [Swagger](http://swagger.io/specification/) definition in `api/swagger.yaml`. This definition can be used to: - -1. To automatically generate documentation. -2. To automatically generate the Go server and client. (A work-in-progress.) -3. Provide a machine readable version of the API for introspecting what it can do, automatically generating clients for other languages, etc. - -## Updating the API documentation - -The API documentation is generated entirely from `api/swagger.yaml`. If you make updates to the API, you'll need to edit this file to represent the change in the documentation. - -The file is split into two main sections: - -- `definitions`, which defines re-usable objects used in requests and responses -- `paths`, which defines the API endpoints (and some inline objects which don't need to be reusable) - -To make an edit, first look for the endpoint you want to edit under `paths`, then make the required edits. Endpoints may reference reusable objects with `$ref`, which can be found in the `definitions` section. - -There is hopefully enough example material in the file for you to copy a similar pattern from elsewhere in the file (e.g. adding new fields or endpoints), but for the full reference, see the [Swagger specification](https://github.com/docker/docker/issues/27919) - -`swagger.yaml` is validated by `hack/validate/swagger` to ensure it is a valid Swagger definition. This is useful for when you are making edits to ensure you are doing the right thing. - -## Viewing the API documentation - -When you make edits to `swagger.yaml`, you may want to check the generated API documentation to ensure it renders correctly. - -Run `make swagger-docs` and a preview will be running at `http://localhost`. Some of the styling may be incorrect, but you'll be able to ensure that it is generating the correct documentation. - -The production documentation is generated by vendoring `swagger.yaml` into [docker/docker.github.io](https://github.com/docker/docker.github.io). diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go deleted file mode 100644 index 9df6255c08..0000000000 --- a/vendor/github.com/docker/docker/api/common.go +++ /dev/null @@ -1,166 +0,0 @@ -package api - -import ( - "encoding/json" - "encoding/pem" - "fmt" - "mime" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - - "github.com/Sirupsen/logrus" - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/system" - "github.com/docker/libtrust" -) - -// Common constants for daemon and client. -const ( - // DefaultVersion of Current REST API - DefaultVersion string = "1.30" - - // NoBaseImageSpecifier is the symbol used by the FROM - // command to specify that no base image is to be used. - NoBaseImageSpecifier string = "scratch" -) - -// byPortInfo is a temporary type used to sort types.Port by its fields -type byPortInfo []types.Port - -func (r byPortInfo) Len() int { return len(r) } -func (r byPortInfo) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r byPortInfo) Less(i, j int) bool { - if r[i].PrivatePort != r[j].PrivatePort { - return r[i].PrivatePort < r[j].PrivatePort - } - - if r[i].IP != r[j].IP { - return r[i].IP < r[j].IP - } - - if r[i].PublicPort != r[j].PublicPort { - return r[i].PublicPort < r[j].PublicPort - } - - return r[i].Type < r[j].Type -} - -// DisplayablePorts returns formatted string representing open ports of container -// e.g. "0.0.0.0:80->9090/tcp, 9988/tcp" -// it's used by command 'docker ps' -func DisplayablePorts(ports []types.Port) string { - type portGroup struct { - first uint16 - last uint16 - } - groupMap := make(map[string]*portGroup) - var result []string - var hostMappings []string - var groupMapKeys []string - sort.Sort(byPortInfo(ports)) - for _, port := range ports { - current := port.PrivatePort - portKey := port.Type - if port.IP != "" { - if port.PublicPort != current { - hostMappings = append(hostMappings, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type)) - continue - } - portKey = fmt.Sprintf("%s/%s", port.IP, port.Type) - } - group := groupMap[portKey] - - if group == nil { - groupMap[portKey] = &portGroup{first: current, last: current} - // record order that groupMap keys are created - groupMapKeys = append(groupMapKeys, portKey) - continue - } - if current == (group.last + 1) { - group.last = current - continue - } - - result = append(result, formGroup(portKey, group.first, group.last)) - groupMap[portKey] = &portGroup{first: current, last: current} - } - for _, portKey := range groupMapKeys { - g := groupMap[portKey] - result = append(result, formGroup(portKey, g.first, g.last)) - } - result = append(result, hostMappings...) - return strings.Join(result, ", ") -} - -func formGroup(key string, start, last uint16) string { - parts := strings.Split(key, "/") - groupType := parts[0] - var ip string - if len(parts) > 1 { - ip = parts[0] - groupType = parts[1] - } - group := strconv.Itoa(int(start)) - if start != last { - group = fmt.Sprintf("%s-%d", group, last) - } - if ip != "" { - group = fmt.Sprintf("%s:%s->%s", ip, group, group) - } - return fmt.Sprintf("%s/%s", group, groupType) -} - -// MatchesContentType validates the content type against the expected one -func MatchesContentType(contentType, expectedType string) bool { - mimetype, _, err := mime.ParseMediaType(contentType) - if err != nil { - logrus.Errorf("Error parsing media type: %s error: %v", contentType, err) - } - return err == nil && mimetype == expectedType -} - -// LoadOrCreateTrustKey attempts to load the libtrust key at the given path, -// otherwise generates a new one -func LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) { - err := system.MkdirAll(filepath.Dir(trustKeyPath), 0700) - if err != nil { - return nil, err - } - trustKey, err := libtrust.LoadKeyFile(trustKeyPath) - if err == libtrust.ErrKeyFileDoesNotExist { - trustKey, err = libtrust.GenerateECP256PrivateKey() - if err != nil { - return nil, fmt.Errorf("Error generating key: %s", err) - } - encodedKey, err := serializePrivateKey(trustKey, filepath.Ext(trustKeyPath)) - if err != nil { - return nil, fmt.Errorf("Error serializing key: %s", err) - } - if err := ioutils.AtomicWriteFile(trustKeyPath, encodedKey, os.FileMode(0600)); err != nil { - return nil, fmt.Errorf("Error saving key file: %s", err) - } - } else if err != nil { - return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err) - } - return trustKey, nil -} - -func serializePrivateKey(key libtrust.PrivateKey, ext string) (encoded []byte, err error) { - if ext == ".json" || ext == ".jwk" { - encoded, err = json.Marshal(key) - if err != nil { - return nil, fmt.Errorf("unable to encode private key JWK: %s", err) - } - } else { - pemBlock, err := key.PEMBlock() - if err != nil { - return nil, fmt.Errorf("unable to encode private key PEM: %s", err) - } - encoded = pem.EncodeToMemory(pemBlock) - } - return -} diff --git a/vendor/github.com/docker/docker/api/common_unix.go b/vendor/github.com/docker/docker/api/common_unix.go deleted file mode 100644 index 081e61c451..0000000000 --- a/vendor/github.com/docker/docker/api/common_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !windows - -package api - -// MinVersion represents Minimum REST API version supported -const MinVersion string = "1.12" diff --git a/vendor/github.com/docker/docker/api/common_windows.go b/vendor/github.com/docker/docker/api/common_windows.go deleted file mode 100644 index a6268a4ff7..0000000000 --- a/vendor/github.com/docker/docker/api/common_windows.go +++ /dev/null @@ -1,8 +0,0 @@ -package api - -// MinVersion represents Minimum REST API version supported -// Technically the first daemon API version released on Windows is v1.25 in -// engine version 1.13. However, some clients are explicitly using downlevel -// APIs (e.g. docker-compose v2.1 file format) and that is just too restrictive. -// Hence also allowing 1.24 on Windows. -const MinVersion string = "1.24" diff --git a/vendor/github.com/docker/docker/api/names.go b/vendor/github.com/docker/docker/api/names.go deleted file mode 100644 index f147d1f4ce..0000000000 --- a/vendor/github.com/docker/docker/api/names.go +++ /dev/null @@ -1,9 +0,0 @@ -package api - -import "regexp" - -// RestrictedNameChars collects the characters allowed to represent a name, normally used to validate container and volume names. -const RestrictedNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]` - -// RestrictedNamePattern is a regular expression to validate names against the collection of restricted characters. -var RestrictedNamePattern = regexp.MustCompile(`^` + RestrictedNameChars + `+$`) diff --git a/vendor/github.com/docker/docker/api/swagger-gen.yaml b/vendor/github.com/docker/docker/api/swagger-gen.yaml deleted file mode 100644 index f07a02737f..0000000000 --- a/vendor/github.com/docker/docker/api/swagger-gen.yaml +++ /dev/null @@ -1,12 +0,0 @@ - -layout: - models: - - name: definition - source: asset:model - target: "{{ joinFilePath .Target .ModelPackage }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" - operations: - - name: handler - source: asset:serverOperation - target: "{{ joinFilePath .Target .APIPackage .Package }}" - file_name: "{{ (snakize (pascalize .Name)) }}.go" diff --git a/vendor/github.com/docker/docker/api/swagger.yaml b/vendor/github.com/docker/docker/api/swagger.yaml deleted file mode 100644 index 01f9d5d233..0000000000 --- a/vendor/github.com/docker/docker/api/swagger.yaml +++ /dev/null @@ -1,8265 +0,0 @@ -# A Swagger 2.0 (a.k.a. OpenAPI) definition of the Engine API. -# -# This is used for generating API documentation and the types used by the -# client/server. See api/README.md for more information. -# -# Some style notes: -# - This file is used by ReDoc, which allows GitHub Flavored Markdown in -# descriptions. -# - There is no maximum line length, for ease of editing and pretty diffs. -# - operationIds are in the format "NounVerb", with a singular noun. - -swagger: "2.0" -schemes: - - "http" - - "https" -produces: - - "application/json" - - "text/plain" -consumes: - - "application/json" - - "text/plain" -basePath: "/v1.30" -info: - title: "Docker Engine API" - version: "1.30" - x-logo: - url: "https://docs.docker.com/images/logo-docker-main.png" - description: | - The Engine API is an HTTP API served by Docker Engine. It is the API the Docker client uses to communicate with the Engine, so everything the Docker client can do can be done with the API. - - Most of the client's commands map directly to API endpoints (e.g. `docker ps` is `GET /containers/json`). The notable exception is running containers, which consists of several API calls. - - # Errors - - The API uses standard HTTP status codes to indicate the success or failure of the API call. The body of the response will be JSON in the following format: - - ``` - { - "message": "page not found" - } - ``` - - # Versioning - - The API is usually changed in each release of Docker, so API calls are versioned to ensure that clients don't break. - - For Docker Engine 17.06, the API version is 1.30. To lock to this version, you prefix the URL with `/v1.30`. For example, calling `/info` is the same as calling `/v1.30/info`. - - Engine releases in the near future should support this version of the API, so your client will continue to work even if it is talking to a newer Engine. - - In previous versions of Docker, it was possible to access the API without providing a version. This behaviour is now deprecated will be removed in a future version of Docker. - - The API uses an open schema model, which means server may add extra properties to responses. Likewise, the server will ignore any extra query parameters and request body properties. When you write clients, you need to ignore additional properties in responses to ensure they do not break when talking to newer Docker daemons. - - This documentation is for version 1.30 of the API, which was introduced with Docker 17.06. Use this table to find documentation for previous versions of the API: - - Docker version | API version | Changes - ----------------|-------------|--------- - 17.05.x | [1.29](https://docs.docker.com/engine/api/v1.29/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-29-api-changes) - 17.04.x | [1.28](https://docs.docker.com/engine/api/v1.28/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-28-api-changes) - 17.03.1 | [1.27](https://docs.docker.com/engine/api/v1.27/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-27-api-changes) - 1.13.1 & 17.03.0 | [1.26](https://docs.docker.com/engine/api/v1.26/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-26-api-changes) - 1.13.0 | [1.25](https://docs.docker.com/engine/api/v1.25/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-25-api-changes) - 1.12.x | [1.24](https://docs.docker.com/engine/api/v1.24/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-24-api-changes) - 1.11.x | [1.23](https://docs.docker.com/engine/api/v1.23/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-23-api-changes) - 1.10.x | [1.22](https://docs.docker.com/engine/api/v1.22/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-22-api-changes) - 1.9.x | [1.21](https://docs.docker.com/engine/api/v1.21/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-21-api-changes) - 1.8.x | [1.20](https://docs.docker.com/engine/api/v1.20/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-20-api-changes) - 1.7.x | [1.19](https://docs.docker.com/engine/api/v1.19/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-19-api-changes) - 1.6.x | [1.18](https://docs.docker.com/engine/api/v1.18/) | [API changes](https://docs.docker.com/engine/api/version-history/#v1-18-api-changes) - - # Authentication - - Authentication for registries is handled client side. The client has to send authentication details to various endpoints that need to communicate with registries, such as `POST /images/(name)/push`. These are sent as `X-Registry-Auth` header as a Base64 encoded (JSON) string with the following structure: - - ``` - { - "username": "string", - "password": "string", - "email": "string", - "serveraddress": "string" - } - ``` - - The `serveraddress` is a domain/IP without a protocol. Throughout this structure, double quotes are required. - - If you have already got an identity token from the [`/auth` endpoint](#operation/SystemAuth), you can just pass this instead of credentials: - - ``` - { - "identitytoken": "9cbaf023786cd7..." - } - ``` - -# The tags on paths define the menu sections in the ReDoc documentation, so -# the usage of tags must make sense for that: -# - They should be singular, not plural. -# - There should not be too many tags, or the menu becomes unwieldy. For -# example, it is preferable to add a path to the "System" tag instead of -# creating a tag with a single path in it. -# - The order of tags in this list defines the order in the menu. -tags: - # Primary objects - - name: "Container" - x-displayName: "Containers" - description: | - Create and manage containers. - - name: "Image" - x-displayName: "Images" - - name: "Network" - x-displayName: "Networks" - description: | - Networks are user-defined networks that containers can be attached to. See the [networking documentation](https://docs.docker.com/engine/userguide/networking/) for more information. - - name: "Volume" - x-displayName: "Volumes" - description: | - Create and manage persistent storage that can be attached to containers. - - name: "Exec" - x-displayName: "Exec" - description: | - Run new commands inside running containers. See the [command-line reference](https://docs.docker.com/engine/reference/commandline/exec/) for more information. - - To exec a command in a container, you first need to create an exec instance, then start it. These two API endpoints are wrapped up in a single command-line command, `docker exec`. - # Swarm things - - name: "Swarm" - x-displayName: "Swarm" - description: | - Engines can be clustered together in a swarm. See [the swarm mode documentation](https://docs.docker.com/engine/swarm/) for more information. - - name: "Node" - x-displayName: "Nodes" - description: | - Nodes are instances of the Engine participating in a swarm. Swarm mode must be enabled for these endpoints to work. - - name: "Service" - x-displayName: "Services" - description: | - Services are the definitions of tasks to run on a swarm. Swarm mode must be enabled for these endpoints to work. - - name: "Task" - x-displayName: "Tasks" - description: | - A task is a container running on a swarm. It is the atomic scheduling unit of swarm. Swarm mode must be enabled for these endpoints to work. - - name: "Secret" - x-displayName: "Secrets" - description: | - Secrets are sensitive data that can be used by services. Swarm mode must be enabled for these endpoints to work. - # System things - - name: "Plugin" - x-displayName: "Plugins" - - name: "System" - x-displayName: "System" - -definitions: - Port: - type: "object" - description: "An open port on a container" - required: [PrivatePort, Type] - properties: - IP: - type: "string" - format: "ip-address" - PrivatePort: - type: "integer" - format: "uint16" - x-nullable: false - description: "Port on the container" - PublicPort: - type: "integer" - format: "uint16" - description: "Port exposed on the host" - Type: - type: "string" - x-nullable: false - enum: ["tcp", "udp"] - example: - PrivatePort: 8080 - PublicPort: 80 - Type: "tcp" - - MountPoint: - type: "object" - description: "A mount point inside a container" - properties: - Type: - type: "string" - Name: - type: "string" - Source: - type: "string" - Destination: - type: "string" - Driver: - type: "string" - Mode: - type: "string" - RW: - type: "boolean" - Propagation: - type: "string" - - DeviceMapping: - type: "object" - description: "A device mapping between the host and container" - properties: - PathOnHost: - type: "string" - PathInContainer: - type: "string" - CgroupPermissions: - type: "string" - example: - PathOnHost: "/dev/deviceName" - PathInContainer: "/dev/deviceName" - CgroupPermissions: "mrw" - - ThrottleDevice: - type: "object" - properties: - Path: - description: "Device path" - type: "string" - Rate: - description: "Rate" - type: "integer" - format: "int64" - minimum: 0 - - Mount: - type: "object" - properties: - Target: - description: "Container path." - type: "string" - Source: - description: "Mount source (e.g. a volume name, a host path)." - Type: - description: | - The mount type. Available types: - - - `bind` Mounts a file or directory from the host into the container. Must exist prior to creating the container. - - `volume` Creates a volume with the given name and options (or uses a pre-existing volume with the same name and options). These are **not** removed when the container is removed. - - `tmpfs` Create a tmpfs with the given options. The mount source cannot be specified for tmpfs. - type: "string" - enum: - - "bind" - - "volume" - - "tmpfs" - ReadOnly: - description: "Whether the mount should be read-only." - type: "boolean" - Consistency: - description: "The consistency requirement for the mount: `default`, `consistent`, `cached`, or `delegated`." - type: "string" - BindOptions: - description: "Optional configuration for the `bind` type." - type: "object" - properties: - Propagation: - description: "A propagation mode with the value `[r]private`, `[r]shared`, or `[r]slave`." - enum: - - "private" - - "rprivate" - - "shared" - - "rshared" - - "slave" - - "rslave" - VolumeOptions: - description: "Optional configuration for the `volume` type." - type: "object" - properties: - NoCopy: - description: "Populate volume with data from the target." - type: "boolean" - default: false - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - DriverConfig: - description: "Map of driver specific options" - type: "object" - properties: - Name: - description: "Name of the driver to use to create the volume." - type: "string" - Options: - description: "key/value map of driver specific options." - type: "object" - additionalProperties: - type: "string" - TmpfsOptions: - description: "Optional configuration for the `tmpfs` type." - type: "object" - properties: - SizeBytes: - description: "The size for the tmpfs mount in bytes." - type: "integer" - format: "int64" - Mode: - description: "The permission mode for the tmpfs mount in an integer." - type: "integer" - RestartPolicy: - description: | - The behavior to apply when the container exits. The default is not to restart. - - An ever increasing delay (double the previous delay, starting at 100ms) is added before each restart to prevent flooding the server. - type: "object" - properties: - Name: - type: "string" - description: | - - `always` Always restart - - `unless-stopped` Restart always except when the user has manually stopped the container - - `on-failure` Restart only when the container exit code is non-zero - enum: - - "always" - - "unless-stopped" - - "on-failure" - MaximumRetryCount: - type: "integer" - description: "If `on-failure` is used, the number of times to retry before giving up" - default: {} - - Resources: - description: "A container's resources (cgroups config, ulimits, etc)" - type: "object" - properties: - # Applicable to all platforms - CpuShares: - description: "An integer value representing this container's relative CPU weight versus other containers." - type: "integer" - Memory: - description: "Memory limit in bytes." - type: "integer" - default: 0 - # Applicable to UNIX platforms - CgroupParent: - description: "Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute, the path is considered to be relative to the `cgroups` path of the init process. Cgroups are created if they do not already exist." - type: "string" - BlkioWeight: - description: "Block IO weight (relative weight)." - type: "integer" - minimum: 0 - maximum: 1000 - BlkioWeightDevice: - description: | - Block IO weight (relative device weight) in the form `[{"Path": "device_path", "Weight": weight}]`. - type: "array" - items: - type: "object" - properties: - Path: - type: "string" - Weight: - type: "integer" - minimum: 0 - BlkioDeviceReadBps: - description: | - Limit read rate (bytes per second) from a device, in the form `[{"Path": "device_path", "Rate": rate}]`. - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteBps: - description: | - Limit write rate (bytes per second) to a device, in the form `[{"Path": "device_path", "Rate": rate}]`. - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceReadIOps: - description: | - Limit read rate (IO per second) from a device, in the form `[{"Path": "device_path", "Rate": rate}]`. - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - BlkioDeviceWriteIOps: - description: | - Limit write rate (IO per second) to a device, in the form `[{"Path": "device_path", "Rate": rate}]`. - type: "array" - items: - $ref: "#/definitions/ThrottleDevice" - CpuPeriod: - description: "The length of a CPU period in microseconds." - type: "integer" - format: "int64" - CpuQuota: - description: "Microseconds of CPU time that the container can get in a CPU period." - type: "integer" - format: "int64" - CpuRealtimePeriod: - description: "The length of a CPU real-time period in microseconds. Set to 0 to allocate no time allocated to real-time tasks." - type: "integer" - format: "int64" - CpuRealtimeRuntime: - description: "The length of a CPU real-time runtime in microseconds. Set to 0 to allocate no time allocated to real-time tasks." - type: "integer" - format: "int64" - CpusetCpus: - description: "CPUs in which to allow execution (e.g., `0-3`, `0,1`)" - type: "string" - CpusetMems: - description: "Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems." - type: "string" - Devices: - description: "A list of devices to add to the container." - type: "array" - items: - $ref: "#/definitions/DeviceMapping" - DeviceCgroupRules: - description: "a list of cgroup rules to apply to the container" - type: "array" - items: - type: "string" - example: "c 13:* rwm" - DiskQuota: - description: "Disk limit (in bytes)." - type: "integer" - format: "int64" - KernelMemory: - description: "Kernel memory limit in bytes." - type: "integer" - format: "int64" - MemoryReservation: - description: "Memory soft limit in bytes." - type: "integer" - format: "int64" - MemorySwap: - description: "Total memory limit (memory + swap). Set as `-1` to enable unlimited swap." - type: "integer" - format: "int64" - MemorySwappiness: - description: "Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100." - type: "integer" - format: "int64" - minimum: 0 - maximum: 100 - NanoCPUs: - description: "CPU quota in units of 10-9 CPUs." - type: "integer" - format: "int64" - OomKillDisable: - description: "Disable OOM Killer for the container." - type: "boolean" - PidsLimit: - description: "Tune a container's pids limit. Set -1 for unlimited." - type: "integer" - format: "int64" - Ulimits: - description: | - A list of resource limits to set in the container. For example: `{"Name": "nofile", "Soft": 1024, "Hard": 2048}`" - type: "array" - items: - type: "object" - properties: - Name: - description: "Name of ulimit" - type: "string" - Soft: - description: "Soft limit" - type: "integer" - Hard: - description: "Hard limit" - type: "integer" - # Applicable to Windows - CpuCount: - description: | - The number of usable CPUs (Windows only). - - On Windows Server containers, the processor resource controls are mutually exclusive. The order of precedence is `CPUCount` first, then `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - CpuPercent: - description: | - The usable percentage of the available CPUs (Windows only). - - On Windows Server containers, the processor resource controls are mutually exclusive. The order of precedence is `CPUCount` first, then `CPUShares`, and `CPUPercent` last. - type: "integer" - format: "int64" - IOMaximumIOps: - description: "Maximum IOps for the container system drive (Windows only)" - type: "integer" - format: "int64" - IOMaximumBandwidth: - description: "Maximum IO in bytes per second for the container system drive (Windows only)" - type: "integer" - format: "int64" - - HealthConfig: - description: "A test to perform to check that the container is healthy." - type: "object" - properties: - Test: - description: | - The test to perform. Possible values are: - - - `[]` inherit healthcheck from image or parent image - - `["NONE"]` disable healthcheck - - `["CMD", args...]` exec arguments directly - - `["CMD-SHELL", command]` run command with system's default shell - type: "array" - items: - type: "string" - Interval: - description: "The time to wait between checks in nanoseconds. It should be 0 or not less than 1000000000(1s). 0 means inherit." - type: "integer" - Timeout: - description: "The time to wait before considering the check to have hung. It should be 0 or not less than 1000000000(1s). 0 means inherit." - type: "integer" - Retries: - description: "The number of consecutive failures needed to consider a container as unhealthy. 0 means inherit." - type: "integer" - StartPeriod: - description: "Start period for the container to initialize before starting health-retries countdown in nanoseconds. 0 means inherit." - type: "integer" - - HostConfig: - description: "Container configuration that depends on the host we are running on" - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - # Applicable to all platforms - Binds: - type: "array" - description: | - A list of volume bindings for this container. Each volume binding is a string in one of these forms: - - - `host-src:container-dest` to bind-mount a host path into the container. Both `host-src`, and `container-dest` must be an _absolute_ path. - - `host-src:container-dest:ro` to make the bind-mount read-only inside the container. Both `host-src`, and `container-dest` must be an _absolute_ path. - - `volume-name:container-dest` to bind-mount a volume managed by a volume driver into the container. `container-dest` must be an _absolute_ path. - - `volume-name:container-dest:ro` to mount the volume read-only inside the container. `container-dest` must be an _absolute_ path. - items: - type: "string" - ContainerIDFile: - type: "string" - description: "Path to a file where the container ID is written" - LogConfig: - type: "object" - description: "The logging configuration for this container" - properties: - Type: - type: "string" - enum: - - "json-file" - - "syslog" - - "journald" - - "gelf" - - "fluentd" - - "awslogs" - - "splunk" - - "etwlogs" - - "none" - Config: - type: "object" - additionalProperties: - type: "string" - NetworkMode: - type: "string" - description: "Network mode to use for this container. Supported standard values are: `bridge`, `host`, `none`, and `container:`. Any other value is taken - as a custom network's name to which this container should connect to." - PortBindings: - type: "object" - description: "A map of exposed container ports and the host port they should map to." - additionalProperties: - type: "object" - properties: - HostIp: - type: "string" - description: "The host IP address" - HostPort: - type: "string" - description: "The host port number, as a string" - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - AutoRemove: - type: "boolean" - description: "Automatically remove the container when the container's process exits. This has no effect if `RestartPolicy` is set." - VolumeDriver: - type: "string" - description: "Driver that this container uses to mount volumes." - VolumesFrom: - type: "array" - description: "A list of volumes to inherit from another container, specified in the form `[:]`." - items: - type: "string" - Mounts: - description: "Specification for mounts to be added to the container." - type: "array" - items: - $ref: "#/definitions/Mount" - - # Applicable to UNIX platforms - CapAdd: - type: "array" - description: "A list of kernel capabilities to add to the container." - items: - type: "string" - CapDrop: - type: "array" - description: "A list of kernel capabilities to drop from the container." - items: - type: "string" - Dns: - type: "array" - description: "A list of DNS servers for the container to use." - items: - type: "string" - DnsOptions: - type: "array" - description: "A list of DNS options." - items: - type: "string" - DnsSearch: - type: "array" - description: "A list of DNS search domains." - items: - type: "string" - ExtraHosts: - type: "array" - description: | - A list of hostnames/IP mappings to add to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - items: - type: "string" - GroupAdd: - type: "array" - description: "A list of additional groups that the container process will run as." - items: - type: "string" - IpcMode: - type: "string" - description: "IPC namespace to use for the container." - Cgroup: - type: "string" - description: "Cgroup to use for the container." - Links: - type: "array" - description: "A list of links for the container in the form `container_name:alias`." - items: - type: "string" - OomScoreAdj: - type: "integer" - description: "An integer value containing the score given to the container in order to tune OOM killer preferences." - PidMode: - type: "string" - description: | - Set the PID (Process) Namespace mode for the container. It can be either: - - - `"container:"`: joins another container's PID namespace - - `"host"`: use the host's PID namespace inside the container - Privileged: - type: "boolean" - description: "Gives the container full access to the host." - PublishAllPorts: - type: "boolean" - description: "Allocates a random host port for all of a container's exposed ports." - ReadonlyRootfs: - type: "boolean" - description: "Mount the container's root filesystem as read only." - SecurityOpt: - type: "array" - description: "A list of string values to customize labels for MLS - systems, such as SELinux." - items: - type: "string" - StorageOpt: - type: "object" - description: | - Storage driver options for this container, in the form `{"size": "120G"}`. - additionalProperties: - type: "string" - Tmpfs: - type: "object" - description: | - A map of container directories which should be replaced by tmpfs mounts, and their corresponding mount options. For example: `{ "/run": "rw,noexec,nosuid,size=65536k" }`. - additionalProperties: - type: "string" - UTSMode: - type: "string" - description: "UTS namespace to use for the container." - UsernsMode: - type: "string" - description: "Sets the usernamespace mode for the container when usernamespace remapping option is enabled." - ShmSize: - type: "integer" - description: "Size of `/dev/shm` in bytes. If omitted, the system uses 64MB." - minimum: 0 - Sysctls: - type: "object" - description: | - A list of kernel parameters (sysctls) to set in the container. For example: `{"net.ipv4.ip_forward": "1"}` - additionalProperties: - type: "string" - Runtime: - type: "string" - description: "Runtime to use with this container." - # Applicable to Windows - ConsoleSize: - type: "array" - description: "Initial console size, as an `[height, width]` array. (Windows only)" - minItems: 2 - maxItems: 2 - items: - type: "integer" - minimum: 0 - Isolation: - type: "string" - description: "Isolation technology of the container. (Windows only)" - enum: - - "default" - - "process" - - "hyperv" - - Config: - description: "Configuration for a container that is portable between hosts" - type: "object" - properties: - Hostname: - description: "The hostname to use for the container, as a valid RFC 1123 hostname." - type: "string" - Domainname: - description: "The domain name to use for the container." - type: "string" - User: - description: "The user that commands are run as inside the container." - type: "string" - AttachStdin: - description: "Whether to attach to `stdin`." - type: "boolean" - default: false - AttachStdout: - description: "Whether to attach to `stdout`." - type: "boolean" - default: true - AttachStderr: - description: "Whether to attach to `stderr`." - type: "boolean" - default: true - ExposedPorts: - description: | - An object mapping ports to an empty object in the form: - - `{"/": {}}` - type: "object" - additionalProperties: - type: "object" - enum: - - {} - default: {} - Tty: - description: "Attach standard streams to a TTY, including `stdin` if it is not closed." - type: "boolean" - default: false - OpenStdin: - description: "Open `stdin`" - type: "boolean" - default: false - StdinOnce: - description: "Close `stdin` after one attached client disconnects" - type: "boolean" - default: false - Env: - description: | - A list of environment variables to set inside the container in the form `["VAR=value", ...]`. A variable without `=` is removed from the environment, rather than to have an empty value. - type: "array" - items: - type: "string" - Cmd: - description: "Command to run specified as a string or an array of strings." - type: - - "array" - - "string" - items: - type: "string" - Healthcheck: - $ref: "#/definitions/HealthConfig" - ArgsEscaped: - description: "Command is already escaped (Windows only)" - type: "boolean" - Image: - description: "The name of the image to use when creating the container" - type: "string" - Volumes: - description: "An object mapping mount point paths inside the container to empty objects." - type: "object" - properties: - additionalProperties: - type: "object" - enum: - - {} - default: {} - WorkingDir: - description: "The working directory for commands to run in." - type: "string" - Entrypoint: - description: | - The entry point for the container as a string or an array of strings. - - If the array consists of exactly one empty string (`[""]`) then the entry point is reset to system default (i.e., the entry point used by docker when there is no `ENTRYPOINT` instruction in the `Dockerfile`). - type: - - "array" - - "string" - items: - type: "string" - NetworkDisabled: - description: "Disable networking for the container." - type: "boolean" - MacAddress: - description: "MAC address of the container." - type: "string" - OnBuild: - description: "`ONBUILD` metadata that were defined in the image's `Dockerfile`." - type: "array" - items: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - StopSignal: - description: "Signal to stop a container as a string or unsigned integer." - type: "string" - default: "SIGTERM" - StopTimeout: - description: "Timeout to stop a container in seconds." - type: "integer" - default: 10 - Shell: - description: "Shell for when `RUN`, `CMD`, and `ENTRYPOINT` uses a shell." - type: "array" - items: - type: "string" - - NetworkConfig: - description: "TODO: check is correct" - type: "object" - properties: - Bridge: - type: "string" - Gateway: - type: "string" - Address: - type: "string" - IPPrefixLen: - type: "integer" - MacAddress: - type: "string" - PortMapping: - type: "string" - Ports: - type: "array" - items: - $ref: "#/definitions/Port" - - GraphDriverData: - description: "Information about a container's graph driver." - type: "object" - required: [Name, Data] - properties: - Name: - type: "string" - x-nullable: false - Data: - type: "object" - x-nullable: false - additionalProperties: - type: "string" - - Image: - type: "object" - required: - - Id - - Parent - - Comment - - Created - - Container - - DockerVersion - - Author - - Architecture - - Os - - Size - - VirtualSize - - GraphDriver - - RootFS - properties: - Id: - type: "string" - x-nullable: false - RepoTags: - type: "array" - items: - type: "string" - RepoDigests: - type: "array" - items: - type: "string" - Parent: - type: "string" - x-nullable: false - Comment: - type: "string" - x-nullable: false - Created: - type: "string" - x-nullable: false - Container: - type: "string" - x-nullable: false - ContainerConfig: - $ref: "#/definitions/Config" - DockerVersion: - type: "string" - x-nullable: false - Author: - type: "string" - x-nullable: false - Config: - $ref: "#/definitions/Config" - Architecture: - type: "string" - x-nullable: false - Os: - type: "string" - x-nullable: false - OsVersion: - type: "string" - Size: - type: "integer" - format: "int64" - x-nullable: false - VirtualSize: - type: "integer" - format: "int64" - x-nullable: false - GraphDriver: - $ref: "#/definitions/GraphDriverData" - RootFS: - type: "object" - required: [Type] - properties: - Type: - type: "string" - x-nullable: false - Layers: - type: "array" - items: - type: "string" - BaseLayer: - type: "string" - - ImageSummary: - type: "object" - required: - - Id - - ParentId - - RepoTags - - RepoDigests - - Created - - Size - - SharedSize - - VirtualSize - - Labels - - Containers - properties: - Id: - type: "string" - x-nullable: false - ParentId: - type: "string" - x-nullable: false - RepoTags: - type: "array" - x-nullable: false - items: - type: "string" - RepoDigests: - type: "array" - x-nullable: false - items: - type: "string" - Created: - type: "integer" - x-nullable: false - Size: - type: "integer" - x-nullable: false - SharedSize: - type: "integer" - x-nullable: false - VirtualSize: - type: "integer" - x-nullable: false - Labels: - type: "object" - x-nullable: false - additionalProperties: - type: "string" - Containers: - x-nullable: false - type: "integer" - - AuthConfig: - type: "object" - properties: - username: - type: "string" - password: - type: "string" - email: - type: "string" - serveraddress: - type: "string" - example: - username: "hannibal" - password: "xxxx" - serveraddress: "https://index.docker.io/v1/" - - ProcessConfig: - type: "object" - properties: - privileged: - type: "boolean" - user: - type: "string" - tty: - type: "boolean" - entrypoint: - type: "string" - arguments: - type: "array" - items: - type: "string" - - Volume: - type: "object" - required: [Name, Driver, Mountpoint, Labels, Scope, Options] - properties: - Name: - type: "string" - description: "Name of the volume." - x-nullable: false - Driver: - type: "string" - description: "Name of the volume driver used by the volume." - x-nullable: false - Mountpoint: - type: "string" - description: "Mount path of the volume on the host." - x-nullable: false - Status: - type: "object" - description: | - Low-level details about the volume, provided by the volume driver. - Details are returned as a map with key/value pairs: - `{"key":"value","key2":"value2"}`. - - The `Status` field is optional, and is omitted if the volume driver - does not support this feature. - additionalProperties: - type: "object" - Labels: - type: "object" - description: "User-defined key/value metadata." - x-nullable: false - additionalProperties: - type: "string" - Scope: - type: "string" - description: "The level at which the volume exists. Either `global` for cluster-wide, or `local` for machine level." - default: "local" - x-nullable: false - enum: ["local", "global"] - Options: - type: "object" - description: "The driver specific options used when creating the volume." - additionalProperties: - type: "string" - UsageData: - type: "object" - required: [Size, RefCount] - properties: - Size: - type: "integer" - description: "The disk space used by the volume (local driver only)" - default: -1 - x-nullable: false - RefCount: - type: "integer" - default: -1 - description: "The number of containers referencing this volume." - x-nullable: false - - example: - Name: "tardis" - Driver: "custom" - Mountpoint: "/var/lib/docker/volumes/tardis" - Status: - hello: "world" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Scope: "local" - - Network: - type: "object" - properties: - Name: - type: "string" - Id: - type: "string" - Created: - type: "string" - format: "dateTime" - Scope: - type: "string" - Driver: - type: "string" - EnableIPv6: - type: "boolean" - IPAM: - $ref: "#/definitions/IPAM" - Internal: - type: "boolean" - Attachable: - type: "boolean" - Ingress: - type: "boolean" - Containers: - type: "object" - additionalProperties: - $ref: "#/definitions/NetworkContainer" - Options: - type: "object" - additionalProperties: - type: "string" - Labels: - type: "object" - additionalProperties: - type: "string" - example: - Name: "net01" - Id: "7d86d31b1478e7cca9ebed7e73aa0fdeec46c5ca29497431d3007d2d9e15ed99" - Created: "2016-10-19T04:33:30.360899459Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - IPAM: - Driver: "default" - Config: - - Subnet: "172.19.0.0/16" - Gateway: "172.19.0.1" - Options: - foo: "bar" - Internal: false - Attachable: false - Ingress: false - Containers: - 19a4d5d687db25203351ed79d478946f861258f018fe384f229f2efa4b23513c: - Name: "test" - EndpointID: "628cadb8bcb92de107b2a1e516cbffe463e321f548feb37697cce00ad694f21a" - MacAddress: "02:42:ac:13:00:02" - IPv4Address: "172.19.0.2/16" - IPv6Address: "" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - IPAM: - type: "object" - properties: - Driver: - description: "Name of the IPAM driver to use." - type: "string" - default: "default" - Config: - description: "List of IPAM configuration options, specified as a map: `{\"Subnet\": , \"IPRange\": , \"Gateway\": , \"AuxAddress\": }`" - type: "array" - items: - type: "object" - additionalProperties: - type: "string" - Options: - description: "Driver-specific options, specified as a map." - type: "array" - items: - type: "object" - additionalProperties: - type: "string" - NetworkContainer: - type: "object" - properties: - EndpointID: - type: "string" - MacAddress: - type: "string" - IPv4Address: - type: "string" - IPv6Address: - type: "string" - - BuildInfo: - type: "object" - properties: - id: - type: "string" - stream: - type: "string" - error: - type: "string" - errorDetail: - $ref: "#/definitions/ErrorDetail" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - CreateImageInfo: - type: "object" - properties: - error: - type: "string" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - - PushImageInfo: - type: "object" - properties: - error: - type: "string" - status: - type: "string" - progress: - type: "string" - progressDetail: - $ref: "#/definitions/ProgressDetail" - ErrorDetail: - type: "object" - properties: - code: - type: "integer" - message: - type: "string" - ProgressDetail: - type: "object" - properties: - code: - type: "integer" - message: - type: "integer" - - ErrorResponse: - description: "Represents an error." - type: "object" - required: ["message"] - properties: - message: - description: "The error message." - type: "string" - x-nullable: false - example: - message: "Something went wrong." - - IdResponse: - description: "Response to an API call that returns just an Id" - type: "object" - required: ["Id"] - properties: - Id: - description: "The id of the newly created object." - type: "string" - x-nullable: false - - EndpointSettings: - description: "Configuration for a network endpoint." - type: "object" - properties: - IPAMConfig: - description: "IPAM configurations for the endpoint" - type: "object" - properties: - IPv4Address: - type: "string" - IPv6Address: - type: "string" - LinkLocalIPs: - type: "array" - items: - type: "string" - Links: - type: "array" - items: - type: "string" - Aliases: - type: "array" - items: - type: "string" - NetworkID: - type: "string" - EndpointID: - type: "string" - Gateway: - type: "string" - IPAddress: - type: "string" - IPPrefixLen: - type: "integer" - IPv6Gateway: - type: "string" - GlobalIPv6Address: - type: "string" - GlobalIPv6PrefixLen: - type: "integer" - format: "int64" - MacAddress: - type: "string" - - PluginMount: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Source, Destination, Type, Options] - properties: - Name: - type: "string" - x-nullable: false - Description: - type: "string" - x-nullable: false - Settable: - type: "array" - items: - type: "string" - Source: - type: "string" - Destination: - type: "string" - x-nullable: false - Type: - type: "string" - x-nullable: false - Options: - type: "array" - items: - type: "string" - - PluginDevice: - type: "object" - required: [Name, Description, Settable, Path] - x-nullable: false - properties: - Name: - type: "string" - x-nullable: false - Description: - type: "string" - x-nullable: false - Settable: - type: "array" - items: - type: "string" - Path: - type: "string" - - PluginEnv: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - Description: - x-nullable: false - type: "string" - Settable: - type: "array" - items: - type: "string" - Value: - type: "string" - - PluginInterfaceType: - type: "object" - x-nullable: false - required: [Prefix, Capability, Version] - properties: - Prefix: - type: "string" - x-nullable: false - Capability: - type: "string" - x-nullable: false - Version: - type: "string" - x-nullable: false - - Plugin: - description: "A plugin for the Engine API" - type: "object" - required: [Settings, Enabled, Config, Name] - properties: - Id: - type: "string" - Name: - type: "string" - x-nullable: false - Enabled: - description: "True when the plugin is running. False when the plugin is not running, only installed." - type: "boolean" - x-nullable: false - Settings: - description: "Settings that can be modified by users." - type: "object" - x-nullable: false - required: [Args, Devices, Env, Mounts] - properties: - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - type: "string" - Args: - type: "array" - items: - type: "string" - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PluginReference: - description: "plugin remote reference used to push/pull the plugin" - type: "string" - x-nullable: false - Config: - description: "The config of a plugin." - type: "object" - x-nullable: false - required: - - Description - - Documentation - - Interface - - Entrypoint - - WorkDir - - Network - - Linux - - PidHost - - PropagatedMount - - IpcHost - - Mounts - - Env - - Args - properties: - DockerVersion: - description: "Docker Version used to create the plugin" - type: "string" - x-nullable: false - Description: - type: "string" - x-nullable: false - Documentation: - type: "string" - x-nullable: false - Interface: - description: "The interface between Docker and the plugin" - x-nullable: false - type: "object" - required: [Types, Socket] - properties: - Types: - type: "array" - items: - $ref: "#/definitions/PluginInterfaceType" - Socket: - type: "string" - x-nullable: false - Entrypoint: - type: "array" - items: - type: "string" - WorkDir: - type: "string" - x-nullable: false - User: - type: "object" - x-nullable: false - properties: - UID: - type: "integer" - format: "uint32" - GID: - type: "integer" - format: "uint32" - Network: - type: "object" - x-nullable: false - required: [Type] - properties: - Type: - x-nullable: false - type: "string" - Linux: - type: "object" - x-nullable: false - required: [Capabilities, AllowAllDevices, Devices] - properties: - Capabilities: - type: "array" - items: - type: "string" - AllowAllDevices: - type: "boolean" - x-nullable: false - Devices: - type: "array" - items: - $ref: "#/definitions/PluginDevice" - PropagatedMount: - type: "string" - x-nullable: false - IpcHost: - type: "boolean" - x-nullable: false - PidHost: - type: "boolean" - x-nullable: false - Mounts: - type: "array" - items: - $ref: "#/definitions/PluginMount" - Env: - type: "array" - items: - $ref: "#/definitions/PluginEnv" - Args: - type: "object" - x-nullable: false - required: [Name, Description, Settable, Value] - properties: - Name: - x-nullable: false - type: "string" - Description: - x-nullable: false - type: "string" - Settable: - type: "array" - items: - type: "string" - Value: - type: "array" - items: - type: "string" - rootfs: - type: "object" - properties: - type: - type: "string" - diff_ids: - type: "array" - items: - type: "string" - example: - Id: "5724e2c8652da337ab2eedd19fc6fc0ec908e4bd907c7421bf6a8dfc70c4c078" - Name: "tiborvass/sample-volume-plugin" - Tag: "latest" - Active: true - Settings: - Env: - - "DEBUG=0" - Args: null - Devices: null - Config: - Description: "A sample volume plugin for Docker" - Documentation: "https://docs.docker.com/engine/extend/plugins/" - Interface: - Types: - - "docker.volumedriver/1.0" - Socket: "plugins.sock" - Entrypoint: - - "/usr/bin/sample-volume-plugin" - - "/data" - WorkDir: "" - User: {} - Network: - Type: "" - Linux: - Capabilities: null - AllowAllDevices: false - Devices: null - Mounts: null - PropagatedMount: "/data" - Env: - - Name: "DEBUG" - Description: "If set, prints debug messages" - Settable: null - Value: "0" - Args: - Name: "args" - Description: "command line arguments" - Settable: null - Value: [] - - ObjectVersion: - description: | - The version number of the object such as node, service, etc. This is needed to avoid conflicting writes. - The client must send the version number along with the modified specification when updating these objects. - This approach ensures safe concurrency and determinism in that the change on the object - may not be applied if the version number has changed from the last read. In other words, - if two update requests specify the same base version, only one of the requests can succeed. - As a result, two separate update requests that happen at the same time will not - unintentially overwrite each other. - type: "object" - properties: - Index: - type: "integer" - format: "int64" - - NodeSpec: - type: "object" - properties: - Name: - description: "Name for the node." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Role: - description: "Role of the node." - type: "string" - enum: - - "worker" - - "manager" - Availability: - description: "Availability of the node." - type: "string" - enum: - - "active" - - "pause" - - "drain" - example: - Availability: "active" - Name: "node-name" - Role: "manager" - Labels: - foo: "bar" - Node: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/NodeSpec" - Description: - type: "object" - properties: - Hostname: - type: "string" - Platform: - type: "object" - properties: - Architecture: - type: "string" - OS: - type: "string" - Resources: - type: "object" - properties: - NanoCPUs: - type: "integer" - format: "int64" - MemoryBytes: - type: "integer" - format: "int64" - Engine: - type: "object" - properties: - EngineVersion: - type: "string" - Labels: - type: "object" - additionalProperties: - type: "string" - Plugins: - type: "array" - items: - type: "object" - properties: - Type: - type: "string" - Name: - type: "string" - example: - ID: "24ifsmvkjbyhk" - Version: - Index: 8 - CreatedAt: "2016-06-07T20:31:11.853781916Z" - UpdatedAt: "2016-06-07T20:31:11.999868824Z" - Spec: - Name: "my-node" - Role: "manager" - Availability: "active" - Labels: - foo: "bar" - Description: - Hostname: "bf3067039e47" - Platform: - Architecture: "x86_64" - OS: "linux" - Resources: - NanoCPUs: 4000000000 - MemoryBytes: 8272408576 - Engine: - EngineVersion: "17.04.0" - Labels: - foo: "bar" - Plugins: - - Type: "Volume" - Name: "local" - - Type: "Network" - Name: "bridge" - - Type: "Network" - Name: "null" - - Type: "Network" - Name: "overlay" - Status: - State: "ready" - Addr: "172.17.0.2" - ManagerStatus: - Leader: true - Reachability: "reachable" - Addr: "172.17.0.2:2377" - SwarmSpec: - description: "User modifiable swarm configuration." - type: "object" - properties: - Name: - description: "Name of the swarm." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Orchestration: - description: "Orchestration configuration." - type: "object" - properties: - TaskHistoryRetentionLimit: - description: "The number of historic tasks to keep per instance or node. If negative, never remove completed or failed tasks." - type: "integer" - format: "int64" - Raft: - description: "Raft configuration." - type: "object" - properties: - SnapshotInterval: - description: "The number of log entries between snapshots." - type: "integer" - format: "int64" - KeepOldSnapshots: - description: "The number of snapshots to keep beyond the current snapshot." - type: "integer" - format: "int64" - LogEntriesForSlowFollowers: - description: "The number of log entries to keep around to sync up slow followers after a snapshot is created." - type: "integer" - format: "int64" - ElectionTick: - description: | - The number of ticks that a follower will wait for a message from the leader before becoming a candidate and starting an election. `ElectionTick` must be greater than `HeartbeatTick`. - - A tick currently defaults to one second, so these translate directly to seconds currently, but this is NOT guaranteed. - type: "integer" - HeartbeatTick: - description: | - The number of ticks between heartbeats. Every HeartbeatTick ticks, the leader will send a heartbeat to the followers. - - A tick currently defaults to one second, so these translate directly to seconds currently, but this is NOT guaranteed. - type: "integer" - Dispatcher: - description: "Dispatcher configuration." - type: "object" - properties: - HeartbeatPeriod: - description: "The delay for an agent to send a heartbeat to the dispatcher." - type: "integer" - format: "int64" - CAConfig: - description: "CA configuration." - type: "object" - properties: - NodeCertExpiry: - description: "The duration node certificates are issued for." - type: "integer" - format: "int64" - ExternalCAs: - description: "Configuration for forwarding signing requests to an external certificate authority." - type: "array" - items: - type: "object" - properties: - Protocol: - description: "Protocol for communication with the external CA (currently only `cfssl` is supported)." - type: "string" - enum: - - "cfssl" - default: "cfssl" - URL: - description: "URL where certificate signing requests should be sent." - type: "string" - Options: - description: "An object with key/value pairs that are interpreted as protocol-specific options for the external CA driver." - type: "object" - additionalProperties: - type: "string" - EncryptionConfig: - description: "Parameters related to encryption-at-rest." - type: "object" - properties: - AutoLockManagers: - description: "If set, generate a key and use it to lock data stored on the managers." - type: "boolean" - TaskDefaults: - description: "Defaults for creating tasks in this cluster." - type: "object" - properties: - LogDriver: - description: | - The log driver to use for tasks created in the orchestrator if unspecified by a service. - - Updating this value will only have an affect on new tasks. Old tasks will continue use their previously configured log driver until recreated. - type: "object" - properties: - Name: - type: "string" - Options: - type: "object" - additionalProperties: - type: "string" - example: - Name: "default" - Orchestration: - TaskHistoryRetentionLimit: 10 - Raft: - SnapshotInterval: 10000 - LogEntriesForSlowFollowers: 500 - HeartbeatTick: 1 - ElectionTick: 3 - Dispatcher: - HeartbeatPeriod: 5000000000 - CAConfig: - NodeCertExpiry: 7776000000000000 - JoinTokens: - Worker: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-1awxwuwd3z9j1z3puu7rcgdbx" - Manager: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - EncryptionConfig: - AutoLockManagers: false - # The Swarm information for `GET /info`. It is the same as `GET /swarm`, but - # without `JoinTokens`. - ClusterInfo: - type: "object" - properties: - ID: - description: "The ID of the swarm." - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/SwarmSpec" - TaskSpec: - description: "User modifiable task configuration." - type: "object" - properties: - ContainerSpec: - type: "object" - properties: - Image: - description: "The image name to use for the container." - type: "string" - Labels: - description: "User-defined key/value data." - type: "object" - additionalProperties: - type: "string" - Command: - description: "The command to be run in the image." - type: "array" - items: - type: "string" - Args: - description: "Arguments to the command." - type: "array" - items: - type: "string" - Hostname: - description: "The hostname to use for the container, as a valid RFC 1123 hostname." - type: "string" - Env: - description: "A list of environment variables in the form `VAR=value`." - type: "array" - items: - type: "string" - Dir: - description: "The working directory for commands to run in." - type: "string" - User: - description: "The user inside the container." - type: "string" - Groups: - type: "array" - description: "A list of additional groups that the container process will run as." - items: - type: "string" - TTY: - description: "Whether a pseudo-TTY should be allocated." - type: "boolean" - OpenStdin: - description: "Open `stdin`" - type: "boolean" - ReadOnly: - description: "Mount the container's root filesystem as read only." - type: "boolean" - Mounts: - description: "Specification for mounts to be added to containers created as part of the service." - type: "array" - items: - $ref: "#/definitions/Mount" - StopSignal: - description: "Signal to stop the container." - type: "string" - StopGracePeriod: - description: "Amount of time to wait for the container to terminate before forcefully killing it." - type: "integer" - format: "int64" - HealthCheck: - $ref: "#/definitions/HealthConfig" - Hosts: - type: "array" - description: | - A list of hostnames/IP mappings to add to the container's `/etc/hosts` file. - The format of extra hosts on swarmkit is specified in: - http://man7.org/linux/man-pages/man5/hosts.5.html - IP_address canonical_hostname [aliases...] - items: - type: "string" - DNSConfig: - description: "Specification for DNS related configurations in resolver configuration file (`resolv.conf`)." - type: "object" - properties: - Nameservers: - description: "The IP addresses of the name servers." - type: "array" - items: - type: "string" - Search: - description: "A search list for host-name lookup." - type: "array" - items: - type: "string" - Options: - description: "A list of internal resolver variables to be modified (e.g., `debug`, `ndots:3`, etc.)." - type: "array" - items: - type: "string" - Secrets: - description: "Secrets contains references to zero or more secrets that will be exposed to the service." - type: "array" - items: - type: "object" - properties: - File: - description: "File represents a specific target that is backed by a file." - type: "object" - properties: - Name: - description: "Name represents the final filename in the filesystem." - type: "string" - UID: - description: "UID represents the file UID." - type: "string" - GID: - description: "GID represents the file GID." - type: "string" - Mode: - description: "Mode represents the FileMode of the file." - type: "integer" - format: "uint32" - SecretID: - description: "SecretID represents the ID of the specific secret that we're referencing." - type: "string" - SecretName: - description: | - SecretName is the name of the secret that this references, but this is just provided for - lookup/display purposes. The secret in the reference will be identified by its ID. - type: "string" - - Resources: - description: "Resource requirements which apply to each individual container created as part of the service." - type: "object" - properties: - Limits: - description: "Define resources limits." - type: "object" - properties: - NanoCPUs: - description: "CPU limit in units of 10-9 CPU shares." - type: "integer" - format: "int64" - MemoryBytes: - description: "Memory limit in Bytes." - type: "integer" - format: "int64" - Reservation: - description: "Define resources reservation." - properties: - NanoCPUs: - description: "CPU reservation in units of 10-9 CPU shares." - type: "integer" - format: "int64" - MemoryBytes: - description: "Memory reservation in Bytes." - type: "integer" - format: "int64" - RestartPolicy: - description: "Specification for the restart policy which applies to containers created as part of this service." - type: "object" - properties: - Condition: - description: "Condition for restart." - type: "string" - enum: - - "none" - - "on-failure" - - "any" - Delay: - description: "Delay between restart attempts." - type: "integer" - format: "int64" - MaxAttempts: - description: "Maximum attempts to restart a given container before giving up (default value is 0, which is ignored)." - type: "integer" - format: "int64" - default: 0 - Window: - description: "Windows is the time window used to evaluate the restart policy (default value is 0, which is unbounded)." - type: "integer" - format: "int64" - default: 0 - Placement: - type: "object" - properties: - Constraints: - description: "An array of constraints." - type: "array" - items: - type: "string" - Preferences: - description: "Preferences provide a way to make the scheduler aware of factors such as topology. They are provided in order from highest to lowest precedence." - type: "array" - items: - type: "object" - properties: - Spread: - type: "object" - properties: - SpreadDescriptor: - description: "label descriptor, such as engine.labels.az" - type: "string" - ForceUpdate: - description: "A counter that triggers an update even if no relevant parameters have been changed." - type: "integer" - Runtime: - description: "Runtime is the type of runtime specified for the task executor." - type: "string" - RuntimeData: - description: "RuntimeData is the payload sent to be used with the runtime for the executor." - type: "array" - Networks: - type: "array" - items: - type: "object" - properties: - Target: - type: "string" - Aliases: - type: "array" - items: - type: "string" - LogDriver: - description: "Specifies the log driver to use for tasks created from this spec. If not present, the default one for the swarm will be used, finally falling back to the engine default if not specified." - type: "object" - properties: - Name: - type: "string" - Options: - type: "object" - additionalProperties: - type: "string" - TaskState: - type: "string" - enum: - - "new" - - "allocated" - - "pending" - - "assigned" - - "accepted" - - "preparing" - - "ready" - - "starting" - - "running" - - "complete" - - "shutdown" - - "failed" - - "rejected" - Task: - type: "object" - properties: - ID: - description: "The ID of the task." - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Name: - description: "Name of the task." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Spec: - $ref: "#/definitions/TaskSpec" - ServiceID: - description: "The ID of the service this task is part of." - type: "string" - Slot: - type: "integer" - NodeID: - description: "The ID of the node that this task is on." - type: "string" - Status: - type: "object" - properties: - Timestamp: - type: "string" - format: "dateTime" - State: - $ref: "#/definitions/TaskState" - Message: - type: "string" - Err: - type: "string" - ContainerStatus: - type: "object" - properties: - ContainerID: - type: "string" - PID: - type: "integer" - ExitCode: - type: "integer" - DesiredState: - $ref: "#/definitions/TaskState" - example: - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - ServiceSpec: - description: "User modifiable configuration for a service." - properties: - Name: - description: "Name of the service." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - TaskTemplate: - $ref: "#/definitions/TaskSpec" - Mode: - description: "Scheduling mode for the service." - type: "object" - properties: - Replicated: - type: "object" - properties: - Replicas: - type: "integer" - format: "int64" - Global: - type: "object" - UpdateConfig: - description: "Specification for the update strategy of the service." - type: "object" - properties: - Parallelism: - description: "Maximum number of tasks to be updated in one iteration (0 means unlimited parallelism)." - type: "integer" - format: "int64" - Delay: - description: "Amount of time between updates, in nanoseconds." - type: "integer" - format: "int64" - FailureAction: - description: "Action to take if an updated task fails to run, or stops running during the update." - type: "string" - enum: - - "continue" - - "pause" - - "rollback" - Monitor: - description: "Amount of time to monitor each updated task for failures, in nanoseconds." - type: "integer" - format: "int64" - MaxFailureRatio: - description: "The fraction of tasks that may fail during an update before the failure action is invoked, specified as a floating point number between 0 and 1." - type: "number" - default: 0 - Order: - description: "The order of operations when rolling out an updated task. Either the old task is shut down before the new task is started, or the new task is started before the old task is shut down." - type: "string" - enum: - - "stop-first" - - "start-first" - RollbackConfig: - description: "Specification for the rollback strategy of the service." - type: "object" - properties: - Parallelism: - description: "Maximum number of tasks to be rolled back in one iteration (0 means unlimited parallelism)." - type: "integer" - format: "int64" - Delay: - description: "Amount of time between rollback iterations, in nanoseconds." - type: "integer" - format: "int64" - FailureAction: - description: "Action to take if an rolled back task fails to run, or stops running during the rollback." - type: "string" - enum: - - "continue" - - "pause" - Monitor: - description: "Amount of time to monitor each rolled back task for failures, in nanoseconds." - type: "integer" - format: "int64" - MaxFailureRatio: - description: "The fraction of tasks that may fail during a rollback before the failure action is invoked, specified as a floating point number between 0 and 1." - type: "number" - default: 0 - Order: - description: "The order of operations when rolling back a task. Either the old task is shut down before the new task is started, or the new task is started before the old task is shut down." - type: "string" - enum: - - "stop-first" - - "start-first" - Networks: - description: "Array of network names or IDs to attach the service to." - type: "array" - items: - type: "object" - properties: - Target: - type: "string" - Aliases: - type: "array" - items: - type: "string" - EndpointSpec: - $ref: "#/definitions/EndpointSpec" - EndpointPortConfig: - type: "object" - properties: - Name: - type: "string" - Protocol: - type: "string" - enum: - - "tcp" - - "udp" - TargetPort: - description: "The port inside the container." - type: "integer" - PublishedPort: - description: "The port on the swarm hosts." - type: "integer" - EndpointSpec: - description: "Properties that can be configured to access and load balance a service." - type: "object" - properties: - Mode: - description: "The mode of resolution to use for internal load balancing - between tasks." - type: "string" - enum: - - "vip" - - "dnsrr" - default: "vip" - Ports: - description: "List of exposed ports that this service is accessible on from the outside. Ports can only be provided if `vip` resolution mode is used." - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - Service: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ServiceSpec" - Endpoint: - type: "object" - properties: - Spec: - $ref: "#/definitions/EndpointSpec" - Ports: - type: "array" - items: - $ref: "#/definitions/EndpointPortConfig" - VirtualIPs: - type: "array" - items: - type: "object" - properties: - NetworkID: - type: "string" - Addr: - type: "string" - UpdateStatus: - description: "The status of a service update." - type: "object" - properties: - State: - type: "string" - enum: - - "updating" - - "paused" - - "completed" - StartedAt: - type: "string" - format: "dateTime" - CompletedAt: - type: "string" - format: "dateTime" - Message: - type: "string" - example: - ID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Version: - Index: 19 - CreatedAt: "2016-06-07T21:05:51.880065305Z" - UpdatedAt: "2016-06-07T21:07:29.962229872Z" - Spec: - Name: "hopeful_cori" - TaskTemplate: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Endpoint: - Spec: - Mode: "vip" - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - Ports: - - - Protocol: "tcp" - TargetPort: 6379 - PublishedPort: 30001 - VirtualIPs: - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.2/16" - - - NetworkID: "4qvuz4ko70xaltuqbt8956gd1" - Addr: "10.255.0.3/16" - ImageDeleteResponseItem: - type: "object" - properties: - Untagged: - description: "The image ID of an image that was untagged" - type: "string" - Deleted: - description: "The image ID of an image that was deleted" - type: "string" - ServiceUpdateResponse: - type: "object" - properties: - Warnings: - description: "Optional warning messages" - type: "array" - items: - type: "string" - example: - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - ContainerSummary: - type: "array" - items: - type: "object" - properties: - Id: - description: "The ID of this container" - type: "string" - x-go-name: "ID" - Names: - description: "The names that this container has been given" - type: "array" - items: - type: "string" - Image: - description: "The name of the image used when creating this container" - type: "string" - ImageID: - description: "The ID of the image that this container was created from" - type: "string" - Command: - description: "Command to run when starting the container" - type: "string" - Created: - description: "When the container was created" - type: "integer" - format: "int64" - Ports: - description: "The ports exposed by this container" - type: "array" - items: - $ref: "#/definitions/Port" - SizeRw: - description: "The size of files that have been created or changed by this container" - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container" - type: "integer" - format: "int64" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - State: - description: "The state of this container (e.g. `Exited`)" - type: "string" - Status: - description: "Additional human-readable status of this container (e.g. `Exit 0`)" - type: "string" - HostConfig: - type: "object" - properties: - NetworkMode: - type: "string" - NetworkSettings: - description: "A summary of the container's network settings" - type: "object" - properties: - Networks: - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - Mounts: - type: "array" - items: - $ref: "#/definitions/Mount" - SecretSpec: - type: "object" - properties: - Name: - description: "User-defined name of the secret." - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - Data: - description: "Base64-url-safe-encoded secret data" - type: "array" - items: - type: "string" - Secret: - type: "object" - properties: - ID: - type: "string" - Version: - $ref: "#/definitions/ObjectVersion" - CreatedAt: - type: "string" - format: "dateTime" - UpdatedAt: - type: "string" - format: "dateTime" - Spec: - $ref: "#/definitions/ServiceSpec" -paths: - /containers/json: - get: - summary: "List containers" - operationId: "ContainerList" - produces: - - "application/json" - parameters: - - name: "all" - in: "query" - description: "Return all containers. By default, only running containers are shown" - type: "boolean" - default: false - - name: "limit" - in: "query" - description: "Return this number of most recently created containers, including non-running ones." - type: "integer" - - name: "size" - in: "query" - description: "Return the size of container as fields `SizeRw` and `SizeRootFs`." - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - Filters to process on the container list, encoded as JSON (a `map[string][]string`). For example, `{"status": ["paused"]}` will only return paused containers. Available filters: - - - `ancestor`=(`[:]`, ``, or ``) - - `before`=(`` or ``) - - `expose`=(`[/]`|`/[]`) - - `exited=` containers with exit code of `` - - `health`=(`starting`|`healthy`|`unhealthy`|`none`) - - `id=` a container's ID - - `isolation=`(`default`|`process`|`hyperv`) (Windows daemon only) - - `is-task=`(`true`|`false`) - - `label=key` or `label="key=value"` of a container label - - `name=` a container's name - - `network`=(`` or ``) - - `publish`=(`[/]`|`/[]`) - - `since`=(`` or ``) - - `status=`(`created`|`restarting`|`running`|`removing`|`paused`|`exited`|`dead`) - - `volume`=(`` or ``) - type: "string" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/ContainerSummary" - examples: - application/json: - - Id: "8dfafdbc3a40" - Names: - - "/boring_feynman" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 1" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: - - PrivatePort: 2222 - PublicPort: 3333 - Type: "tcp" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "2cdc4edb1ded3631c81f57966563e5c8525b81121bb3706a9a9a3ae102711f3f" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:02" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - - Id: "9cd87474be90" - Names: - - "/coolName" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 222222" - Created: 1367854155 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "88eaed7b37b38c2a3f0c4bc796494fdf51b270c2d22656412a2ca5d559a64d7a" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.8" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:08" - Mounts: [] - - Id: "3176a2479c92" - Names: - - "/sleepy_dog" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 3333333333333333" - Created: 1367854154 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "8b27c041c30326d59cd6e6f510d4f8d1d570a228466f956edf7815508f78e30d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.6" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:06" - Mounts: [] - - Id: "4cb07b47f9fb" - Names: - - "/running_cat" - Image: "ubuntu:latest" - ImageID: "d74508fb6632491cea586a1fd7d748dfc5274cd6fdfedee309ecdcbc2bf5cb82" - Command: "echo 444444444444444444444444444444444" - Created: 1367854152 - State: "Exited" - Status: "Exit 0" - Ports: [] - Labels: {} - SizeRw: 12288 - SizeRootFs: 0 - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "d91c7b2f0644403d7ef3095985ea0e2370325cd2332ff3a3225c4247328e66e9" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.5" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:11:00:05" - Mounts: [] - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/create: - post: - summary: "Create a container" - operationId: "ContainerCreate" - consumes: - - "application/json" - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "name" - in: "query" - description: "Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`." - type: "string" - pattern: "/?[a-zA-Z0-9_-]+" - - name: "body" - in: "body" - description: "Container to create" - schema: - allOf: - - $ref: "#/definitions/Config" - - type: "object" - properties: - HostConfig: - $ref: "#/definitions/HostConfig" - NetworkingConfig: - description: "This container's networking configuration." - type: "object" - properties: - EndpointsConfig: - description: "A mapping of network name to endpoint configuration for that network." - type: "object" - additionalProperties: - $ref: "#/definitions/EndpointSettings" - example: - Hostname: "" - Domainname: "" - User: "" - AttachStdin: false - AttachStdout: true - AttachStderr: true - Tty: false - OpenStdin: false - StdinOnce: false - Env: - - "FOO=bar" - - "BAZ=quux" - Cmd: - - "date" - Entrypoint: "" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - Volumes: - /volumes/data: {} - WorkingDir: "" - NetworkDisabled: false - MacAddress: "12:34:56:78:9a:bc" - ExposedPorts: - 22/tcp: {} - StopSignal: "SIGTERM" - StopTimeout: 10 - HostConfig: - Binds: - - "/tmp:/tmp" - Links: - - "redis3:redis" - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - KernelMemory: 0 - NanoCPUs: 500000 - CpuPercent: 80 - CpuShares: 512 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpuQuota: 50000 - CpusetCpus: "0,1" - CpusetMems: "0,1" - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 300 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceWriteIOps: - - {} - MemorySwappiness: 60 - OomKillDisable: false - OomScoreAdj: 500 - PidMode: "" - PidsLimit: -1 - PortBindings: - 22/tcp: - - HostPort: "11022" - PublishAllPorts: false - Privileged: false - ReadonlyRootfs: false - Dns: - - "8.8.8.8" - DnsOptions: - - "" - DnsSearch: - - "" - VolumesFrom: - - "parent" - - "other:ro" - CapAdd: - - "NET_ADMIN" - CapDrop: - - "MKNOD" - GroupAdd: - - "newgroup" - RestartPolicy: - Name: "" - MaximumRetryCount: 0 - AutoRemove: true - NetworkMode: "bridge" - Devices: [] - Ulimits: - - {} - LogConfig: - Type: "json-file" - Config: {} - SecurityOpt: [] - StorageOpt: {} - CgroupParent: "" - VolumeDriver: "" - ShmSize: 67108864 - NetworkingConfig: - EndpointsConfig: - isolated_nw: - IPAMConfig: - IPv4Address: "172.20.30.33" - IPv6Address: "2001:db8:abcd::3033" - LinkLocalIPs: - - "169.254.34.68" - - "fe80::3468" - Links: - - "container_1" - - "container_2" - Aliases: - - "server_x" - - "server_y" - - required: true - responses: - 201: - description: "Container created successfully" - schema: - type: "object" - required: [Id, Warnings] - properties: - Id: - description: "The ID of the created container" - type: "string" - x-nullable: false - Warnings: - description: "Warnings encountered when creating the container" - type: "array" - x-nullable: false - items: - type: "string" - examples: - application/json: - Id: "e90e34656806" - Warnings: [] - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 406: - description: "impossible to attach" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /containers/{id}/json: - get: - summary: "Inspect a container" - description: "Return low-level information about a container." - operationId: "ContainerInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - Id: - description: "The ID of the container" - type: "string" - Created: - description: "The time the container was created" - type: "string" - Path: - description: "The path to the command being run" - type: "string" - Args: - description: "The arguments to the command being run" - type: "array" - items: - type: "string" - State: - description: "The state of the container." - type: "object" - properties: - Status: - description: "The status of the container. For example, `running` or `exited`." - type: "string" - Running: - description: "Whether this container is running." - type: "boolean" - Paused: - description: "Whether this container is paused." - type: "boolean" - Restarting: - description: "Whether this container is restarting." - type: "boolean" - OOMKilled: - description: "Whether this container has been killed because it ran out of memory." - type: "boolean" - Dead: - type: "boolean" - Pid: - description: "The process ID of this container" - type: "integer" - ExitCode: - description: "The last exit code of this container" - type: "integer" - Error: - type: "string" - StartedAt: - description: "The time when this container was last started." - type: "string" - FinishedAt: - description: "The time when this container last exited." - type: "string" - Image: - description: "The container's image" - type: "string" - ResolvConfPath: - type: "string" - HostnamePath: - type: "string" - HostsPath: - type: "string" - LogPath: - type: "string" - Node: - description: "TODO" - type: "object" - Name: - type: "string" - RestartCount: - type: "integer" - Driver: - type: "string" - MountLabel: - type: "string" - ProcessLabel: - type: "string" - AppArmorProfile: - type: "string" - ExecIDs: - type: "string" - HostConfig: - $ref: "#/definitions/HostConfig" - GraphDriver: - $ref: "#/definitions/GraphDriverData" - SizeRw: - description: "The size of files that have been created or changed by this container." - type: "integer" - format: "int64" - SizeRootFs: - description: "The total size of all the files in this container." - type: "integer" - format: "int64" - Mounts: - type: "array" - items: - $ref: "#/definitions/MountPoint" - Config: - $ref: "#/definitions/Config" - NetworkSettings: - $ref: "#/definitions/NetworkConfig" - examples: - application/json: - AppArmorProfile: "" - Args: - - "-c" - - "exit 9" - Config: - AttachStderr: true - AttachStdin: false - AttachStdout: true - Cmd: - - "/bin/sh" - - "-c" - - "exit 9" - Domainname: "" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Hostname: "ba033ac44011" - Image: "ubuntu" - Labels: - com.example.vendor: "Acme" - com.example.license: "GPL" - com.example.version: "1.0" - MacAddress: "" - NetworkDisabled: false - OpenStdin: false - StdinOnce: false - Tty: false - User: "" - Volumes: - /volumes/data: {} - WorkingDir: "" - StopSignal: "SIGTERM" - StopTimeout: 10 - Created: "2015-01-06T15:47:31.485331387Z" - Driver: "devicemapper" - HostConfig: - MaximumIOps: 0 - MaximumIOBps: 0 - BlkioWeight: 0 - BlkioWeightDevice: - - {} - BlkioDeviceReadBps: - - {} - BlkioDeviceWriteBps: - - {} - BlkioDeviceReadIOps: - - {} - BlkioDeviceWriteIOps: - - {} - ContainerIDFile: "" - CpusetCpus: "" - CpusetMems: "" - CpuPercent: 80 - CpuShares: 0 - CpuPeriod: 100000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - Devices: [] - IpcMode: "" - LxcConf: [] - Memory: 0 - MemorySwap: 0 - MemoryReservation: 0 - KernelMemory: 0 - OomKillDisable: false - OomScoreAdj: 500 - NetworkMode: "bridge" - PidMode: "" - PortBindings: {} - Privileged: false - ReadonlyRootfs: false - PublishAllPorts: false - RestartPolicy: - MaximumRetryCount: 2 - Name: "on-failure" - LogConfig: - Type: "json-file" - Sysctls: - net.ipv4.ip_forward: "1" - Ulimits: - - {} - VolumeDriver: "" - ShmSize: 67108864 - HostnamePath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname" - HostsPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts" - LogPath: "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log" - Id: "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39" - Image: "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2" - MountLabel: "" - Name: "/boring_euclid" - NetworkSettings: - Bridge: "" - SandboxID: "" - HairpinMode: false - LinkLocalIPv6Address: "" - LinkLocalIPv6PrefixLen: 0 - SandboxKey: "" - SecondaryIPAddresses: null - SecondaryIPv6Addresses: null - EndpointID: "" - Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - IPAddress: "" - IPPrefixLen: 0 - IPv6Gateway: "" - MacAddress: "" - Networks: - bridge: - NetworkID: "7ea29fc1412292a2d7bba362f9253545fecdfa8ce9a6e37dd10ba8bee7129812" - EndpointID: "7587b82f0dada3656fda26588aee72630c6fab1536d36e394b2bfbcf898c971d" - Gateway: "172.17.0.1" - IPAddress: "172.17.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Path: "/bin/sh" - ProcessLabel: "" - ResolvConfPath: "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf" - RestartCount: 1 - State: - Error: "" - ExitCode: 9 - FinishedAt: "2015-01-06T15:47:32.080254511Z" - OOMKilled: false - Dead: false - Paused: false - Pid: 0 - Restarting: false - Running: true - StartedAt: "2015-01-06T15:47:32.072697474Z" - Status: "running" - Mounts: - - Name: "fac362...80535" - Source: "/data" - Destination: "/data" - Driver: "local" - Mode: "ro,Z" - RW: false - Propagation: "" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "size" - in: "query" - type: "boolean" - default: false - description: "Return the size of container as fields `SizeRw` and `SizeRootFs`" - tags: ["Container"] - /containers/{id}/top: - get: - summary: "List processes running inside a container" - description: "On Unix systems, this is done by running the `ps` command. This endpoint is not supported on Windows." - operationId: "ContainerTop" - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - Titles: - description: "The ps column titles" - type: "array" - items: - type: "string" - Processes: - description: "Each process running in the container, where each is process is an array of values corresponding to the titles" - type: "array" - items: - type: "array" - items: - type: "string" - examples: - application/json: - Titles: - - "UID" - - "PID" - - "PPID" - - "C" - - "STIME" - - "TTY" - - "TIME" - - "CMD" - Processes: - - - - "root" - - "13642" - - "882" - - "0" - - "17:03" - - "pts/0" - - "00:00:00" - - "/bin/bash" - - - - "root" - - "13735" - - "13642" - - "0" - - "17:06" - - "pts/0" - - "00:00:00" - - "sleep 10" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "ps_args" - in: "query" - description: "The arguments to pass to `ps`. For example, `aux`" - type: "string" - default: "-ef" - tags: ["Container"] - /containers/{id}/logs: - get: - summary: "Get container logs" - description: | - Get `stdout` and `stderr` logs from a container. - - Note: This endpoint works only for containers with the `json-file` or `journald` logging driver. - operationId: "ContainerLogs" - responses: - 101: - description: "logs returned as a stream" - schema: - type: "string" - format: "binary" - 200: - description: "logs returned as a string in response body" - schema: - type: "string" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "follow" - in: "query" - description: | - Return the logs as a stream. - - This will return a `101` HTTP response with a `Connection: upgrade` header, then hijack the HTTP connection to send raw output. For more information about hijacking and the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach). - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: "Only return this number of log lines from the end of the logs. Specify as an integer or `all` to output all log lines." - type: "string" - default: "all" - tags: ["Container"] - /containers/{id}/changes: - get: - summary: "Get changes on a container’s filesystem" - description: | - Returns which files in a container's filesystem have been added, deleted, - or modified. The `Kind` of modification can be one of: - - - `0`: Modified - - `1`: Added - - `2`: Deleted - operationId: "ContainerChanges" - produces: ["application/json"] - responses: - 200: - description: "The list of changes" - schema: - type: "array" - items: - type: "object" - x-go-name: "ContainerChangeResponseItem" - required: [Path, Kind] - properties: - Path: - description: "Path to file that has changed" - type: "string" - x-nullable: false - Kind: - description: "Kind of change" - type: "integer" - format: "uint8" - enum: [0, 1, 2] - x-nullable: false - examples: - application/json: - - Path: "/dev" - Kind: 0 - - Path: "/dev/kmsg" - Kind: 1 - - Path: "/test" - Kind: 1 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/export: - get: - summary: "Export a container" - description: "Export the contents of a container as a tarball." - operationId: "ContainerExport" - produces: - - "application/octet-stream" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/stats: - get: - summary: "Get container stats based on resource usage" - description: | - This endpoint returns a live stream of a container’s resource usage - statistics. - - The `precpu_stats` is the CPU statistic of last read, which is used - for calculating the CPU usage percentage. It is not the same as the - `cpu_stats` field. - - If either `precpu_stats.online_cpus` or `cpu_stats.online_cpus` is - nil then for compatibility with older daemons the length of the - corresponding `cpu_usage.percpu_usage` array should be used. - operationId: "ContainerStats" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - type: "object" - examples: - application/json: - read: "2015-01-08T22:57:31.547920715Z" - pids_stats: - current: 3 - networks: - eth0: - rx_bytes: 5338 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 36 - tx_bytes: 648 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 8 - eth5: - rx_bytes: 4641 - rx_dropped: 0 - rx_errors: 0 - rx_packets: 26 - tx_bytes: 690 - tx_dropped: 0 - tx_errors: 0 - tx_packets: 9 - memory_stats: - stats: - total_pgmajfault: 0 - cache: 0 - mapped_file: 0 - total_inactive_file: 0 - pgpgout: 414 - rss: 6537216 - total_mapped_file: 0 - writeback: 0 - unevictable: 0 - pgpgin: 477 - total_unevictable: 0 - pgmajfault: 0 - total_rss: 6537216 - total_rss_huge: 6291456 - total_writeback: 0 - total_inactive_anon: 0 - rss_huge: 6291456 - hierarchical_memory_limit: 67108864 - total_pgfault: 964 - total_active_file: 0 - active_anon: 6537216 - total_active_anon: 6537216 - total_pgpgout: 414 - total_cache: 0 - inactive_anon: 0 - active_file: 0 - pgfault: 964 - inactive_file: 0 - total_pgpgin: 477 - max_usage: 6651904 - usage: 6537216 - failcnt: 0 - limit: 67108864 - blkio_stats: {} - cpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24472255 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100215355 - usage_in_kernelmode: 30000000 - system_cpu_usage: 739306590000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - precpu_stats: - cpu_usage: - percpu_usage: - - 8646879 - - 24350896 - - 36438778 - - 30657443 - usage_in_usermode: 50000000 - total_usage: 100093996 - usage_in_kernelmode: 30000000 - system_cpu_usage: 9492140000000 - online_cpus: 4 - throttling_data: - periods: 0 - throttled_periods: 0 - throttled_time: 0 - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "stream" - in: "query" - description: "Stream the output. If false, the stats will be output once and then it will disconnect." - type: "boolean" - default: true - tags: ["Container"] - /containers/{id}/resize: - post: - summary: "Resize a container TTY" - description: "Resize the TTY for a container. You must restart the container for the resize to take effect." - operationId: "ContainerResize" - consumes: - - "application/octet-stream" - produces: - - "text/plain" - responses: - 200: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "cannot resize container" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "h" - in: "query" - description: "Height of the tty session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the tty session in characters" - type: "integer" - tags: ["Container"] - /containers/{id}/start: - post: - summary: "Start a container" - operationId: "ContainerStart" - responses: - 204: - description: "no error" - 304: - description: "container already started" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, `@`, `^`, `[`, `,` or `_`." - type: "string" - tags: ["Container"] - /containers/{id}/stop: - post: - summary: "Stop a container" - operationId: "ContainerStop" - responses: - 204: - description: "no error" - 304: - description: "container already stopped" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/restart: - post: - summary: "Restart a container" - operationId: "ContainerRestart" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "t" - in: "query" - description: "Number of seconds to wait before killing the container" - type: "integer" - tags: ["Container"] - /containers/{id}/kill: - post: - summary: "Kill a container" - description: "Send a POSIX signal to a container, defaulting to killing to the container." - operationId: "ContainerKill" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "signal" - in: "query" - description: "Signal to send to the container as an integer or string (e.g. `SIGINT`)" - type: "string" - default: "SIGKILL" - tags: ["Container"] - /containers/{id}/update: - post: - summary: "Update a container" - description: "Change various configuration options of a container without having to recreate it." - operationId: "ContainerUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "The container has been updated." - schema: - type: "object" - properties: - Warnings: - type: "array" - items: - type: "string" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "update" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/Resources" - - type: "object" - properties: - RestartPolicy: - $ref: "#/definitions/RestartPolicy" - example: - BlkioWeight: 300 - CpuShares: 512 - CpuPeriod: 100000 - CpuQuota: 50000 - CpuRealtimePeriod: 1000000 - CpuRealtimeRuntime: 10000 - CpusetCpus: "0,1" - CpusetMems: "0" - Memory: 314572800 - MemorySwap: 514288000 - MemoryReservation: 209715200 - KernelMemory: 52428800 - RestartPolicy: - MaximumRetryCount: 4 - Name: "on-failure" - tags: ["Container"] - /containers/{id}/rename: - post: - summary: "Rename a container" - operationId: "ContainerRename" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "name already in use" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "name" - in: "query" - required: true - description: "New name for the container" - type: "string" - tags: ["Container"] - /containers/{id}/pause: - post: - summary: "Pause a container" - description: | - Use the cgroups freezer to suspend all processes in a container. - - Traditionally, when suspending a process the `SIGSTOP` signal is used, which is observable by the process being suspended. With the cgroups freezer the process is unaware, and unable to capture, that it is being suspended, and subsequently resumed. - operationId: "ContainerPause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/unpause: - post: - summary: "Unpause a container" - description: "Resume a container which has been paused." - operationId: "ContainerUnpause" - responses: - 204: - description: "no error" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}/attach: - post: - summary: "Attach to a container" - description: | - Attach to a container to read its output or send it input. You can attach to the same container multiple times and you can reattach to containers that have been detached. - - Either the `stream` or `logs` parameter must be `true` for this endpoint to do anything. - - See [the documentation for the `docker attach` command](https://docs.docker.com/engine/reference/commandline/attach/) for more details. - - ### Hijacking - - This endpoint hijacks the HTTP connection to transport `stdin`, `stdout`, and `stderr` on the same socket. - - This is the response from the daemon for an attach request: - - ``` - HTTP/1.1 200 OK - Content-Type: application/vnd.docker.raw-stream - - [STREAM] - ``` - - After the headers and two new lines, the TCP connection can now be used for raw, bidirectional communication between the client and server. - - To hint potential proxies about connection hijacking, the Docker client can also optionally send connection upgrade headers. - - For example, the client sends this request to upgrade the connection: - - ``` - POST /containers/16253994b7c4/attach?stream=1&stdout=1 HTTP/1.1 - Upgrade: tcp - Connection: Upgrade - ``` - - The Docker daemon will respond with a `101 UPGRADED` response, and will similarly follow with the raw stream: - - ``` - HTTP/1.1 101 UPGRADED - Content-Type: application/vnd.docker.raw-stream - Connection: Upgrade - Upgrade: tcp - - [STREAM] - ``` - - ### Stream format - - When the TTY setting is disabled in [`POST /containers/create`](#operation/ContainerCreate), the stream over the hijacked connected is multiplexed to separate out `stdout` and `stderr`. The stream consists of a series of frames, each containing a header and a payload. - - The header contains the information which the stream writes (`stdout` or `stderr`). It also contains the size of the associated frame encoded in the last four bytes (`uint32`). - - It is encoded on the first eight bytes like this: - - ```go - header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} - ``` - - `STREAM_TYPE` can be: - - - 0: `stdin` (is written on `stdout`) - - 1: `stdout` - - 2: `stderr` - - `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of the `uint32` size encoded as big endian. - - Following the header is the payload, which is the specified number of bytes of `STREAM_TYPE`. - - The simplest way to implement this protocol is the following: - - 1. Read 8 bytes. - 2. Choose `stdout` or `stderr` depending on the first byte. - 3. Extract the frame size from the last four bytes. - 4. Read the extracted size and output it on the correct output. - 5. Goto 1. - - ### Stream format when using a TTY - - When the TTY setting is enabled in [`POST /containers/create`](#operation/ContainerCreate), the stream is not multiplexed. The data exchanged over the hijacked connection is simply the raw data from the process PTY and client's `stdin`. - - operationId: "ContainerAttach" - produces: - - "application/vnd.docker.raw-stream" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: "Override the key sequence for detaching a container.Format is a single character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, `@`, `^`, `[`, `,` or `_`." - type: "string" - - name: "logs" - in: "query" - description: | - Replay previous logs from the container. - - This is useful for attaching to a container that has started and you want to output everything since the container started. - - If `stream` is also enabled, once all the previous output has been returned, it will seamlessly transition into streaming current output. - type: "boolean" - default: false - - name: "stream" - in: "query" - description: "Stream attached streams from the time the request was made onwards" - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/attach/ws: - get: - summary: "Attach to a container via a websocket" - operationId: "ContainerAttachWebsocket" - responses: - 101: - description: "no error, hints proxy about hijacking" - 200: - description: "no error, no upgrade header found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "detachKeys" - in: "query" - description: "Override the key sequence for detaching a container.Format is a single character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, `@`, `^`, `[`, `,`, or `_`." - type: "string" - - name: "logs" - in: "query" - description: "Return logs" - type: "boolean" - default: false - - name: "stream" - in: "query" - description: "Return stream" - type: "boolean" - default: false - - name: "stdin" - in: "query" - description: "Attach to `stdin`" - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Attach to `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Attach to `stderr`" - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/wait: - post: - summary: "Wait for a container" - description: "Block until a container stops, then returns the exit code." - operationId: "ContainerWait" - produces: ["application/json"] - responses: - 200: - description: "The container has exit." - schema: - type: "object" - required: [StatusCode] - properties: - StatusCode: - description: "Exit code of the container" - type: "integer" - x-nullable: false - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - tags: ["Container"] - /containers/{id}: - delete: - summary: "Remove a container" - operationId: "ContainerDelete" - responses: - 204: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "conflict" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "You cannot remove a running container: c2ada9df5af8. Stop the container before attempting removal or force remove" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "v" - in: "query" - description: "Remove the volumes associated with the container." - type: "boolean" - default: false - - name: "force" - in: "query" - description: "If the container is running, kill it before removing it." - type: "boolean" - default: false - - name: "link" - in: "query" - description: "Remove the specified link associated with the container." - type: "boolean" - default: false - tags: ["Container"] - /containers/{id}/archive: - head: - summary: "Get information about files in a container" - description: "A response header `X-Docker-Container-Path-Stat` is return containing a base64 - encoded JSON object with some filesystem header information about the path." - operationId: "ContainerArchiveInfo" - responses: - 200: - description: "no error" - headers: - X-Docker-Container-Path-Stat: - type: "string" - description: "TODO" - 400: - description: "Bad parameter" - schema: - allOf: - - $ref: "#/definitions/ErrorResponse" - - type: "object" - properties: - message: - description: "The error message. Either \"must specify path parameter\" (path cannot be empty) or \"not a directory\" (path was asserted to be a directory but exists as a file)." - type: "string" - x-nullable: false - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - get: - summary: "Get an archive of a filesystem resource in a container" - description: "Get a tar archive of a resource in the filesystem of container id." - operationId: "ContainerArchive" - produces: ["application/x-tar"] - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - allOf: - - $ref: "#/definitions/ErrorResponse" - - type: "object" - properties: - message: - description: "The error message. Either \"must specify path parameter\" (path cannot be empty) or \"not a directory\" (path was asserted to be a directory but exists as a file)." - type: "string" - x-nullable: false - 404: - description: "Container or path does not exist" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Resource in the container’s filesystem to archive." - type: "string" - tags: ["Container"] - put: - summary: "Extract an archive of files or folders to a directory in a container" - description: "Upload a tar archive to be extracted to a path in the filesystem of container id." - operationId: "PutContainerArchive" - consumes: ["application/x-tar", "application/octet-stream"] - responses: - 200: - description: "The content was extracted successfully" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 403: - description: "Permission denied, the volume or container rootfs is marked as read-only." - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such container or path does not exist inside the container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the container" - type: "string" - - name: "path" - in: "query" - required: true - description: "Path to a directory in the container to extract the archive’s contents into. " - type: "string" - - name: "noOverwriteDirNonDir" - in: "query" - description: "If “1”, “true”, or “True” then it will be an error if unpacking the given content would cause an existing directory to be replaced with a non-directory and vice versa." - type: "string" - - name: "inputStream" - in: "body" - required: true - description: "The input stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz." - schema: - type: "string" - tags: ["Container"] - /containers/prune: - post: - summary: "Delete stopped containers" - produces: - - "application/json" - operationId: "ContainerPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune containers created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune containers with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - ContainersDeleted: - description: "Container IDs that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Container"] - /images/json: - get: - summary: "List Images" - description: "Returns a list of images on the server. Note that it uses a different, smaller representation of an image than inspecting a single image." - operationId: "ImageList" - produces: - - "application/json" - responses: - 200: - description: "Summary image data for the images matching the query" - schema: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - examples: - application/json: - - Id: "sha256:e216a057b1cb1efc11f8a268f37ef62083e70b1b38323ba252e25ac88904a7e8" - ParentId: "" - RepoTags: - - "ubuntu:12.04" - - "ubuntu:precise" - RepoDigests: - - "ubuntu@sha256:992069aee4016783df6345315302fa59681aae51a8eeb2f889dea59290f21787" - Created: 1474925151 - Size: 103579269 - VirtualSize: 103579269 - SharedSize: 0 - Labels: {} - Containers: 2 - - Id: "sha256:3e314f95dcace0f5e4fd37b10862fe8398e3c60ed36600bc0ca5fda78b087175" - ParentId: "" - RepoTags: - - "ubuntu:12.10" - - "ubuntu:quantal" - RepoDigests: - - "ubuntu@sha256:002fba3e3255af10be97ea26e476692a7ebed0bb074a9ab960b2e7a1526b15d7" - - "ubuntu@sha256:68ea0200f0b90df725d99d823905b04cf844f6039ef60c60bf3e019915017bd3" - Created: 1403128455 - Size: 172064416 - VirtualSize: 172064416 - SharedSize: 0 - Labels: {} - Containers: 5 - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "all" - in: "query" - description: "Show all images. Only images from a final layer (no children) are shown by default." - type: "boolean" - default: false - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the images list. Available filters: - - - `before`=(`[:]`, `` or ``) - - `dangling=true` - - `label=key` or `label="key=value"` of an image label - - `reference`=(`[:]`) - - `since`=(`[:]`, `` or ``) - type: "string" - - name: "digests" - in: "query" - description: "Show digest information as a `RepoDigests` field on each image." - type: "boolean" - default: false - tags: ["Image"] - /build: - post: - summary: "Build an image" - description: | - Build an image from a tar archive with a `Dockerfile` in it. - - The `Dockerfile` specifies how the image is built from the tar archive. It is typically in the archive's root, but can be at a different path or have a different name by specifying the `dockerfile` parameter. [See the `Dockerfile` reference for more information](https://docs.docker.com/engine/reference/builder/). - - The Docker daemon performs a preliminary validation of the `Dockerfile` before starting the build, and returns an error if the syntax is incorrect. After that, each instruction is run one-by-one until the ID of the new image is output. - - The build is canceled if the client drops the connection by quitting or being killed. - operationId: "ImageBuild" - consumes: - - "application/octet-stream" - produces: - - "application/json" - parameters: - - name: "inputStream" - in: "body" - description: "A tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz." - schema: - type: "string" - format: "binary" - - name: "dockerfile" - in: "query" - description: "Path within the build context to the `Dockerfile`. This is ignored if `remote` is specified and points to an external `Dockerfile`." - type: "string" - default: "Dockerfile" - - name: "t" - in: "query" - description: "A name and optional tag to apply to the image in the `name:tag` format. If you omit the tag the default `latest` value is assumed. You can provide several `t` parameters." - type: "string" - - name: "extrahosts" - in: "query" - description: "Extra hosts to add to /etc/hosts" - type: "string" - - name: "remote" - in: "query" - description: "A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file’s contents are placed into a file called `Dockerfile` and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the `dockerfile` parameter is also specified, there must be a file with the corresponding path inside the tarball." - type: "string" - - name: "q" - in: "query" - description: "Suppress verbose build output." - type: "boolean" - default: false - - name: "nocache" - in: "query" - description: "Do not use the cache when building the image." - type: "boolean" - default: false - - name: "cachefrom" - in: "query" - description: "JSON array of images used for build cache resolution." - type: "string" - - name: "pull" - in: "query" - description: "Attempt to pull the image even if an older image exists locally." - type: "string" - - name: "rm" - in: "query" - description: "Remove intermediate containers after a successful build." - type: "boolean" - default: true - - name: "forcerm" - in: "query" - description: "Always remove intermediate containers, even upon failure." - type: "boolean" - default: false - - name: "memory" - in: "query" - description: "Set memory limit for build." - type: "integer" - - name: "memswap" - in: "query" - description: "Total memory (memory + swap). Set as `-1` to disable swap." - type: "integer" - - name: "cpushares" - in: "query" - description: "CPU shares (relative weight)." - type: "integer" - - name: "cpusetcpus" - in: "query" - description: "CPUs in which to allow execution (e.g., `0-3`, `0,1`)." - type: "string" - - name: "cpuperiod" - in: "query" - description: "The length of a CPU period in microseconds." - type: "integer" - - name: "cpuquota" - in: "query" - description: "Microseconds of CPU time that the container can get in a CPU period." - type: "integer" - - name: "buildargs" - in: "query" - description: "JSON map of string pairs for build-time variables. Users pass these values at build-time. Docker uses the buildargs as the environment context for commands run via the `Dockerfile` RUN instruction, or for variable expansion in other `Dockerfile` instructions. This is not meant for passing secret values. [Read more about the buildargs instruction.](https://docs.docker.com/engine/reference/builder/#arg)" - type: "integer" - - name: "shmsize" - in: "query" - description: "Size of `/dev/shm` in bytes. The size must be greater than 0. If omitted the system uses 64MB." - type: "integer" - - name: "squash" - in: "query" - description: "Squash the resulting images layers into a single layer. *(Experimental release only.)*" - type: "boolean" - - name: "labels" - in: "query" - description: "Arbitrary key/value labels to set on the image, as a JSON map of string pairs." - type: "string" - - name: "networkmode" - in: "query" - description: "Sets the networking mode for the run commands during - build. Supported standard values are: `bridge`, `host`, `none`, and - `container:`. Any other value is taken as a custom network's - name to which this container should connect to." - type: "string" - - name: "Content-type" - in: "header" - type: "string" - enum: - - "application/x-tar" - default: "application/x-tar" - - name: "X-Registry-Config" - in: "header" - description: | - This is a base64-encoded JSON object with auth configurations for multiple registries that a build may refer to. - - The key is a registry URL, and the value is an auth configuration object, [as described in the authentication section](#section/Authentication). For example: - - ``` - { - "docker.example.com": { - "username": "janedoe", - "password": "hunter2" - }, - "https://index.docker.io/v1/": { - "username": "mobydock", - "password": "conta1n3rize14" - } - } - ``` - - Only the registry domain name (and port if not the default 443) are required. However, for legacy reasons, the Docker Hub registry must be specified with both a `https://` prefix and a `/v1/` suffix even though Docker will prefer to use the v2 registry API. - type: "string" - responses: - 200: - description: "no error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /images/create: - post: - summary: "Create an image" - description: "Create an image by either pulling it from a registry or importing it." - operationId: "ImageCreate" - consumes: - - "text/plain" - - "application/octet-stream" - produces: - - "application/json" - responses: - 200: - description: "no error" - 404: - description: "repository does not exist or no read access" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "fromImage" - in: "query" - description: "Name of the image to pull. The name may include a tag or digest. This parameter may only be used when pulling an image. The pull is cancelled if the HTTP connection is closed." - type: "string" - - name: "fromSrc" - in: "query" - description: "Source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. This parameter may only be used when importing an image." - type: "string" - - name: "repo" - in: "query" - description: "Repository name given to an image when it is imported. The repo may include a tag. This parameter may only be used when importing an image." - type: "string" - - name: "tag" - in: "query" - description: "Tag or digest. If empty when pulling an image, this causes all tags for the given image to be pulled." - type: "string" - - name: "inputImage" - in: "body" - description: "Image content if the value `-` has been specified in fromSrc query parameter" - schema: - type: "string" - required: false - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration. [See the authentication section for details.](#section/Authentication)" - type: "string" - tags: ["Image"] - /images/{name}/json: - get: - summary: "Inspect an image" - description: "Return low-level information about an image." - operationId: "ImageInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Image" - examples: - application/json: - Id: "sha256:85f05633ddc1c50679be2b16a0479ab6f7637f8884e0cfe0f4d20e1ebb3d6e7c" - Container: "cb91e48a60d01f1e27028b4fc6819f4f290b3cf12496c8176ec714d0d390984a" - Comment: "" - Os: "linux" - Architecture: "amd64" - Parent: "sha256:91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - ContainerConfig: - Tty: false - Hostname: "e611e15f9c9d" - Domainname: "" - AttachStdout: false - PublishService: "" - AttachStdin: false - OpenStdin: false - StdinOnce: false - NetworkDisabled: false - OnBuild: [] - Image: "91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - User: "" - WorkingDir: "" - MacAddress: "" - AttachStderr: false - Labels: - com.example.license: "GPL" - com.example.version: "1.0" - com.example.vendor: "Acme" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Cmd: - - "/bin/sh" - - "-c" - - "#(nop) LABEL com.example.vendor=Acme com.example.license=GPL com.example.version=1.0" - DockerVersion: "1.9.0-dev" - VirtualSize: 188359297 - Size: 0 - Author: "" - Created: "2015-09-10T08:30:53.26995814Z" - GraphDriver: - Name: "aufs" - Data: {} - RepoDigests: - - "localhost:5000/test/busybox/example@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" - RepoTags: - - "example:1.0" - - "example:latest" - - "example:stable" - Config: - Image: "91e54dfb11794fad694460162bf0cb0a4fa710cfa3f60979c177d920813e267c" - NetworkDisabled: false - OnBuild: [] - StdinOnce: false - PublishService: "" - AttachStdin: false - OpenStdin: false - Domainname: "" - AttachStdout: false - Tty: false - Hostname: "e611e15f9c9d" - Cmd: - - "/bin/bash" - Env: - - "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - Labels: - com.example.vendor: "Acme" - com.example.version: "1.0" - com.example.license: "GPL" - MacAddress: "" - AttachStderr: false - WorkingDir: "" - User: "" - RootFS: - Type: "layers" - Layers: - - "sha256:1834950e52ce4d5a88a1bbd131c537f4d0e56d10ff0dd69e66be3b7dfa9df7e6" - - "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such image: someimage (tag: latest)" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or id" - type: "string" - required: true - tags: ["Image"] - /images/{name}/history: - get: - summary: "Get the history of an image" - description: "Return parent layers of an image." - operationId: "ImageHistory" - produces: ["application/json"] - responses: - 200: - description: "List of image layers" - schema: - type: "array" - items: - type: "object" - x-go-name: HistoryResponseItem - required: [Id, Created, CreatedBy, Tags, Size, Comment] - properties: - Id: - type: "string" - x-nullable: false - Created: - type: "integer" - format: "int64" - x-nullable: false - CreatedBy: - type: "string" - x-nullable: false - Tags: - type: "array" - items: - type: "string" - Size: - type: "integer" - format: "int64" - x-nullable: false - Comment: - type: "string" - x-nullable: false - examples: - application/json: - - Id: "3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710" - Created: 1398108230 - CreatedBy: "/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /" - Tags: - - "ubuntu:lucid" - - "ubuntu:10.04" - Size: 182964289 - Comment: "" - - Id: "6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8" - Created: 1398108222 - CreatedBy: "/bin/sh -c #(nop) MAINTAINER Tianon Gravi - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/" - Tags: [] - Size: 0 - Comment: "" - - Id: "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158" - Created: 1371157430 - CreatedBy: "" - Tags: - - "scratch12:latest" - - "scratch:latest" - Size: 0 - Comment: "Imported from -" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/{name}/push: - post: - summary: "Push an image" - description: | - Push an image to a registry. - - If you wish to push an image on to a private registry, that image must already have a tag which references the registry. For example, `registry.example.com/myimage:latest`. - - The push is cancelled if the HTTP connection is closed. - operationId: "ImagePush" - consumes: - - "application/octet-stream" - responses: - 200: - description: "No error" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID." - type: "string" - required: true - - name: "tag" - in: "query" - description: "The tag to associate with the image on the registry." - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration. [See the authentication section for details.](#section/Authentication)" - type: "string" - required: true - tags: ["Image"] - /images/{name}/tag: - post: - summary: "Tag an image" - description: "Tag an image so that it becomes part of a repository." - operationId: "ImageTag" - responses: - 201: - description: "No error" - 400: - description: "Bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID to tag." - type: "string" - required: true - - name: "repo" - in: "query" - description: "The repository to tag in. For example, `someuser/someimage`." - type: "string" - - name: "tag" - in: "query" - description: "The name of the new tag." - type: "string" - tags: ["Image"] - /images/{name}: - delete: - summary: "Remove an image" - description: | - Remove an image, along with any untagged parent images that were - referenced by that image. - - Images can't be removed if they have descendant images, are being - used by a running container or are being used by a build. - operationId: "ImageDelete" - produces: ["application/json"] - responses: - 200: - description: "The image was deleted successfully" - schema: - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - examples: - application/json: - - Untagged: "3e2f21a89f" - - Deleted: "3e2f21a89f" - - Deleted: "53b4f83ac9" - 404: - description: "No such image" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Conflict" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - - name: "force" - in: "query" - description: "Remove the image even if it is being used by stopped containers or has other tags" - type: "boolean" - default: false - - name: "noprune" - in: "query" - description: "Do not delete untagged parent images" - type: "boolean" - default: false - tags: ["Image"] - /images/search: - get: - summary: "Search images" - description: "Search for an image on Docker Hub." - operationId: "ImageSearch" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - type: "object" - properties: - description: - type: "string" - is_official: - type: "boolean" - is_automated: - type: "boolean" - name: - type: "string" - star_count: - type: "integer" - examples: - application/json: - - description: "" - is_official: false - is_automated: false - name: "wma55/u1210sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "jdswinbank/sshd" - star_count: 0 - - description: "" - is_official: false - is_automated: false - name: "vgauthier/sshd" - star_count: 0 - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "term" - in: "query" - description: "Term to search" - type: "string" - required: true - - name: "limit" - in: "query" - description: "Maximum number of results to return" - type: "integer" - - name: "filters" - in: "query" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the images list. Available filters: - - - `is-automated=(true|false)` - - `is-official=(true|false)` - - `stars=` Matches images that has at least 'number' stars. - type: "string" - tags: ["Image"] - /images/prune: - post: - summary: "Delete unused images" - produces: - - "application/json" - operationId: "ImagePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). Available filters: - - - `dangling=` When set to `true` (or `1`), prune only - unused *and* untagged images. When set to `false` - (or `0`), all unused images are pruned. - - `until=` Prune images created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune images with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - ImagesDeleted: - description: "Images that were deleted" - type: "array" - items: - $ref: "#/definitions/ImageDeleteResponseItem" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Image"] - /auth: - post: - summary: "Check auth configuration" - description: "Validate credentials for a registry and, if available, get an identity token for accessing the registry without password." - operationId: "SystemAuth" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "An identity token was generated successfully." - schema: - type: "object" - required: [Status] - properties: - Status: - description: "The status of the authentication" - type: "string" - x-nullable: false - IdentityToken: - description: "An opaque token used to authenticate a user after a successful login" - type: "string" - x-nullable: false - examples: - application/json: - Status: "Login Succeeded" - IdentityToken: "9cbaf023786cd7..." - 204: - description: "No error" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "authConfig" - in: "body" - description: "Authentication to check" - schema: - $ref: "#/definitions/AuthConfig" - tags: ["System"] - /info: - get: - summary: "Get system information" - operationId: "SystemInfo" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - Architecture: - type: "string" - Containers: - type: "integer" - ContainersRunning: - type: "integer" - ContainersStopped: - type: "integer" - ContainersPaused: - type: "integer" - CpuCfsPeriod: - type: "boolean" - CpuCfsQuota: - type: "boolean" - Debug: - type: "boolean" - DiscoveryBackend: - type: "string" - DockerRootDir: - type: "string" - Driver: - type: "string" - DriverStatus: - type: "array" - items: - type: "array" - items: - type: "string" - SystemStatus: - type: "array" - items: - type: "array" - items: - type: "string" - Plugins: - type: "object" - properties: - Volume: - type: "array" - items: - type: "string" - Network: - type: "array" - items: - type: "string" - ExperimentalBuild: - type: "boolean" - HttpProxy: - type: "string" - HttpsProxy: - type: "string" - ID: - type: "string" - IPv4Forwarding: - type: "boolean" - Images: - type: "integer" - IndexServerAddress: - type: "string" - InitPath: - type: "string" - InitSha1: - type: "string" - KernelVersion: - type: "string" - Labels: - type: "array" - items: - type: "string" - MemTotal: - type: "integer" - MemoryLimit: - type: "boolean" - NCPU: - type: "integer" - NEventsListener: - type: "integer" - NFd: - type: "integer" - NGoroutines: - type: "integer" - Name: - type: "string" - NoProxy: - type: "string" - OomKillDisable: - type: "boolean" - OSType: - type: "string" - OomScoreAdj: - type: "integer" - OperatingSystem: - type: "string" - RegistryConfig: - type: "object" - properties: - IndexConfigs: - type: "object" - additionalProperties: - type: "object" - properties: - Mirrors: - type: "array" - items: - type: "string" - Name: - type: "string" - Official: - type: "boolean" - Secure: - type: "boolean" - InsecureRegistryCIDRs: - type: "array" - items: - type: "string" - SwapLimit: - type: "boolean" - SystemTime: - type: "string" - ServerVersion: - type: "string" - examples: - application/json: - Architecture: "x86_64" - ClusterStore: "etcd://localhost:2379" - CgroupDriver: "cgroupfs" - Containers: 11 - ContainersRunning: 7 - ContainersStopped: 3 - ContainersPaused: 1 - CpuCfsPeriod: true - CpuCfsQuota: true - Debug: false - DockerRootDir: "/var/lib/docker" - Driver: "btrfs" - DriverStatus: - - - - "" - ExperimentalBuild: false - HttpProxy: "http://test:test@localhost:8080" - HttpsProxy: "https://test:test@localhost:8080" - ID: "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS" - IPv4Forwarding: true - Images: 16 - IndexServerAddress: "https://index.docker.io/v1/" - InitPath: "/usr/bin/docker" - InitSha1: "" - KernelMemory: true - KernelVersion: "3.12.0-1-amd64" - Labels: - - "storage=ssd" - MemTotal: 2099236864 - MemoryLimit: true - NCPU: 1 - NEventsListener: 0 - NFd: 11 - NGoroutines: 21 - Name: "prod-server-42" - NoProxy: "9.81.1.160" - OomKillDisable: true - OSType: "linux" - OperatingSystem: "Boot2Docker" - Plugins: - Volume: - - "local" - Network: - - "null" - - "host" - - "bridge" - RegistryConfig: - IndexConfigs: - docker.io: - Name: "docker.io" - Official: true - Secure: true - InsecureRegistryCIDRs: - - "127.0.0.0/8" - SecurityOptions: - - Key: "Name" - Value: "seccomp" - - Key: "Profile" - Value: "default" - - Key: "Name" - Value: "apparmor" - - Key: "Name" - Value: "selinux" - - Key: "Name" - Value: "userns" - ServerVersion: "1.9.0" - SwapLimit: false - SystemStatus: - - - - "State" - - "Healthy" - SystemTime: "2015-03-10T11:11:23.730591467-07:00" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /version: - get: - summary: "Get version" - description: "Returns the version of Docker that is running and various information about the system that Docker is running on." - operationId: "SystemVersion" - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - Version: - type: "string" - ApiVersion: - type: "string" - MinAPIVersion: - type: "string" - GitCommit: - type: "string" - GoVersion: - type: "string" - Os: - type: "string" - Arch: - type: "string" - KernelVersion: - type: "string" - Experimental: - type: "boolean" - BuildTime: - type: "string" - examples: - application/json: - Version: "17.04.0" - Os: "linux" - KernelVersion: "3.19.0-23-generic" - GoVersion: "go1.7.5" - GitCommit: "deadbee" - Arch: "amd64" - ApiVersion: "1.27" - MinAPIVersion: "1.12" - BuildTime: "2016-06-14T07:09:13.444803460+00:00" - Experimental: true - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /_ping: - get: - summary: "Ping" - description: "This is a dummy endpoint you can use to test if the server is accessible." - operationId: "SystemPing" - produces: ["text/plain"] - responses: - 200: - description: "no error" - schema: - type: "string" - example: "OK" - headers: - API-Version: - type: "string" - description: "Max API Version the server supports" - Docker-Experimental: - type: "boolean" - description: "If the server is running with experimental mode enabled" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /commit: - post: - summary: "Create a new image from a container" - operationId: "ImageCommit" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "containerConfig" - in: "body" - description: "The container configuration" - schema: - $ref: "#/definitions/Config" - - name: "container" - in: "query" - description: "The ID or name of the container to commit" - type: "string" - - name: "repo" - in: "query" - description: "Repository name for the created image" - type: "string" - - name: "tag" - in: "query" - description: "Tag name for the create image" - type: "string" - - name: "comment" - in: "query" - description: "Commit message" - type: "string" - - name: "author" - in: "query" - description: "Author of the image (e.g., `John Hannibal Smith `)" - type: "string" - - name: "pause" - in: "query" - description: "Whether to pause the container before committing" - type: "boolean" - default: true - - name: "changes" - in: "query" - description: "`Dockerfile` instructions to apply while committing" - type: "string" - tags: ["Image"] - /events: - get: - summary: "Monitor events" - description: | - Stream real-time events from the server. - - Various objects within Docker report events when something happens to them. - - Containers report these events: `attach, commit, copy, create, destroy, detach, die, exec_create, exec_detach, exec_start, export, health_status, kill, oom, pause, rename, resize, restart, start, stop, top, unpause, update` - - Images report these events: `delete, import, load, pull, push, save, tag, untag` - - Volumes report these events: `create, mount, unmount, destroy` - - Networks report these events: `create, connect, disconnect, destroy` - - The Docker daemon reports these events: `reload` - - operationId: "SystemEvents" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - Type: - description: "The type of object emitting the event" - type: "string" - Action: - description: "The type of event" - type: "string" - Actor: - type: "object" - properties: - ID: - description: "The ID of the object emitting the event" - type: "string" - Attributes: - description: "Various key/value attributes of the object, depending on its type" - type: "object" - additionalProperties: - type: "string" - time: - description: "Timestamp of event" - type: "integer" - timeNano: - description: "Timestamp of event, with nanosecond accuracy" - type: "integer" - format: "int64" - examples: - application/json: - Type: "container" - Action: "create" - Actor: - ID: "ede54ee1afda366ab42f824e8a5ffd195155d853ceaec74a927f249ea270c743" - Attributes: - com.example.some-label: "some-label-value" - image: "alpine" - name: "my-container" - time: 1461943101 - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "since" - in: "query" - description: "Show events created since this timestamp then stream new events." - type: "string" - - name: "until" - in: "query" - description: "Show events created until this timestamp then stop streaming." - type: "string" - - name: "filters" - in: "query" - description: | - A JSON encoded value of filters (a `map[string][]string`) to process on the event list. Available filters: - - - `container=` container name or ID - - `daemon=` daemon name or ID - - `event=` event type - - `image=` image name or ID - - `label=` image or container label - - `network=` network name or ID - - `plugin`= plugin name or ID - - `type=` object to filter by, one of `container`, `image`, `volume`, `network`, or `daemon` - - `volume=` volume name or ID - type: "string" - tags: ["System"] - /system/df: - get: - summary: "Get data usage information" - operationId: "SystemDataUsage" - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - LayersSize: - type: "integer" - format: "int64" - Images: - type: "array" - items: - $ref: "#/definitions/ImageSummary" - Containers: - type: "array" - items: - $ref: "#/definitions/ContainerSummary" - Volumes: - type: "array" - items: - $ref: "#/definitions/Volume" - example: - LayersSize: 1092588 - Images: - - - Id: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - ParentId: "" - RepoTags: - - "busybox:latest" - RepoDigests: - - "busybox@sha256:a59906e33509d14c036c8678d687bd4eec81ed7c4b8ce907b888c607f6a1e0e6" - Created: 1466724217 - Size: 1092588 - SharedSize: 0 - VirtualSize: 1092588 - Labels: {} - Containers: 1 - Containers: - - - Id: "e575172ed11dc01bfce087fb27bee502db149e1a0fad7c296ad300bbff178148" - Names: - - "/top" - Image: "busybox" - ImageID: "sha256:2b8fd9751c4c0f5dd266fcae00707e67a2545ef34f9a29354585f93dac906749" - Command: "top" - Created: 1472592424 - Ports: [] - SizeRootFs: 1092588 - Labels: {} - State: "exited" - Status: "Exited (0) 56 minutes ago" - HostConfig: - NetworkMode: "default" - NetworkSettings: - Networks: - bridge: - IPAMConfig: null - Links: null - Aliases: null - NetworkID: "d687bc59335f0e5c9ee8193e5612e8aee000c8c62ea170cfb99c098f95899d92" - EndpointID: "8ed5115aeaad9abb174f68dcf135b49f11daf597678315231a32ca28441dec6a" - Gateway: "172.18.0.1" - IPAddress: "172.18.0.2" - IPPrefixLen: 16 - IPv6Gateway: "" - GlobalIPv6Address: "" - GlobalIPv6PrefixLen: 0 - MacAddress: "02:42:ac:12:00:02" - Mounts: [] - Volumes: - - - Name: "my-volume" - Driver: "local" - Mountpoint: "" - Labels: null - Scope: "" - Options: null - UsageData: - Size: 0 - RefCount: 0 - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["System"] - /images/{name}/get: - get: - summary: "Export an image" - description: | - Get a tarball containing all images and metadata for a repository. - - If `name` is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the `repositories` file in the tarball, as there were no image names referenced. - - ### Image tarball format - - An image tarball contains one directory per image layer (named using its long ID), each containing these files: - - - `VERSION`: currently `1.0` - the file format version - - `json`: detailed layer information, similar to `docker inspect layer_id` - - `layer.tar`: A tarfile containing the filesystem changes in this layer - - The `layer.tar` file contains `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. - - If the tarball defines a repository, the tarball should also include a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. - - ```json - { - "hello-world": { - "latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1" - } - } - ``` - operationId: "ImageGet" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "Image name or ID" - type: "string" - required: true - tags: ["Image"] - /images/get: - get: - summary: "Export several images" - description: | - Get a tarball containing all images and metadata for several image repositories. - - For each value of the `names` parameter: if it is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. - - For details on the format, see [the export image endpoint](#operation/ImageGet). - operationId: "ImageGetAll" - produces: - - "application/x-tar" - responses: - 200: - description: "no error" - schema: - type: "string" - format: "binary" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "names" - in: "query" - description: "Image names to filter by" - type: "array" - items: - type: "string" - tags: ["Image"] - /images/load: - post: - summary: "Import images" - description: | - Load a set of images and tags into a repository. - - For details on the format, see [the export image endpoint](#operation/ImageGet). - operationId: "ImageLoad" - consumes: - - "application/x-tar" - produces: - - "application/json" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "imagesTarball" - in: "body" - description: "Tar archive containing images" - schema: - type: "string" - format: "binary" - - name: "quiet" - in: "query" - description: "Suppress progress details during load." - type: "boolean" - default: false - tags: ["Image"] - /containers/{id}/exec: - post: - summary: "Create an exec instance" - description: "Run a command inside a running container." - operationId: "ContainerExec" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - $ref: "#/definitions/IdResponse" - 404: - description: "no such container" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such container: c2ada9df5af8" - 409: - description: "container is paused" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execConfig" - in: "body" - description: "Exec configuration" - schema: - type: "object" - properties: - AttachStdin: - type: "boolean" - description: "Attach to `stdin` of the exec command." - AttachStdout: - type: "boolean" - description: "Attach to `stdout` of the exec command." - AttachStderr: - type: "boolean" - description: "Attach to `stderr` of the exec command." - DetachKeys: - type: "string" - description: "Override the key sequence for detaching a container. Format is a single character `[a-Z]` or `ctrl-` where `` is one of: `a-z`, `@`, `^`, `[`, `,` or `_`." - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - Env: - description: "A list of environment variables in the form `[\"VAR=value\", ...]`." - type: "array" - items: - type: "string" - Cmd: - type: "array" - description: "Command to run, as a string or array of strings." - items: - type: "string" - Privileged: - type: "boolean" - description: "Runs the exec process with extended privileges." - default: false - User: - type: "string" - description: "The user, and optionally, group to run the exec process inside the container. Format is one of: `user`, `user:group`, `uid`, or `uid:gid`." - example: - AttachStdin: false - AttachStdout: true - AttachStderr: true - DetachKeys: "ctrl-p,ctrl-q" - Tty: false - Cmd: - - "date" - Env: - - "FOO=bar" - - "BAZ=quux" - required: true - - name: "id" - in: "path" - description: "ID or name of container" - type: "string" - required: true - tags: ["Exec"] - /exec/{id}/start: - post: - summary: "Start an exec instance" - description: "Starts a previously set up exec instance. If detach is true, this endpoint returns immediately after starting the command. Otherwise, it sets up an interactive session with the command." - operationId: "ExecStart" - consumes: - - "application/json" - produces: - - "application/vnd.docker.raw-stream" - responses: - 200: - description: "No error" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Container is stopped or paused" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "execStartConfig" - in: "body" - schema: - type: "object" - properties: - Detach: - type: "boolean" - description: "Detach from the command." - Tty: - type: "boolean" - description: "Allocate a pseudo-TTY." - example: - Detach: false - Tty: false - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - /exec/{id}/resize: - post: - summary: "Resize an exec instance" - description: "Resize the TTY session used by an exec instance. This endpoint only works if `tty` was specified as part of creating and starting the exec instance." - operationId: "ExecResize" - responses: - 201: - description: "No error" - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - - name: "h" - in: "query" - description: "Height of the TTY session in characters" - type: "integer" - - name: "w" - in: "query" - description: "Width of the TTY session in characters" - type: "integer" - tags: ["Exec"] - /exec/{id}/json: - get: - summary: "Inspect an exec instance" - description: "Return low-level information about an exec instance." - operationId: "ExecInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - ID: - type: "string" - Running: - type: "boolean" - ExitCode: - type: "integer" - ProcessConfig: - $ref: "#/definitions/ProcessConfig" - OpenStdin: - type: "boolean" - OpenStderr: - type: "boolean" - OpenStdout: - type: "boolean" - ContainerID: - type: "string" - Pid: - type: "integer" - description: "The system process ID for the exec process." - examples: - application/json: - CanRemove: false - ContainerID: "b53ee82b53a40c7dca428523e34f741f3abc51d9f297a14ff874bf761b995126" - DetachKeys: "" - ExitCode: 2 - ID: "f33bbfb39f5b142420f4759b2348913bd4a8d1a6d7fd56499cb41a1bb91d7b3b" - OpenStderr: true - OpenStdin: true - OpenStdout: true - ProcessConfig: - arguments: - - "-c" - - "exit 2" - entrypoint: "sh" - privileged: false - tty: true - user: "1000" - Running: false - Pid: 42000 - 404: - description: "No such exec instance" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Exec instance ID" - required: true - type: "string" - tags: ["Exec"] - - /volumes: - get: - summary: "List volumes" - operationId: "VolumeList" - produces: ["application/json"] - responses: - 200: - description: "Summary volume data that matches the query" - schema: - type: "object" - required: [Volumes, Warnings] - properties: - Volumes: - type: "array" - x-nullable: false - description: "List of volumes" - items: - $ref: "#/definitions/Volume" - Warnings: - type: "array" - x-nullable: false - description: "Warnings that occurred when fetching the list of volumes" - items: - type: "string" - - examples: - application/json: - Volumes: - - Name: "tardis" - Driver: "local" - Mountpoint: "/var/lib/docker/volumes/tardis" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Scope: "local" - Options: - device: "tmpfs" - o: "size=100m,uid=1000" - type: "tmpfs" - Warnings: [] - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to - process on the volumes list. Available filters: - - - `dangling=` When set to `true` (or `1`), returns all - volumes that are not in use by a container. When set to `false` - (or `0`), only volumes that are in use by one or more - containers are returned. - - `driver=` Matches volumes based on their driver. - - `label=` or `label=:` Matches volumes based on - the presence of a `label` alone or a `label` and a value. - - `name=` Matches all or part of a volume name. - type: "string" - format: "json" - tags: ["Volume"] - - /volumes/create: - post: - summary: "Create a volume" - operationId: "VolumeCreate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 201: - description: "The volume was created successfully" - schema: - $ref: "#/definitions/Volume" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "volumeConfig" - in: "body" - required: true - description: "Volume configuration" - schema: - type: "object" - properties: - Name: - description: "The new volume's name. If not specified, Docker generates a name." - type: "string" - x-nullable: false - Driver: - description: "Name of the volume driver to use." - type: "string" - default: "local" - x-nullable: false - DriverOpts: - description: "A mapping of driver options and values. These options are passed directly to the driver and are driver specific." - type: "object" - additionalProperties: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - Name: "tardis" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - Driver: "custom" - tags: ["Volume"] - - /volumes/{name}: - get: - summary: "Inspect a volume" - operationId: "VolumeInspect" - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Volume" - 404: - description: "No such volume" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - tags: ["Volume"] - - delete: - summary: "Remove a volume" - description: "Instruct the driver to remove the volume." - operationId: "VolumeDelete" - responses: - 204: - description: "The volume was removed" - 404: - description: "No such volume or volume driver" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "Volume is in use and cannot be removed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - required: true - description: "Volume name or ID" - type: "string" - - name: "force" - in: "query" - description: "Force the removal of the volume" - type: "boolean" - default: false - tags: ["Volume"] - /volumes/prune: - post: - summary: "Delete unused volumes" - produces: - - "application/json" - operationId: "VolumePrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune volumes with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - VolumesDeleted: - description: "Volumes that were deleted" - type: "array" - items: - type: "string" - SpaceReclaimed: - description: "Disk space reclaimed in bytes" - type: "integer" - format: "int64" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Volume"] - /networks: - get: - summary: "List networks" - operationId: "NetworkList" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Network" - examples: - application/json: - - Name: "bridge" - Id: "f2de39df4171b0dc801e8002d1d999b77256983dfc63041c0f34030aa3977566" - Created: "2016-10-19T06:21:00.416543526Z" - Scope: "local" - Driver: "bridge" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: - - - Subnet: "172.17.0.0/16" - Containers: - 39b69226f9d79f5634485fb236a23b2fe4e96a0a94128390a7fbbcc167065867: - EndpointID: "ed2419a97c1d9954d05b46e462e7002ea552f216e9b136b80a7db8d98b442eda" - MacAddress: "02:42:ac:11:00:02" - IPv4Address: "172.17.0.2/16" - IPv6Address: "" - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - - Name: "none" - Id: "e086a3893b05ab69242d3c44e49483a3bbbd3a26b46baa8f61ab797c1088d794" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "null" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - - Name: "host" - Id: "13e871235c677f196c4e1ecebb9dc733b9b2d2ab589e30c539efeda84a24215e" - Created: "0001-01-01T00:00:00Z" - Scope: "local" - Driver: "host" - EnableIPv6: false - Internal: false - Attachable: false - Ingress: false - IPAM: - Driver: "default" - Config: [] - Containers: {} - Options: {} - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - JSON encoded value of the filters (a `map[string][]string`) to process on the networks list. Available filters: - - - `driver=` Matches a network's driver. - - `id=` Matches all or part of a network ID. - - `label=` or `label==` of a network label. - - `name=` Matches all or part of a network name. - - `scope=["swarm"|"global"|"local"]` Filters networks by scope (`swarm`, `global`, or `local`). - - `type=["custom"|"builtin"]` Filters networks by type. The `custom` keyword returns all user-defined networks. - type: "string" - tags: ["Network"] - - /networks/{id}: - get: - summary: "Inspect a network" - operationId: "NetworkInspect" - produces: - - "application/json" - responses: - 200: - description: "No error" - schema: - $ref: "#/definitions/Network" - 404: - description: "Network not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "verbose" - in: "query" - description: "Detailed inspect output for troubleshooting" - type: "boolean" - default: false - tags: ["Network"] - - delete: - summary: "Remove a network" - operationId: "NetworkDelete" - responses: - 204: - description: "No error" - 403: - description: "operation not supported for pre-defined networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such network" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - tags: ["Network"] - - /networks/create: - post: - summary: "Create a network" - operationId: "NetworkCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "No error" - schema: - type: "object" - properties: - Id: - description: "The ID of the created network." - type: "string" - Warning: - type: "string" - example: - Id: "22be93d5babb089c5aab8dbc369042fad48ff791584ca2da2100db837a1c7c30" - Warning: "" - 403: - description: "operation not supported for pre-defined networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "plugin not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "networkConfig" - in: "body" - description: "Network configuration" - required: true - schema: - type: "object" - required: ["Name"] - properties: - Name: - description: "The network's name." - type: "string" - CheckDuplicate: - description: "Check for networks with duplicate names. Since Network is primarily keyed based on a random ID and not on the name, and network name is strictly a user-friendly alias to the network which is uniquely identified using ID, there is no guaranteed way to check for duplicates. CheckDuplicate is there to provide a best effort checking of any networks which has the same name but it is not guaranteed to catch all name collisions." - type: "boolean" - Driver: - description: "Name of the network driver plugin to use." - type: "string" - default: "bridge" - Internal: - description: "Restrict external access to the network." - type: "boolean" - Attachable: - description: "Globally scoped network is manually attachable by regular containers from workers in swarm mode." - type: "boolean" - Ingress: - description: "Ingress network is the network which provides the routing-mesh in swarm mode." - type: "boolean" - IPAM: - description: "Optional custom IP scheme for the network." - $ref: "#/definitions/IPAM" - EnableIPv6: - description: "Enable IPv6 on the network." - type: "boolean" - Options: - description: "Network specific options to be used by the drivers." - type: "object" - additionalProperties: - type: "string" - Labels: - description: "User-defined key/value metadata." - type: "object" - additionalProperties: - type: "string" - example: - Name: "isolated_nw" - CheckDuplicate: false - Driver: "bridge" - EnableIPv6: true - IPAM: - Driver: "default" - Config: - - Subnet: "172.20.0.0/16" - IPRange: "172.20.10.0/24" - Gateway: "172.20.10.11" - - Subnet: "2001:db8:abcd::/64" - Gateway: "2001:db8:abcd::1011" - Options: - foo: "bar" - Internal: true - Attachable: false - Ingress: false - Options: - com.docker.network.bridge.default_bridge: "true" - com.docker.network.bridge.enable_icc: "true" - com.docker.network.bridge.enable_ip_masquerade: "true" - com.docker.network.bridge.host_binding_ipv4: "0.0.0.0" - com.docker.network.bridge.name: "docker0" - com.docker.network.driver.mtu: "1500" - Labels: - com.example.some-label: "some-value" - com.example.some-other-label: "some-other-value" - tags: ["Network"] - - /networks/{id}/connect: - post: - summary: "Connect a container to a network" - operationId: "NetworkConnect" - consumes: - - "application/octet-stream" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - properties: - Container: - type: "string" - description: "The ID or name of the container to connect to the network." - EndpointConfig: - $ref: "#/definitions/EndpointSettings" - example: - Container: "3613f73ba0e4" - EndpointConfig: - IPAMConfig: - IPv4Address: "172.24.56.89" - IPv6Address: "2001:db8::5689" - tags: ["Network"] - - /networks/{id}/disconnect: - post: - summary: "Disconnect a container from a network" - operationId: "NetworkDisconnect" - consumes: - - "application/json" - responses: - 200: - description: "No error" - 403: - description: "Operation not supported for swarm scoped networks" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "Network or container not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "Network ID or name" - required: true - type: "string" - - name: "container" - in: "body" - required: true - schema: - type: "object" - properties: - Container: - type: "string" - description: "The ID or name of the container to disconnect from the network." - Force: - type: "boolean" - description: "Force the container to disconnect from the network." - tags: ["Network"] - /networks/prune: - post: - summary: "Delete unused networks" - produces: - - "application/json" - operationId: "NetworkPrune" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the prune list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `until=` Prune networks created before this timestamp. The `` can be Unix timestamps, date formatted timestamps, or Go duration strings (e.g. `10m`, `1h30m`) computed relative to the daemon machine’s time. - - `label` (`label=`, `label==`, `label!=`, or `label!==`) Prune networks with (or without, in case `label!=...` is used) the specified labels. - type: "string" - responses: - 200: - description: "No error" - schema: - type: "object" - properties: - NetworksDeleted: - description: "Networks that were deleted" - type: "array" - items: - type: "string" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Network"] - /plugins: - get: - summary: "List plugins" - operationId: "PluginList" - description: "Returns information about installed plugins." - produces: ["application/json"] - responses: - 200: - description: "No error" - schema: - type: "array" - items: - $ref: "#/definitions/Plugin" - example: - - Id: "5724e2c8652da337ab2eedd19fc6fc0ec908e4bd907c7421bf6a8dfc70c4c078" - Name: "tiborvass/sample-volume-plugin" - Tag: "latest" - Active: true - Settings: - Env: - - "DEBUG=0" - Args: null - Devices: null - Config: - Description: "A sample volume plugin for Docker" - Documentation: "https://docs.docker.com/engine/extend/plugins/" - Interface: - Types: - - "docker.volumedriver/1.0" - Socket: "plugins.sock" - Entrypoint: - - "/usr/bin/sample-volume-plugin" - - "/data" - WorkDir: "" - User: {} - Network: - Type: "" - Linux: - Capabilities: null - AllowAllDevices: false - Devices: null - Mounts: null - PropagatedMount: "/data" - Env: - - Name: "DEBUG" - Description: "If set, prints debug messages" - Settable: null - Value: "0" - Args: - Name: "args" - Description: "command line arguments" - Settable: null - Value: [] - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the plugin list. Available filters: - - - `capability=` - - `enable=|` - tags: ["Plugin"] - - /plugins/privileges: - get: - summary: "Get plugin privileges" - operationId: "GetPluginPrivileges" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - description: "Describes a permission the user has to accept upon installing the plugin." - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - tags: - - "Plugin" - - /plugins/pull: - post: - summary: "Install a plugin" - operationId: "PluginPull" - description: | - Pulls and installs a plugin. After the plugin is installed, it can be enabled using the [`POST /plugins/{name}/enable` endpoint](#operation/PostPluginsEnable). - produces: - - "application/json" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "remote" - in: "query" - description: | - Remote reference for plugin to install. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "name" - in: "query" - description: | - Local name for the pulled plugin. - - The `:latest` tag is optional, and is used as the default if omitted. - required: false - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration to use when pulling a plugin from a registry. [See the authentication section for details.](#section/Authentication)" - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - description: "Describes a permission accepted by the user upon installing the plugin." - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/{name}/json: - get: - summary: "Inspect a plugin" - operationId: "PluginInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - tags: ["Plugin"] - /plugins/{name}: - delete: - summary: "Remove a plugin" - operationId: "PluginDelete" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Plugin" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - - name: "force" - in: "query" - description: "Disable the plugin before removing. This may result in issues if the plugin is in use by a container." - type: "boolean" - default: false - tags: ["Plugin"] - /plugins/{name}/enable: - post: - summary: "Enable a plugin" - operationId: "PluginEnable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - - name: "timeout" - in: "query" - description: "Set the HTTP client timeout (in seconds)" - type: "integer" - default: 0 - tags: ["Plugin"] - /plugins/{name}/disable: - post: - summary: "Disable a plugin" - operationId: "PluginDisable" - responses: - 200: - description: "no error" - 404: - description: "plugin is not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - tags: ["Plugin"] - /plugins/{name}/upgrade: - post: - summary: "Upgrade a plugin" - operationId: "PluginUpgrade" - responses: - 204: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - - name: "remote" - in: "query" - description: | - Remote reference to upgrade to. - - The `:latest` tag is optional, and is used as the default if omitted. - required: true - type: "string" - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration to use when pulling a plugin from a registry. [See the authentication section for details.](#section/Authentication)" - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - description: "Describes a permission accepted by the user upon installing the plugin." - type: "object" - properties: - Name: - type: "string" - Description: - type: "string" - Value: - type: "array" - items: - type: "string" - example: - - Name: "network" - Description: "" - Value: - - "host" - - Name: "mount" - Description: "" - Value: - - "/data" - - Name: "device" - Description: "" - Value: - - "/dev/cpu_dma_latency" - tags: ["Plugin"] - /plugins/create: - post: - summary: "Create a plugin" - operationId: "PluginCreate" - consumes: - - "application/x-tar" - responses: - 204: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "name" - in: "query" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - - name: "tarContext" - in: "body" - description: "Path to tar containing plugin rootfs and manifest" - schema: - type: "string" - format: "binary" - tags: ["Plugin"] - /plugins/{name}/push: - post: - summary: "Push a plugin" - operationId: "PluginPush" - description: | - Push a plugin to the registry. - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - responses: - 200: - description: "no error" - 404: - description: "plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /plugins/{name}/set: - post: - summary: "Configure a plugin" - operationId: "PluginSet" - consumes: - - "application/json" - parameters: - - name: "name" - in: "path" - description: "The name of the plugin. The `:latest` tag is optional, and is the default if omitted." - required: true - type: "string" - - name: "body" - in: "body" - schema: - type: "array" - items: - type: "string" - example: ["DEBUG=1"] - responses: - 204: - description: "No error" - 404: - description: "Plugin not installed" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "Server error" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Plugin"] - /nodes: - get: - summary: "List nodes" - operationId: "NodeList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Node" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - description: | - Filters to process on the nodes list, encoded as JSON (a `map[string][]string`). - - Available filters: - - `id=` - - `label=` - - `membership=`(`accepted`|`pending`)` - - `name=` - - `role=`(`manager`|`worker`)` - type: "string" - tags: ["Node"] - /nodes/{id}: - get: - summary: "Inspect a node" - operationId: "NodeInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Node" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - tags: ["Node"] - delete: - summary: "Delete a node" - operationId: "NodeDelete" - responses: - 200: - description: "no error" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the node" - type: "string" - required: true - - name: "force" - in: "query" - description: "Force remove a node from the swarm" - default: false - type: "boolean" - tags: ["Node"] - /nodes/{id}/update: - post: - summary: "Update a node" - operationId: "NodeUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such node" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID of the node" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/NodeSpec" - - name: "version" - in: "query" - description: "The version number of the node object being updated. This is required to avoid conflicting writes." - type: "integer" - format: "int64" - required: true - tags: ["Node"] - /swarm: - get: - summary: "Inspect swarm" - operationId: "SwarmInspect" - responses: - 200: - description: "no error" - schema: - allOf: - - $ref: "#/definitions/ClusterInfo" - - type: "object" - properties: - JoinTokens: - description: "The tokens workers and managers need to join the swarm." - type: "object" - properties: - Worker: - description: "The token workers can use to join the swarm." - type: "string" - Manager: - description: "The token managers can use to join the swarm." - type: "string" - example: - CreatedAt: "2016-08-15T16:00:20.349727406Z" - Spec: - Dispatcher: - HeartbeatPeriod: 5000000000 - Orchestration: - TaskHistoryRetentionLimit: 10 - CAConfig: - NodeCertExpiry: 7776000000000000 - Raft: - LogEntriesForSlowFollowers: 500 - HeartbeatTick: 1 - SnapshotInterval: 10000 - ElectionTick: 3 - TaskDefaults: {} - EncryptionConfig: - AutoLockManagers: false - Name: "default" - JoinTokens: - Worker: "SWMTKN-1-1h8aps2yszaiqmz2l3oc5392pgk8e49qhx2aj3nyv0ui0hez2a-6qmn92w6bu3jdvnglku58u11a" - Manager: "SWMTKN-1-1h8aps2yszaiqmz2l3oc5392pgk8e49qhx2aj3nyv0ui0hez2a-8llk83c4wm9lwioey2s316r9l" - ID: "70ilmkj2f6sp2137c753w2nmt" - UpdatedAt: "2016-08-15T16:32:09.623207604Z" - Version: - Index: 51 - 404: - description: "no such swarm" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/init: - post: - summary: "Initialize a new swarm" - operationId: "SwarmInit" - produces: - - "application/json" - - "text/plain" - responses: - 200: - description: "no error" - schema: - description: "The node ID" - type: "string" - example: "7v2t30z9blmxuhnyo6s4cpenp" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - ListenAddr: - description: "Listen address used for inter-manager communication, as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP). This can either be an address/port combination in the form `192.168.1.1:4567`, or an interface followed by a port number, like `eth0:4567`. If the port number is omitted, the default swarm listening port is used." - type: "string" - AdvertiseAddr: - description: "Externally reachable address advertised to other nodes. This can either be an address/port combination in the form `192.168.1.1:4567`, or an interface followed by a port number, like `eth0:4567`. If the port number is omitted, the port number from the listen address is used. If `AdvertiseAddr` is not specified, it will be automatically detected when possible." - type: "string" - ForceNewCluster: - description: "Force creation of a new swarm." - type: "boolean" - Spec: - $ref: "#/definitions/SwarmSpec" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - ForceNewCluster: false - Spec: - Orchestration: {} - Raft: {} - Dispatcher: {} - CAConfig: {} - EncryptionConfig: - AutoLockManagers: false - tags: ["Swarm"] - /swarm/join: - post: - summary: "Join an existing swarm" - operationId: "SwarmJoin" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is already part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - ListenAddr: - description: "Listen address used for inter-manager communication if the node gets promoted to manager, as well as determining the networking interface used for the VXLAN Tunnel Endpoint (VTEP)." - type: "string" - AdvertiseAddr: - description: "Externally reachable address advertised to other nodes. This can either be an address/port combination in the form `192.168.1.1:4567`, or an interface followed by a port number, like `eth0:4567`. If the port number is omitted, the port number from the listen address is used. If `AdvertiseAddr` is not specified, it will be automatically detected when possible." - type: "string" - RemoteAddrs: - description: "Addresses of manager nodes already participating in the swarm." - type: "string" - JoinToken: - description: "Secret token for joining this swarm." - type: "string" - example: - ListenAddr: "0.0.0.0:2377" - AdvertiseAddr: "192.168.1.1:2377" - RemoteAddrs: - - "node1:2377" - JoinToken: "SWMTKN-1-3pu6hszjas19xyp7ghgosyx9k8atbfcr8p2is99znpy26u2lkl-7p73s1dx5in4tatdymyhg9hu2" - tags: ["Swarm"] - /swarm/leave: - post: - summary: "Leave a swarm" - operationId: "SwarmLeave" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "force" - description: "Force leave swarm, even if this is the last manager or that it will break the cluster." - in: "query" - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/update: - post: - summary: "Update a swarm" - operationId: "SwarmUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - $ref: "#/definitions/SwarmSpec" - - name: "version" - in: "query" - description: "The version number of the swarm object being updated. This is required to avoid conflicting writes." - type: "integer" - format: "int64" - required: true - - name: "rotateWorkerToken" - in: "query" - description: "Rotate the worker join token." - type: "boolean" - default: false - - name: "rotateManagerToken" - in: "query" - description: "Rotate the manager join token." - type: "boolean" - default: false - - name: "rotateManagerUnlockKey" - in: "query" - description: "Rotate the manager unlock key." - type: "boolean" - default: false - tags: ["Swarm"] - /swarm/unlockkey: - get: - summary: "Get the unlock key" - operationId: "SwarmUnlockkey" - consumes: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "object" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /swarm/unlock: - post: - summary: "Unlock a locked manager" - operationId: "SwarmUnlock" - consumes: - - "application/json" - produces: - - "application/json" - parameters: - - name: "body" - in: "body" - required: true - schema: - type: "object" - properties: - UnlockKey: - description: "The swarm's unlock key." - type: "string" - example: - UnlockKey: "SWMKEY-1-7c37Cc8654o6p38HnroywCi19pllOnGtbdZEgtKxZu8" - responses: - 200: - description: "no error" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - tags: ["Swarm"] - /services: - get: - summary: "List services" - operationId: "ServiceList" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Service" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the services list. Available filters: - - - `id=` - - `label=` - - `mode=["replicated"|"global"]` - - `name=` - tags: ["Service"] - /services/create: - post: - summary: "Create a service" - operationId: "ServiceCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - type: "object" - properties: - ID: - description: "The ID of the created service." - type: "string" - Warning: - description: "Optional warning message" - type: "string" - example: - ID: "ak7w3gjqoa3kuz8xcpnyy0pvl" - Warning: "unable to pin image doesnotexist:latest to digest: image library/doesnotexist:latest not found" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 403: - description: "network is not eligible for services" - schema: - $ref: "#/definitions/ErrorResponse" - 409: - description: "name conflicts with an existing service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "web" - TaskTemplate: - ContainerSpec: - Image: "nginx:alpine" - Mounts: - - - ReadOnly: true - Source: "web-data" - Target: "/usr/share/nginx/html" - Type: "volume" - VolumeOptions: - DriverConfig: {} - Labels: - com.example.something: "something-value" - Hosts: ["10.10.10.10 host1", "ABCD:EF01:2345:6789:ABCD:EF01:2345:6789 host2"] - User: "33" - DNSConfig: - Nameservers: ["8.8.8.8"] - Search: ["example.org"] - Options: ["timeout:3"] - LogDriver: - Name: "json-file" - Options: - max-file: "3" - max-size: "10M" - Placement: {} - Resources: - Limits: - MemoryBytes: 104857600 - Reservations: {} - RestartPolicy: - Condition: "on-failure" - Delay: 10000000000 - MaxAttempts: 10 - Mode: - Replicated: - Replicas: 4 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Ports: - - - Protocol: "tcp" - PublishedPort: 8080 - TargetPort: 80 - Labels: - foo: "bar" - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration for pulling from private registries. [See the authentication section for details.](#section/Authentication)" - type: "string" - tags: ["Service"] - /services/{id}: - get: - summary: "Inspect a service" - operationId: "ServiceInspect" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Service" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "insertDefaults" - in: "query" - description: "Fill empty fields with default values." - type: "boolean" - default: false - tags: ["Service"] - delete: - summary: "Delete a service" - operationId: "ServiceDelete" - responses: - 200: - description: "no error" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - tags: ["Service"] - /services/{id}/update: - post: - summary: "Update a service" - operationId: "ServiceUpdate" - consumes: ["application/json"] - produces: ["application/json"] - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/ServiceUpdateResponse" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID or name of service." - required: true - type: "string" - - name: "body" - in: "body" - required: true - schema: - allOf: - - $ref: "#/definitions/ServiceSpec" - - type: "object" - example: - Name: "top" - TaskTemplate: - ContainerSpec: - Image: "busybox" - Args: - - "top" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ForceUpdate: 0 - Mode: - Replicated: - Replicas: 1 - UpdateConfig: - Parallelism: 2 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - RollbackConfig: - Parallelism: 1 - Delay: 1000000000 - FailureAction: "pause" - Monitor: 15000000000 - MaxFailureRatio: 0.15 - EndpointSpec: - Mode: "vip" - - - name: "version" - in: "query" - description: "The version number of the service object being updated. This is required to avoid conflicting writes." - required: true - type: "integer" - - name: "registryAuthFrom" - in: "query" - type: "string" - description: "If the X-Registry-Auth header is not specified, this - parameter indicates where to find registry authorization credentials. The - valid values are `spec` and `previous-spec`." - default: "spec" - - name: "rollback" - in: "query" - type: "string" - description: "Set to this parameter to `previous` to cause a - server-side rollback to the previous service spec. The supplied spec will be - ignored in this case." - - name: "X-Registry-Auth" - in: "header" - description: "A base64-encoded auth configuration for pulling from private registries. [See the authentication section for details.](#section/Authentication)" - type: "string" - - tags: ["Service"] - /services/{id}/logs: - get: - summary: "Get service logs" - description: | - Get `stdout` and `stderr` logs from a service. - - **Note**: This endpoint works only for services with the `json-file` or `journald` logging drivers. - operationId: "ServiceLogs" - produces: - - "application/vnd.docker.raw-stream" - - "application/json" - responses: - 101: - description: "logs returned as a stream" - schema: - type: "string" - format: "binary" - 200: - description: "logs returned as a string in response body" - schema: - type: "string" - 404: - description: "no such service" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such service: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID or name of the service" - type: "string" - - name: "details" - in: "query" - description: "Show service context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: | - Return the logs as a stream. - - This will return a `101` HTTP response with a `Connection: upgrade` header, then hijack the HTTP connection to send raw output. For more information about hijacking and the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach). - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: "Only return this number of log lines from the end of the logs. Specify as an integer or `all` to output all log lines." - type: "string" - default: "all" - tags: ["Service"] - /tasks: - get: - summary: "List tasks" - operationId: "TaskList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Task" - example: - - ID: "0kzzo1i0y4jz6027t0k7aezc7" - Version: - Index: 71 - CreatedAt: "2016-06-07T21:07:31.171892745Z" - UpdatedAt: "2016-06-07T21:07:31.376370513Z" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:31.290032978Z" - State: "running" - Message: "started" - ContainerStatus: - ContainerID: "e5d62702a1b48d01c3e02ca1e0212a250801fa8d67caca0b6f35919ebc12f035" - PID: 677 - DesiredState: "running" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.10/16" - - ID: "1yljwbmlr8er2waf8orvqpwms" - Version: - Index: 30 - CreatedAt: "2016-06-07T21:07:30.019104782Z" - UpdatedAt: "2016-06-07T21:07:30.231958098Z" - Name: "hopeful_cori" - Spec: - ContainerSpec: - Image: "redis" - Resources: - Limits: {} - Reservations: {} - RestartPolicy: - Condition: "any" - MaxAttempts: 0 - Placement: {} - ServiceID: "9mnpnzenvg8p8tdbtq4wvbkcz" - Slot: 1 - NodeID: "60gvrl6tm78dmak4yl7srz94v" - Status: - Timestamp: "2016-06-07T21:07:30.202183143Z" - State: "shutdown" - Message: "shutdown" - ContainerStatus: - ContainerID: "1cf8d63d18e79668b0004a4be4c6ee58cddfad2dae29506d8781581d0688a213" - DesiredState: "shutdown" - NetworksAttachments: - - Network: - ID: "4qvuz4ko70xaltuqbt8956gd1" - Version: - Index: 18 - CreatedAt: "2016-06-07T20:31:11.912919752Z" - UpdatedAt: "2016-06-07T21:07:29.955277358Z" - Spec: - Name: "ingress" - Labels: - com.docker.swarm.internal: "true" - DriverConfiguration: {} - IPAMOptions: - Driver: {} - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - DriverState: - Name: "overlay" - Options: - com.docker.network.driver.overlay.vxlanid_list: "256" - IPAMOptions: - Driver: - Name: "default" - Configs: - - Subnet: "10.255.0.0/16" - Gateway: "10.255.0.1" - Addresses: - - "10.255.0.5/16" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the tasks list. Available filters: - - - `desired-state=(running | shutdown | accepted)` - - `id=` - - `label=key` or `label="key=value"` - - `name=` - - `node=` - - `service=` - tags: ["Task"] - /tasks/{id}: - get: - summary: "Inspect a task" - operationId: "TaskInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Task" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "ID of the task" - required: true - type: "string" - tags: ["Task"] - /tasks/{id}/logs: - get: - summary: "Get task logs" - description: | - Get `stdout` and `stderr` logs from a task. - - **Note**: This endpoint works only for services with the `json-file` or `journald` logging drivers. - operationId: "TaskLogs" - produces: - - "application/vnd.docker.raw-stream" - - "application/json" - responses: - 101: - description: "logs returned as a stream" - schema: - type: "string" - format: "binary" - 200: - description: "logs returned as a string in response body" - schema: - type: "string" - 404: - description: "no such task" - schema: - $ref: "#/definitions/ErrorResponse" - examples: - application/json: - message: "No such task: c2ada9df5af8" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - description: "ID of the task" - type: "string" - - name: "details" - in: "query" - description: "Show task context and extra details provided to logs." - type: "boolean" - default: false - - name: "follow" - in: "query" - description: | - Return the logs as a stream. - - This will return a `101` HTTP response with a `Connection: upgrade` header, then hijack the HTTP connection to send raw output. For more information about hijacking and the stream format, [see the documentation for the attach endpoint](#operation/ContainerAttach). - type: "boolean" - default: false - - name: "stdout" - in: "query" - description: "Return logs from `stdout`" - type: "boolean" - default: false - - name: "stderr" - in: "query" - description: "Return logs from `stderr`" - type: "boolean" - default: false - - name: "since" - in: "query" - description: "Only return logs since this time, as a UNIX timestamp" - type: "integer" - default: 0 - - name: "timestamps" - in: "query" - description: "Add timestamps to every log line" - type: "boolean" - default: false - - name: "tail" - in: "query" - description: "Only return this number of log lines from the end of the logs. Specify as an integer or `all` to output all log lines." - type: "string" - default: "all" - /secrets: - get: - summary: "List secrets" - operationId: "SecretList" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - type: "array" - items: - $ref: "#/definitions/Secret" - example: - - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "filters" - in: "query" - type: "string" - description: | - A JSON encoded value of the filters (a `map[string][]string`) to process on the secrets list. Available filters: - - - `id=` - - `label= or label==value` - - `name=` - - `names=` - tags: ["Secret"] - /secrets/create: - post: - summary: "Create a secret" - operationId: "SecretCreate" - consumes: - - "application/json" - produces: - - "application/json" - responses: - 201: - description: "no error" - schema: - type: "object" - properties: - ID: - description: "The ID of the created secret." - type: "string" - example: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - 409: - description: "name conflicts with an existing object" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "body" - in: "body" - schema: - allOf: - - $ref: "#/definitions/SecretSpec" - - type: "object" - example: - Name: "app-key.crt" - Labels: - foo: "bar" - Data: "VEhJUyBJUyBOT1QgQSBSRUFMIENFUlRJRklDQVRFCg==" - tags: ["Secret"] - /secrets/{id}: - get: - summary: "Inspect a secret" - operationId: "SecretInspect" - produces: - - "application/json" - responses: - 200: - description: "no error" - schema: - $ref: "#/definitions/Secret" - example: - ID: "ktnbjxoalbkvbvedmg1urrz8h" - Version: - Index: 11 - CreatedAt: "2016-11-05T01:20:17.327670065Z" - UpdatedAt: "2016-11-05T01:20:17.327670065Z" - Spec: - Name: "app-dev.crt" - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - delete: - summary: "Delete a secret" - operationId: "SecretDelete" - produces: - - "application/json" - responses: - 204: - description: "no error" - 404: - description: "secret not found" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - required: true - type: "string" - description: "ID of the secret" - tags: ["Secret"] - /secrets/{id}/update: - post: - summary: "Update a Secret" - operationId: "SecretUpdate" - responses: - 200: - description: "no error" - 400: - description: "bad parameter" - schema: - $ref: "#/definitions/ErrorResponse" - 404: - description: "no such secret" - schema: - $ref: "#/definitions/ErrorResponse" - 500: - description: "server error" - schema: - $ref: "#/definitions/ErrorResponse" - 503: - description: "node is not part of a swarm" - schema: - $ref: "#/definitions/ErrorResponse" - parameters: - - name: "id" - in: "path" - description: "The ID or name of the secret" - type: "string" - required: true - - name: "body" - in: "body" - schema: - $ref: "#/definitions/SecretSpec" - description: "The spec of the secret to update. Currently, only the Labels field can be updated. All other fields must remain unchanged from the [SecretInspect endpoint](#operation/SecretInspect) response values." - - name: "version" - in: "query" - description: "The version number of the secret object being updated. This is required to avoid conflicting writes." - type: "integer" - format: "int64" - required: true - tags: ["Secret"] diff --git a/vendor/github.com/docker/docker/api/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go deleted file mode 100644 index 056af6b842..0000000000 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ /dev/null @@ -1,22 +0,0 @@ -package types - -// AuthConfig contains authorization information for connecting to a Registry -type AuthConfig struct { - Username string `json:"username,omitempty"` - Password string `json:"password,omitempty"` - Auth string `json:"auth,omitempty"` - - // Email is an optional value associated with the username. - // This field is deprecated and will be removed in a later - // version of docker. - Email string `json:"email,omitempty"` - - ServerAddress string `json:"serveraddress,omitempty"` - - // IdentityToken is used to authenticate the user and get - // an access token for the registry. - IdentityToken string `json:"identitytoken,omitempty"` - - // RegistryToken is a bearer token to be sent to a registry - RegistryToken string `json:"registrytoken,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go b/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go deleted file mode 100644 index 931ae10ab1..0000000000 --- a/vendor/github.com/docker/docker/api/types/blkiodev/blkio.go +++ /dev/null @@ -1,23 +0,0 @@ -package blkiodev - -import "fmt" - -// WeightDevice is a structure that holds device:weight pair -type WeightDevice struct { - Path string - Weight uint16 -} - -func (w *WeightDevice) String() string { - return fmt.Sprintf("%s:%d", w.Path, w.Weight) -} - -// ThrottleDevice is a structure that holds device:rate_per_second pair -type ThrottleDevice struct { - Path string - Rate uint64 -} - -func (t *ThrottleDevice) String() string { - return fmt.Sprintf("%s:%d", t.Path, t.Rate) -} diff --git a/vendor/github.com/docker/docker/api/types/client.go b/vendor/github.com/docker/docker/api/types/client.go deleted file mode 100644 index 00255271b2..0000000000 --- a/vendor/github.com/docker/docker/api/types/client.go +++ /dev/null @@ -1,372 +0,0 @@ -package types - -import ( - "bufio" - "io" - "net" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/go-units" -) - -// CheckpointCreateOptions holds parameters to create a checkpoint from a container -type CheckpointCreateOptions struct { - CheckpointID string - CheckpointDir string - Exit bool -} - -// CheckpointListOptions holds parameters to list checkpoints for a container -type CheckpointListOptions struct { - CheckpointDir string -} - -// CheckpointDeleteOptions holds parameters to delete a checkpoint from a container -type CheckpointDeleteOptions struct { - CheckpointID string - CheckpointDir string -} - -// ContainerAttachOptions holds parameters to attach to a container. -type ContainerAttachOptions struct { - Stream bool - Stdin bool - Stdout bool - Stderr bool - DetachKeys string - Logs bool -} - -// ContainerCommitOptions holds parameters to commit changes into a container. -type ContainerCommitOptions struct { - Reference string - Comment string - Author string - Changes []string - Pause bool - Config *container.Config -} - -// ContainerExecInspect holds information returned by exec inspect. -type ContainerExecInspect struct { - ExecID string - ContainerID string - Running bool - ExitCode int - Pid int -} - -// ContainerListOptions holds parameters to list containers with. -type ContainerListOptions struct { - Quiet bool - Size bool - All bool - Latest bool - Since string - Before string - Limit int - Filters filters.Args -} - -// ContainerLogsOptions holds parameters to filter logs with. -type ContainerLogsOptions struct { - ShowStdout bool - ShowStderr bool - Since string - Timestamps bool - Follow bool - Tail string - Details bool -} - -// ContainerRemoveOptions holds parameters to remove containers. -type ContainerRemoveOptions struct { - RemoveVolumes bool - RemoveLinks bool - Force bool -} - -// ContainerStartOptions holds parameters to start containers. -type ContainerStartOptions struct { - CheckpointID string - CheckpointDir string -} - -// CopyToContainerOptions holds information -// about files to copy into a container -type CopyToContainerOptions struct { - AllowOverwriteDirWithFile bool - CopyUIDGID bool -} - -// EventsOptions holds parameters to filter events with. -type EventsOptions struct { - Since string - Until string - Filters filters.Args -} - -// NetworkListOptions holds parameters to filter the list of networks with. -type NetworkListOptions struct { - Filters filters.Args -} - -// HijackedResponse holds connection information for a hijacked request. -type HijackedResponse struct { - Conn net.Conn - Reader *bufio.Reader -} - -// Close closes the hijacked connection and reader. -func (h *HijackedResponse) Close() { - h.Conn.Close() -} - -// CloseWriter is an interface that implements structs -// that close input streams to prevent from writing. -type CloseWriter interface { - CloseWrite() error -} - -// CloseWrite closes a readWriter for writing. -func (h *HijackedResponse) CloseWrite() error { - if conn, ok := h.Conn.(CloseWriter); ok { - return conn.CloseWrite() - } - return nil -} - -// ImageBuildOptions holds the information -// necessary to build images. -type ImageBuildOptions struct { - Tags []string - SuppressOutput bool - RemoteContext string - NoCache bool - Remove bool - ForceRemove bool - PullParent bool - Isolation container.Isolation - CPUSetCPUs string - CPUSetMems string - CPUShares int64 - CPUQuota int64 - CPUPeriod int64 - Memory int64 - MemorySwap int64 - CgroupParent string - NetworkMode string - ShmSize int64 - Dockerfile string - Ulimits []*units.Ulimit - // BuildArgs needs to be a *string instead of just a string so that - // we can tell the difference between "" (empty string) and no value - // at all (nil). See the parsing of buildArgs in - // api/server/router/build/build_routes.go for even more info. - BuildArgs map[string]*string - AuthConfigs map[string]AuthConfig - Context io.Reader - Labels map[string]string - // squash the resulting image's layers to the parent - // preserves the original image and creates a new one from the parent with all - // the changes applied to a single layer - Squash bool - // CacheFrom specifies images that are used for matching cache. Images - // specified here do not need to have a valid parent chain to match cache. - CacheFrom []string - SecurityOpt []string - ExtraHosts []string // List of extra hosts - Target string -} - -// ImageBuildResponse holds information -// returned by a server after building -// an image. -type ImageBuildResponse struct { - Body io.ReadCloser - OSType string -} - -// ImageCreateOptions holds information to create images. -type ImageCreateOptions struct { - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry -} - -// ImageImportSource holds source information for ImageImport -type ImageImportSource struct { - Source io.Reader // Source is the data to send to the server to create this image from. You must set SourceName to "-" to leverage this. - SourceName string // SourceName is the name of the image to pull. Set to "-" to leverage the Source attribute. -} - -// ImageImportOptions holds information to import images from the client host. -type ImageImportOptions struct { - Tag string // Tag is the name to tag this image with. This attribute is deprecated. - Message string // Message is the message to tag the image with - Changes []string // Changes are the raw changes to apply to this image -} - -// ImageListOptions holds parameters to filter the list of images with. -type ImageListOptions struct { - All bool - Filters filters.Args -} - -// ImageLoadResponse returns information to the client about a load process. -type ImageLoadResponse struct { - // Body must be closed to avoid a resource leak - Body io.ReadCloser - JSON bool -} - -// ImagePullOptions holds information to pull images. -type ImagePullOptions struct { - All bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - PrivilegeFunc RequestPrivilegeFunc -} - -// RequestPrivilegeFunc is a function interface that -// clients can supply to retry operations after -// getting an authorization error. -// This function returns the registry authentication -// header value in base 64 format, or an error -// if the privilege request fails. -type RequestPrivilegeFunc func() (string, error) - -//ImagePushOptions holds information to push images. -type ImagePushOptions ImagePullOptions - -// ImageRemoveOptions holds parameters to remove images. -type ImageRemoveOptions struct { - Force bool - PruneChildren bool -} - -// ImageSearchOptions holds parameters to search images with. -type ImageSearchOptions struct { - RegistryAuth string - PrivilegeFunc RequestPrivilegeFunc - Filters filters.Args - Limit int -} - -// ResizeOptions holds parameters to resize a tty. -// It can be used to resize container ttys and -// exec process ttys too. -type ResizeOptions struct { - Height uint - Width uint -} - -// NodeListOptions holds parameters to list nodes with. -type NodeListOptions struct { - Filters filters.Args -} - -// NodeRemoveOptions holds parameters to remove nodes with. -type NodeRemoveOptions struct { - Force bool -} - -// ServiceCreateOptions contains the options to use when creating a service. -type ServiceCreateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string -} - -// ServiceCreateResponse contains the information returned to a client -// on the creation of a new service. -type ServiceCreateResponse struct { - // ID is the ID of the created service. - ID string - // Warnings is a set of non-fatal warning messages to pass on to the user. - Warnings []string `json:",omitempty"` -} - -// Values for RegistryAuthFrom in ServiceUpdateOptions -const ( - RegistryAuthFromSpec = "spec" - RegistryAuthFromPreviousSpec = "previous-spec" -) - -// ServiceUpdateOptions contains the options to be used for updating services. -type ServiceUpdateOptions struct { - // EncodedRegistryAuth is the encoded registry authorization credentials to - // use when updating the service. - // - // This field follows the format of the X-Registry-Auth header. - EncodedRegistryAuth string - - // TODO(stevvooe): Consider moving the version parameter of ServiceUpdate - // into this field. While it does open API users up to racy writes, most - // users may not need that level of consistency in practice. - - // RegistryAuthFrom specifies where to find the registry authorization - // credentials if they are not given in EncodedRegistryAuth. Valid - // values are "spec" and "previous-spec". - RegistryAuthFrom string - - // Rollback indicates whether a server-side rollback should be - // performed. When this is set, the provided spec will be ignored. - // The valid values are "previous" and "none". An empty value is the - // same as "none". - Rollback string -} - -// ServiceListOptions holds parameters to list services with. -type ServiceListOptions struct { - Filters filters.Args -} - -// ServiceInspectOptions holds parameters related to the "service inspect" -// operation. -type ServiceInspectOptions struct { - InsertDefaults bool -} - -// TaskListOptions holds parameters to list tasks with. -type TaskListOptions struct { - Filters filters.Args -} - -// PluginRemoveOptions holds parameters to remove plugins. -type PluginRemoveOptions struct { - Force bool -} - -// PluginEnableOptions holds parameters to enable plugins. -type PluginEnableOptions struct { - Timeout int -} - -// PluginDisableOptions holds parameters to disable plugins. -type PluginDisableOptions struct { - Force bool -} - -// PluginInstallOptions holds parameters to install a plugin. -type PluginInstallOptions struct { - Disabled bool - AcceptAllPermissions bool - RegistryAuth string // RegistryAuth is the base64 encoded credentials for the registry - RemoteRef string // RemoteRef is the plugin name on the registry - PrivilegeFunc RequestPrivilegeFunc - AcceptPermissionsFunc func(PluginPrivileges) (bool, error) - Args []string -} - -// SwarmUnlockKeyResponse contains the response for Engine API: -// GET /swarm/unlockkey -type SwarmUnlockKeyResponse struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// PluginCreateOptions hold all options to plugin create. -type PluginCreateOptions struct { - RepoName string -} diff --git a/vendor/github.com/docker/docker/api/types/configs.go b/vendor/github.com/docker/docker/api/types/configs.go deleted file mode 100644 index 20c19f2132..0000000000 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ /dev/null @@ -1,69 +0,0 @@ -package types - -import ( - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" -) - -// configs holds structs used for internal communication between the -// frontend (such as an http server) and the backend (such as the -// docker daemon). - -// ContainerCreateConfig is the parameter set to ContainerCreate() -type ContainerCreateConfig struct { - Name string - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig - AdjustCPUShares bool -} - -// ContainerRmConfig holds arguments for the container remove -// operation. This struct is used to tell the backend what operations -// to perform. -type ContainerRmConfig struct { - ForceRemove, RemoveVolume, RemoveLink bool -} - -// ContainerCommitConfig contains build configs for commit operation, -// and is used when making a commit with the current state of the container. -type ContainerCommitConfig struct { - Pause bool - Repo string - Tag string - Author string - Comment string - // merge container config into commit config before commit - MergeConfigs bool - Config *container.Config -} - -// ExecConfig is a small subset of the Config struct that holds the configuration -// for the exec feature of docker. -type ExecConfig struct { - User string // User that will run the command - Privileged bool // Is the container in privileged mode - Tty bool // Attach standard streams to a tty. - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStderr bool // Attach the standard error - AttachStdout bool // Attach the standard output - Detach bool // Execute in detach mode - DetachKeys string // Escape keys for detach - Env []string // Environment variables - Cmd []string // Execution commands and args -} - -// PluginRmConfig holds arguments for plugin remove. -type PluginRmConfig struct { - ForceRemove bool -} - -// PluginEnableConfig holds arguments for plugin enable -type PluginEnableConfig struct { - Timeout int -} - -// PluginDisableConfig holds arguments for plugin disable. -type PluginDisableConfig struct { - ForceDisable bool -} diff --git a/vendor/github.com/docker/docker/api/types/container/config.go b/vendor/github.com/docker/docker/api/types/container/config.go deleted file mode 100644 index 02e1b87a78..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ /dev/null @@ -1,63 +0,0 @@ -package container - -import ( - "time" - - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" -) - -// HealthConfig holds configuration settings for the HEALTHCHECK feature. -type HealthConfig struct { - // Test is the test to perform to check that the container is healthy. - // An empty slice means to inherit the default. - // The options are: - // {} : inherit healthcheck - // {"NONE"} : disable healthcheck - // {"CMD", args...} : exec arguments directly - // {"CMD-SHELL", command} : run command with system's default shell - Test []string `json:",omitempty"` - - // Zero means to inherit. Durations are expressed as integer nanoseconds. - Interval time.Duration `json:",omitempty"` // Interval is the time to wait between checks. - Timeout time.Duration `json:",omitempty"` // Timeout is the time to wait before considering the check to have hung. - StartPeriod time.Duration `json:",omitempty"` // The start period for the container to initialize before the retries starts to count down. - - // Retries is the number of consecutive failures needed to consider a container as unhealthy. - // Zero means inherit. - Retries int `json:",omitempty"` -} - -// Config contains the configuration data about a container. -// It should hold only portable information about the container. -// Here, "portable" means "independent from the host we are running on". -// Non-portable information *should* appear in HostConfig. -// All fields added to this struct must be marked `omitempty` to keep getting -// predictable hashes from the old `v1Compatibility` configuration. -type Config struct { - Hostname string // Hostname - Domainname string // Domainname - User string // User that will run the command(s) inside the container, also support user:group - AttachStdin bool // Attach the standard input, makes possible user interaction - AttachStdout bool // Attach the standard output - AttachStderr bool // Attach the standard error - ExposedPorts nat.PortSet `json:",omitempty"` // List of exposed ports - Tty bool // Attach standard streams to a tty, including stdin if it is not closed. - OpenStdin bool // Open stdin - StdinOnce bool // If true, close stdin after the 1 attached client disconnects. - Env []string // List of environment variable to set in the container - Cmd strslice.StrSlice // Command to run when starting the container - Healthcheck *HealthConfig `json:",omitempty"` // Healthcheck describes how to check the container is healthy - ArgsEscaped bool `json:",omitempty"` // True if command is already escaped (Windows specific) - Image string // Name of the image as it was passed by the operator (e.g. could be symbolic) - Volumes map[string]struct{} // List of volumes (mounts) used for the container - WorkingDir string // Current directory (PWD) in the command will be launched - Entrypoint strslice.StrSlice // Entrypoint to run when starting the container - NetworkDisabled bool `json:",omitempty"` // Is network disabled - MacAddress string `json:",omitempty"` // Mac Address of the container - OnBuild []string // ONBUILD metadata that were defined on the image Dockerfile - Labels map[string]string // List of labels set to this container - StopSignal string `json:",omitempty"` // Signal to stop a container - StopTimeout *int `json:",omitempty"` // Timeout (in seconds) to stop a container - Shell strslice.StrSlice `json:",omitempty"` // Shell for shell-form of RUN, CMD, ENTRYPOINT -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_changes.go b/vendor/github.com/docker/docker/api/types/container/container_changes.go deleted file mode 100644 index 767945a532..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_changes.go +++ /dev/null @@ -1,21 +0,0 @@ -package container - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerChangeResponseItem container change response item -// swagger:model ContainerChangeResponseItem -type ContainerChangeResponseItem struct { - - // Kind of change - // Required: true - Kind uint8 `json:"Kind"` - - // Path to file that has changed - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_create.go b/vendor/github.com/docker/docker/api/types/container/container_create.go deleted file mode 100644 index c95023b814..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_create.go +++ /dev/null @@ -1,21 +0,0 @@ -package container - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerCreateCreatedBody container create created body -// swagger:model ContainerCreateCreatedBody -type ContainerCreateCreatedBody struct { - - // The ID of the created container - // Required: true - ID string `json:"Id"` - - // Warnings encountered when creating the container - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_top.go b/vendor/github.com/docker/docker/api/types/container/container_top.go deleted file mode 100644 index 78bc37ee5e..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_top.go +++ /dev/null @@ -1,21 +0,0 @@ -package container - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerTopOKBody container top o k body -// swagger:model ContainerTopOKBody -type ContainerTopOKBody struct { - - // Each process running in the container, where each is process is an array of values corresponding to the titles - // Required: true - Processes [][]string `json:"Processes"` - - // The ps column titles - // Required: true - Titles []string `json:"Titles"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_update.go b/vendor/github.com/docker/docker/api/types/container/container_update.go deleted file mode 100644 index 2339366fbd..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_update.go +++ /dev/null @@ -1,17 +0,0 @@ -package container - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerUpdateOKBody container update o k body -// swagger:model ContainerUpdateOKBody -type ContainerUpdateOKBody struct { - - // warnings - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_wait.go b/vendor/github.com/docker/docker/api/types/container/container_wait.go deleted file mode 100644 index 77ecdbaf7a..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_wait.go +++ /dev/null @@ -1,17 +0,0 @@ -package container - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerWaitOKBody container wait o k body -// swagger:model ContainerWaitOKBody -type ContainerWaitOKBody struct { - - // Exit code of the container - // Required: true - StatusCode int64 `json:"StatusCode"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/host_config.go b/vendor/github.com/docker/docker/api/types/container/host_config.go deleted file mode 100644 index 9fea9eb04b..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/host_config.go +++ /dev/null @@ -1,380 +0,0 @@ -package container - -import ( - "strings" - - "github.com/docker/docker/api/types/blkiodev" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - "github.com/docker/go-units" -) - -// Isolation represents the isolation technology of a container. The supported -// values are platform specific -type Isolation string - -// IsDefault indicates the default isolation technology of a container. On Linux this -// is the native driver. On Windows, this is a Windows Server Container. -func (i Isolation) IsDefault() bool { - return strings.ToLower(string(i)) == "default" || string(i) == "" -} - -// IpcMode represents the container ipc stack. -type IpcMode string - -// IsPrivate indicates whether the container uses its private ipc stack. -func (n IpcMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsHost indicates whether the container uses the host's ipc stack. -func (n IpcMode) IsHost() bool { - return n == "host" -} - -// IsContainer indicates whether the container uses a container's ipc stack. -func (n IpcMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the ipc stack is valid. -func (n IpcMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true -} - -// Container returns the name of the container ipc stack is going to be used. -func (n IpcMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// NetworkMode represents the container network stack. -type NetworkMode string - -// IsNone indicates whether container isn't using a network stack. -func (n NetworkMode) IsNone() bool { - return n == "none" -} - -// IsDefault indicates whether container uses the default network stack. -func (n NetworkMode) IsDefault() bool { - return n == "default" -} - -// IsPrivate indicates whether container uses its private network stack. -func (n NetworkMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsContainer indicates whether container uses a container network stack. -func (n NetworkMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -//UserDefined indicates user-created network -func (n NetworkMode) UserDefined() string { - if n.IsUserDefined() { - return string(n) - } - return "" -} - -// UsernsMode represents userns mode in the container. -type UsernsMode string - -// IsHost indicates whether the container uses the host's userns. -func (n UsernsMode) IsHost() bool { - return n == "host" -} - -// IsPrivate indicates whether the container uses the a private userns. -func (n UsernsMode) IsPrivate() bool { - return !(n.IsHost()) -} - -// Valid indicates whether the userns is valid. -func (n UsernsMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// CgroupSpec represents the cgroup to use for the container. -type CgroupSpec string - -// IsContainer indicates whether the container is using another container cgroup -func (c CgroupSpec) IsContainer() bool { - parts := strings.SplitN(string(c), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the cgroup spec is valid. -func (c CgroupSpec) Valid() bool { - return c.IsContainer() || c == "" -} - -// Container returns the name of the container whose cgroup will be used. -func (c CgroupSpec) Container() string { - parts := strings.SplitN(string(c), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// UTSMode represents the UTS namespace of the container. -type UTSMode string - -// IsPrivate indicates whether the container uses its private UTS namespace. -func (n UTSMode) IsPrivate() bool { - return !(n.IsHost()) -} - -// IsHost indicates whether the container uses the host's UTS namespace. -func (n UTSMode) IsHost() bool { - return n == "host" -} - -// Valid indicates whether the UTS namespace is valid. -func (n UTSMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// PidMode represents the pid namespace of the container. -type PidMode string - -// IsPrivate indicates whether the container uses its own new pid namespace. -func (n PidMode) IsPrivate() bool { - return !(n.IsHost() || n.IsContainer()) -} - -// IsHost indicates whether the container uses the host's pid namespace. -func (n PidMode) IsHost() bool { - return n == "host" -} - -// IsContainer indicates whether the container uses a container's pid namespace. -func (n PidMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the pid namespace is valid. -func (n PidMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true -} - -// Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// DeviceMapping represents the device mapping between the host and the container. -type DeviceMapping struct { - PathOnHost string - PathInContainer string - CgroupPermissions string -} - -// RestartPolicy represents the restart policies of the container. -type RestartPolicy struct { - Name string - MaximumRetryCount int -} - -// IsNone indicates whether the container has the "no" restart policy. -// This means the container will not automatically restart when exiting. -func (rp *RestartPolicy) IsNone() bool { - return rp.Name == "no" || rp.Name == "" -} - -// IsAlways indicates whether the container has the "always" restart policy. -// This means the container will automatically restart regardless of the exit status. -func (rp *RestartPolicy) IsAlways() bool { - return rp.Name == "always" -} - -// IsOnFailure indicates whether the container has the "on-failure" restart policy. -// This means the container will automatically restart of exiting with a non-zero exit status. -func (rp *RestartPolicy) IsOnFailure() bool { - return rp.Name == "on-failure" -} - -// IsUnlessStopped indicates whether the container has the -// "unless-stopped" restart policy. This means the container will -// automatically restart unless user has put it to stopped state. -func (rp *RestartPolicy) IsUnlessStopped() bool { - return rp.Name == "unless-stopped" -} - -// IsSame compares two RestartPolicy to see if they are the same -func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool { - return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount -} - -// LogMode is a type to define the available modes for logging -// These modes affect how logs are handled when log messages start piling up. -type LogMode string - -// Available logging modes -const ( - LogModeUnset = "" - LogModeBlocking LogMode = "blocking" - LogModeNonBlock LogMode = "non-blocking" -) - -// LogConfig represents the logging configuration of the container. -type LogConfig struct { - Type string - Config map[string]string -} - -// Resources contains container's resources (cgroups config, ulimits...) -type Resources struct { - // Applicable to all platforms - CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers) - Memory int64 // Memory limit (in bytes) - NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10-9 CPUs. - - // Applicable to UNIX platforms - CgroupParent string // Parent cgroup. - BlkioWeight uint16 // Block IO weight (relative weight vs. other containers) - BlkioWeightDevice []*blkiodev.WeightDevice - BlkioDeviceReadBps []*blkiodev.ThrottleDevice - BlkioDeviceWriteBps []*blkiodev.ThrottleDevice - BlkioDeviceReadIOps []*blkiodev.ThrottleDevice - BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice - CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period - CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota - CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period - CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime - CpusetCpus string // CpusetCpus 0-2, 0,1 - CpusetMems string // CpusetMems 0-2, 0,1 - Devices []DeviceMapping // List of devices to map inside the container - DeviceCgroupRules []string // List of rule to be added to the device cgroup - DiskQuota int64 // Disk limit (in bytes) - KernelMemory int64 // Kernel memory limit (in bytes) - MemoryReservation int64 // Memory soft limit (in bytes) - MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap - MemorySwappiness *int64 // Tuning container memory swappiness behaviour - OomKillDisable *bool // Whether to disable OOM Killer or not - PidsLimit int64 // Setting pids limit for a container - Ulimits []*units.Ulimit // List of ulimits to be set in the container - - // Applicable to Windows - CPUCount int64 `json:"CpuCount"` // CPU count - CPUPercent int64 `json:"CpuPercent"` // CPU percent - IOMaximumIOps uint64 // Maximum IOps for the container system drive - IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive -} - -// UpdateConfig holds the mutable attributes of a Container. -// Those attributes can be updated at runtime. -type UpdateConfig struct { - // Contains container's resources (cgroups, ulimits) - Resources - RestartPolicy RestartPolicy -} - -// HostConfig the non-portable Config structure of a container. -// Here, "non-portable" means "dependent of the host we are running on". -// Portable information *should* appear in Config. -type HostConfig struct { - // Applicable to all platforms - Binds []string // List of volume bindings for this container - ContainerIDFile string // File (path) where the containerId is written - LogConfig LogConfig // Configuration of the logs for this container - NetworkMode NetworkMode // Network mode to use for the container - PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host - RestartPolicy RestartPolicy // Restart policy to be used for the container - AutoRemove bool // Automatically remove container when it exits - VolumeDriver string // Name of the volume driver used to mount volumes - VolumesFrom []string // List of volumes to take from other container - - // Applicable to UNIX platforms - CapAdd strslice.StrSlice // List of kernel capabilities to add to the container - CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container - DNS []string `json:"Dns"` // List of DNS server to lookup - DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for - DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for - ExtraHosts []string // List of extra hosts - GroupAdd []string // List of additional groups that the container process will run as - IpcMode IpcMode // IPC namespace to use for the container - Cgroup CgroupSpec // Cgroup to use for the container - Links []string // List of links (in the name:alias form) - OomScoreAdj int // Container preference for OOM-killing - PidMode PidMode // PID namespace to use for the container - Privileged bool // Is the container in privileged mode - PublishAllPorts bool // Should docker publish all exposed port for the container - ReadonlyRootfs bool // Is the container root filesystem in read-only - SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux. - StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container. - Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container - UTSMode UTSMode // UTS namespace to use for the container - UsernsMode UsernsMode // The user namespace to use for the container - ShmSize int64 // Total shm memory usage - Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container - Runtime string `json:",omitempty"` // Runtime to use with this container - - // Applicable to Windows - ConsoleSize [2]uint // Initial console size (height,width) - Isolation Isolation // Isolation technology of the container (e.g. default, hyperv) - - // Contains container's resources (cgroups, ulimits) - Resources - - // Mounts specs used by the container - Mounts []mount.Mount `json:",omitempty"` - - // Run a custom init inside the container, if null, use the daemon's configured settings - Init *bool `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go deleted file mode 100644 index 2d664d1c96..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !windows - -package container - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsBridge() { - return "bridge" - } else if n.IsHost() { - return "host" - } else if n.IsContainer() { - return "container" - } else if n.IsNone() { - return "none" - } else if n.IsDefault() { - return "default" - } else if n.IsUserDefined() { - return n.UserDefined() - } - return "" -} - -// IsBridge indicates whether container uses the bridge network stack -func (n NetworkMode) IsBridge() bool { - return n == "bridge" -} - -// IsHost indicates whether container uses the host network stack. -func (n NetworkMode) IsHost() bool { - return n == "host" -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsBridge() && !n.IsHost() && !n.IsNone() && !n.IsContainer() -} diff --git a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go b/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go deleted file mode 100644 index 469923f7e9..0000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_windows.go +++ /dev/null @@ -1,54 +0,0 @@ -package container - -import ( - "strings" -) - -// IsBridge indicates whether container uses the bridge network stack -// in windows it is given the name NAT -func (n NetworkMode) IsBridge() bool { - return n == "nat" -} - -// IsHost indicates whether container uses the host network stack. -// returns false as this is not supported by windows -func (n NetworkMode) IsHost() bool { - return false -} - -// IsUserDefined indicates user-created network -func (n NetworkMode) IsUserDefined() bool { - return !n.IsDefault() && !n.IsNone() && !n.IsBridge() && !n.IsContainer() -} - -// IsHyperV indicates the use of a Hyper-V partition for isolation -func (i Isolation) IsHyperV() bool { - return strings.ToLower(string(i)) == "hyperv" -} - -// IsProcess indicates the use of process isolation -func (i Isolation) IsProcess() bool { - return strings.ToLower(string(i)) == "process" -} - -// IsValid indicates if an isolation technology is valid -func (i Isolation) IsValid() bool { - return i.IsDefault() || i.IsHyperV() || i.IsProcess() -} - -// NetworkName returns the name of the network stack. -func (n NetworkMode) NetworkName() string { - if n.IsDefault() { - return "default" - } else if n.IsBridge() { - return "nat" - } else if n.IsNone() { - return "none" - } else if n.IsContainer() { - return "container" - } else if n.IsUserDefined() { - return n.UserDefined() - } - - return "" -} diff --git a/vendor/github.com/docker/docker/api/types/error_response.go b/vendor/github.com/docker/docker/api/types/error_response.go deleted file mode 100644 index dc942d9d9e..0000000000 --- a/vendor/github.com/docker/docker/api/types/error_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ErrorResponse Represents an error. -// swagger:model ErrorResponse -type ErrorResponse struct { - - // The error message. - // Required: true - Message string `json:"message"` -} diff --git a/vendor/github.com/docker/docker/api/types/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go deleted file mode 100644 index 7129a65acf..0000000000 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ /dev/null @@ -1,42 +0,0 @@ -package events - -const ( - // ContainerEventType is the event type that containers generate - ContainerEventType = "container" - // DaemonEventType is the event type that daemon generate - DaemonEventType = "daemon" - // ImageEventType is the event type that images generate - ImageEventType = "image" - // NetworkEventType is the event type that networks generate - NetworkEventType = "network" - // PluginEventType is the event type that plugins generate - PluginEventType = "plugin" - // VolumeEventType is the event type that volumes generate - VolumeEventType = "volume" -) - -// Actor describes something that generates events, -// like a container, or a network, or a volume. -// It has a defined name and a set or attributes. -// The container attributes are its labels, other actors -// can generate these attributes from other properties. -type Actor struct { - ID string - Attributes map[string]string -} - -// Message represents the information an event contains -type Message struct { - // Deprecated information from JSONMessage. - // With data only in container events. - Status string `json:"status,omitempty"` - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - - Type string - Action string - Actor Actor - - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/filters/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go deleted file mode 100644 index beec3d4940..0000000000 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ /dev/null @@ -1,310 +0,0 @@ -// Package filters provides helper function to parse and handle command line -// filter, used for example in docker ps or docker images commands. -package filters - -import ( - "encoding/json" - "errors" - "fmt" - "regexp" - "strings" - - "github.com/docker/docker/api/types/versions" -) - -// Args stores filter arguments as map key:{map key: bool}. -// It contains an aggregation of the map of arguments (which are in the form -// of -f 'key=value') based on the key, and stores values for the same key -// in a map with string keys and boolean values. -// e.g given -f 'label=label1=1' -f 'label=label2=2' -f 'image.name=ubuntu' -// the args will be {"image.name":{"ubuntu":true},"label":{"label1=1":true,"label2=2":true}} -type Args struct { - fields map[string]map[string]bool -} - -// NewArgs initializes a new Args struct. -func NewArgs() Args { - return Args{fields: map[string]map[string]bool{}} -} - -// ParseFlag parses the argument to the filter flag. Like -// -// `docker ps -f 'created=today' -f 'image.name=ubuntu*'` -// -// If prev map is provided, then it is appended to, and returned. By default a new -// map is created. -func ParseFlag(arg string, prev Args) (Args, error) { - filters := prev - if len(arg) == 0 { - return filters, nil - } - - if !strings.Contains(arg, "=") { - return filters, ErrBadFormat - } - - f := strings.SplitN(arg, "=", 2) - - name := strings.ToLower(strings.TrimSpace(f[0])) - value := strings.TrimSpace(f[1]) - - filters.Add(name, value) - - return filters, nil -} - -// ErrBadFormat is an error returned in case of bad format for a filter. -var ErrBadFormat = errors.New("bad format of filter (expected name=value)") - -// ToParam packs the Args into a string for easy transport from client to server. -func ToParam(a Args) (string, error) { - // this way we don't URL encode {}, just empty space - if a.Len() == 0 { - return "", nil - } - - buf, err := json.Marshal(a.fields) - if err != nil { - return "", err - } - return string(buf), nil -} - -// ToParamWithVersion packs the Args into a string for easy transport from client to server. -// The generated string will depend on the specified version (corresponding to the API version). -func ToParamWithVersion(version string, a Args) (string, error) { - // this way we don't URL encode {}, just empty space - if a.Len() == 0 { - return "", nil - } - - // for daemons older than v1.10, filter must be of the form map[string][]string - var buf []byte - var err error - if version != "" && versions.LessThan(version, "1.22") { - buf, err = json.Marshal(convertArgsToSlice(a.fields)) - } else { - buf, err = json.Marshal(a.fields) - } - if err != nil { - return "", err - } - return string(buf), nil -} - -// FromParam unpacks the filter Args. -func FromParam(p string) (Args, error) { - if len(p) == 0 { - return NewArgs(), nil - } - - r := strings.NewReader(p) - d := json.NewDecoder(r) - - m := map[string]map[string]bool{} - if err := d.Decode(&m); err != nil { - r.Seek(0, 0) - - // Allow parsing old arguments in slice format. - // Because other libraries might be sending them in this format. - deprecated := map[string][]string{} - if deprecatedErr := d.Decode(&deprecated); deprecatedErr == nil { - m = deprecatedArgs(deprecated) - } else { - return NewArgs(), err - } - } - return Args{m}, nil -} - -// Get returns the list of values associates with a field. -// It returns a slice of strings to keep backwards compatibility with old code. -func (filters Args) Get(field string) []string { - values := filters.fields[field] - if values == nil { - return make([]string, 0) - } - slice := make([]string, 0, len(values)) - for key := range values { - slice = append(slice, key) - } - return slice -} - -// Add adds a new value to a filter field. -func (filters Args) Add(name, value string) { - if _, ok := filters.fields[name]; ok { - filters.fields[name][value] = true - } else { - filters.fields[name] = map[string]bool{value: true} - } -} - -// Del removes a value from a filter field. -func (filters Args) Del(name, value string) { - if _, ok := filters.fields[name]; ok { - delete(filters.fields[name], value) - if len(filters.fields[name]) == 0 { - delete(filters.fields, name) - } - } -} - -// Len returns the number of fields in the arguments. -func (filters Args) Len() int { - return len(filters.fields) -} - -// MatchKVList returns true if the values for the specified field matches the ones -// from the sources. -// e.g. given Args are {'label': {'label1=1','label2=1'}, 'image.name', {'ubuntu'}}, -// field is 'label' and sources are {'label1': '1', 'label2': '2'} -// it returns true. -func (filters Args) MatchKVList(field string, sources map[string]string) bool { - fieldValues := filters.fields[field] - - //do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - - if len(sources) == 0 { - return false - } - - for name2match := range fieldValues { - testKV := strings.SplitN(name2match, "=", 2) - - v, ok := sources[testKV[0]] - if !ok { - return false - } - if len(testKV) == 2 && testKV[1] != v { - return false - } - } - - return true -} - -// Match returns true if the values for the specified field matches the source string -// e.g. given Args are {'label': {'label1=1','label2=1'}, 'image.name', {'ubuntu'}}, -// field is 'image.name' and source is 'ubuntu' -// it returns true. -func (filters Args) Match(field, source string) bool { - if filters.ExactMatch(field, source) { - return true - } - - fieldValues := filters.fields[field] - for name2match := range fieldValues { - match, err := regexp.MatchString(name2match, source) - if err != nil { - continue - } - if match { - return true - } - } - return false -} - -// ExactMatch returns true if the source matches exactly one of the filters. -func (filters Args) ExactMatch(field, source string) bool { - fieldValues, ok := filters.fields[field] - //do not filter if there is no filter set or cannot determine filter - if !ok || len(fieldValues) == 0 { - return true - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// UniqueExactMatch returns true if there is only one filter and the source matches exactly this one. -func (filters Args) UniqueExactMatch(field, source string) bool { - fieldValues := filters.fields[field] - //do not filter if there is no filter set or cannot determine filter - if len(fieldValues) == 0 { - return true - } - if len(filters.fields[field]) != 1 { - return false - } - - // try to match full name value to avoid O(N) regular expression matching - return fieldValues[source] -} - -// FuzzyMatch returns true if the source matches exactly one of the filters, -// or the source has one of the filters as a prefix. -func (filters Args) FuzzyMatch(field, source string) bool { - if filters.ExactMatch(field, source) { - return true - } - - fieldValues := filters.fields[field] - for prefix := range fieldValues { - if strings.HasPrefix(source, prefix) { - return true - } - } - return false -} - -// Include returns true if the name of the field to filter is in the filters. -func (filters Args) Include(field string) bool { - _, ok := filters.fields[field] - return ok -} - -// Validate ensures that all the fields in the filter are valid. -// It returns an error as soon as it finds an invalid field. -func (filters Args) Validate(accepted map[string]bool) error { - for name := range filters.fields { - if !accepted[name] { - return fmt.Errorf("Invalid filter '%s'", name) - } - } - return nil -} - -// WalkValues iterates over the list of filtered values for a field. -// It stops the iteration if it finds an error and it returns that error. -func (filters Args) WalkValues(field string, op func(value string) error) error { - if _, ok := filters.fields[field]; !ok { - return nil - } - for v := range filters.fields[field] { - if err := op(v); err != nil { - return err - } - } - return nil -} - -func deprecatedArgs(d map[string][]string) map[string]map[string]bool { - m := map[string]map[string]bool{} - for k, v := range d { - values := map[string]bool{} - for _, vv := range v { - values[vv] = true - } - m[k] = values - } - return m -} - -func convertArgsToSlice(f map[string]map[string]bool) map[string][]string { - m := map[string][]string{} - for k, v := range f { - values := []string{} - for kk := range v { - if v[kk] { - values = append(values, kk) - } - } - m[k] = values - } - return m -} diff --git a/vendor/github.com/docker/docker/api/types/graph_driver_data.go b/vendor/github.com/docker/docker/api/types/graph_driver_data.go deleted file mode 100644 index 4d9bf1c62c..0000000000 --- a/vendor/github.com/docker/docker/api/types/graph_driver_data.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// GraphDriverData Information about a container's graph driver. -// swagger:model GraphDriverData -type GraphDriverData struct { - - // data - // Required: true - Data map[string]string `json:"Data"` - - // name - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/id_response.go b/vendor/github.com/docker/docker/api/types/id_response.go deleted file mode 100644 index 7592d2f8b1..0000000000 --- a/vendor/github.com/docker/docker/api/types/id_response.go +++ /dev/null @@ -1,13 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// IDResponse Response to an API call that returns just an Id -// swagger:model IdResponse -type IDResponse struct { - - // The id of the newly created object. - // Required: true - ID string `json:"Id"` -} diff --git a/vendor/github.com/docker/docker/api/types/image/image_history.go b/vendor/github.com/docker/docker/api/types/image/image_history.go deleted file mode 100644 index 0dd30c729a..0000000000 --- a/vendor/github.com/docker/docker/api/types/image/image_history.go +++ /dev/null @@ -1,37 +0,0 @@ -package image - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// HistoryResponseItem history response item -// swagger:model HistoryResponseItem -type HistoryResponseItem struct { - - // comment - // Required: true - Comment string `json:"Comment"` - - // created - // Required: true - Created int64 `json:"Created"` - - // created by - // Required: true - CreatedBy string `json:"CreatedBy"` - - // Id - // Required: true - ID string `json:"Id"` - - // size - // Required: true - Size int64 `json:"Size"` - - // tags - // Required: true - Tags []string `json:"Tags"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go b/vendor/github.com/docker/docker/api/types/image_delete_response_item.go deleted file mode 100644 index b9a65a0d8e..0000000000 --- a/vendor/github.com/docker/docker/api/types/image_delete_response_item.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageDeleteResponseItem image delete response item -// swagger:model ImageDeleteResponseItem -type ImageDeleteResponseItem struct { - - // The image ID of an image that was deleted - Deleted string `json:"Deleted,omitempty"` - - // The image ID of an image that was untagged - Untagged string `json:"Untagged,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/image_summary.go b/vendor/github.com/docker/docker/api/types/image_summary.go deleted file mode 100644 index e145b3dcfc..0000000000 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ /dev/null @@ -1,49 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ImageSummary image summary -// swagger:model ImageSummary -type ImageSummary struct { - - // containers - // Required: true - Containers int64 `json:"Containers"` - - // created - // Required: true - Created int64 `json:"Created"` - - // Id - // Required: true - ID string `json:"Id"` - - // labels - // Required: true - Labels map[string]string `json:"Labels"` - - // parent Id - // Required: true - ParentID string `json:"ParentId"` - - // repo digests - // Required: true - RepoDigests []string `json:"RepoDigests"` - - // repo tags - // Required: true - RepoTags []string `json:"RepoTags"` - - // shared size - // Required: true - SharedSize int64 `json:"SharedSize"` - - // size - // Required: true - Size int64 `json:"Size"` - - // virtual size - // Required: true - VirtualSize int64 `json:"VirtualSize"` -} diff --git a/vendor/github.com/docker/docker/api/types/mount/mount.go b/vendor/github.com/docker/docker/api/types/mount/mount.go deleted file mode 100644 index 2744f85d6d..0000000000 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ /dev/null @@ -1,128 +0,0 @@ -package mount - -import ( - "os" -) - -// Type represents the type of a mount. -type Type string - -// Type constants -const ( - // TypeBind is the type for mounting host dir - TypeBind Type = "bind" - // TypeVolume is the type for remote storage volumes - TypeVolume Type = "volume" - // TypeTmpfs is the type for mounting tmpfs - TypeTmpfs Type = "tmpfs" -) - -// Mount represents a mount (volume). -type Mount struct { - Type Type `json:",omitempty"` - // Source specifies the name of the mount. Depending on mount type, this - // may be a volume name or a host path, or even ignored. - // Source is not supported for tmpfs (must be an empty value) - Source string `json:",omitempty"` - Target string `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Consistency Consistency `json:",omitempty"` - - BindOptions *BindOptions `json:",omitempty"` - VolumeOptions *VolumeOptions `json:",omitempty"` - TmpfsOptions *TmpfsOptions `json:",omitempty"` -} - -// Propagation represents the propagation of a mount. -type Propagation string - -const ( - // PropagationRPrivate RPRIVATE - PropagationRPrivate Propagation = "rprivate" - // PropagationPrivate PRIVATE - PropagationPrivate Propagation = "private" - // PropagationRShared RSHARED - PropagationRShared Propagation = "rshared" - // PropagationShared SHARED - PropagationShared Propagation = "shared" - // PropagationRSlave RSLAVE - PropagationRSlave Propagation = "rslave" - // PropagationSlave SLAVE - PropagationSlave Propagation = "slave" -) - -// Propagations is the list of all valid mount propagations -var Propagations = []Propagation{ - PropagationRPrivate, - PropagationPrivate, - PropagationRShared, - PropagationShared, - PropagationRSlave, - PropagationSlave, -} - -// Consistency represents the consistency requirements of a mount. -type Consistency string - -const ( - // ConsistencyFull guarantees bind-mount-like consistency - ConsistencyFull Consistency = "consistent" - // ConsistencyCached mounts can cache read data and FS structure - ConsistencyCached Consistency = "cached" - // ConsistencyDelegated mounts can cache read and written data and structure - ConsistencyDelegated Consistency = "delegated" - // ConsistencyDefault provides "consistent" behavior unless overridden - ConsistencyDefault Consistency = "default" -) - -// BindOptions defines options specific to mounts of type "bind". -type BindOptions struct { - Propagation Propagation `json:",omitempty"` -} - -// VolumeOptions represents the options for a mount of type volume. -type VolumeOptions struct { - NoCopy bool `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - DriverConfig *Driver `json:",omitempty"` -} - -// Driver represents a volume driver. -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} - -// TmpfsOptions defines options specific to mounts of type "tmpfs". -type TmpfsOptions struct { - // Size sets the size of the tmpfs, in bytes. - // - // This will be converted to an operating system specific value - // depending on the host. For example, on linux, it will be converted to - // use a 'k', 'm' or 'g' syntax. BSD, though not widely supported with - // docker, uses a straight byte value. - // - // Percentages are not supported. - SizeBytes int64 `json:",omitempty"` - // Mode of the tmpfs upon creation - Mode os.FileMode `json:",omitempty"` - - // TODO(stevvooe): There are several more tmpfs flags, specified in the - // daemon, that are accepted. Only the most basic are added for now. - // - // From docker/docker/pkg/mount/flags.go: - // - // var validFlags = map[string]bool{ - // "": true, - // "size": true, X - // "mode": true, X - // "uid": true, - // "gid": true, - // "nr_inodes": true, - // "nr_blocks": true, - // "mpol": true, - // } - // - // Some of these may be straightforward to add, but others, such as - // uid/gid have implications in a clustered system. -} diff --git a/vendor/github.com/docker/docker/api/types/network/network.go b/vendor/github.com/docker/docker/api/types/network/network.go deleted file mode 100644 index 8d15ed21b5..0000000000 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ /dev/null @@ -1,102 +0,0 @@ -package network - -// Address represents an IP address -type Address struct { - Addr string - PrefixLen int -} - -// IPAM represents IP Address Management -type IPAM struct { - Driver string - Options map[string]string //Per network IPAM driver options - Config []IPAMConfig -} - -// IPAMConfig represents IPAM configurations -type IPAMConfig struct { - Subnet string `json:",omitempty"` - IPRange string `json:",omitempty"` - Gateway string `json:",omitempty"` - AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` -} - -// EndpointIPAMConfig represents IPAM configurations for the endpoint -type EndpointIPAMConfig struct { - IPv4Address string `json:",omitempty"` - IPv6Address string `json:",omitempty"` - LinkLocalIPs []string `json:",omitempty"` -} - -// Copy makes a copy of the endpoint ipam config -func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig { - cfgCopy := *cfg - cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs)) - cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...) - return &cfgCopy -} - -// PeerInfo represents one peer of an overlay network -type PeerInfo struct { - Name string - IP string -} - -// EndpointSettings stores the network endpoint details -type EndpointSettings struct { - // Configurations - IPAMConfig *EndpointIPAMConfig - Links []string - Aliases []string - // Operational data - NetworkID string - EndpointID string - Gateway string - IPAddress string - IPPrefixLen int - IPv6Gateway string - GlobalIPv6Address string - GlobalIPv6PrefixLen int - MacAddress string -} - -// Task carries the information about one backend task -type Task struct { - Name string - EndpointID string - EndpointIP string - Info map[string]string -} - -// ServiceInfo represents service parameters with the list of service's tasks -type ServiceInfo struct { - VIP string - Ports []string - LocalLBIndex int - Tasks []Task -} - -// Copy makes a deep copy of `EndpointSettings` -func (es *EndpointSettings) Copy() *EndpointSettings { - epCopy := *es - if es.IPAMConfig != nil { - epCopy.IPAMConfig = es.IPAMConfig.Copy() - } - - if es.Links != nil { - links := make([]string, 0, len(es.Links)) - epCopy.Links = append(links, es.Links...) - } - - if es.Aliases != nil { - aliases := make([]string, 0, len(es.Aliases)) - epCopy.Aliases = append(aliases, es.Aliases...) - } - return &epCopy -} - -// NetworkingConfig represents the container's networking configuration for each of its interfaces -// Carries the networking configs specified in the `docker run` and `docker network connect` commands -type NetworkingConfig struct { - EndpointsConfig map[string]*EndpointSettings // Endpoint configs for each connecting network -} diff --git a/vendor/github.com/docker/docker/api/types/plugin.go b/vendor/github.com/docker/docker/api/types/plugin.go deleted file mode 100644 index ed3c2c26e4..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin.go +++ /dev/null @@ -1,200 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Plugin A plugin for the Engine API -// swagger:model Plugin -type Plugin struct { - - // config - // Required: true - Config PluginConfig `json:"Config"` - - // True when the plugin is running. False when the plugin is not running, only installed. - // Required: true - Enabled bool `json:"Enabled"` - - // Id - ID string `json:"Id,omitempty"` - - // name - // Required: true - Name string `json:"Name"` - - // plugin remote reference used to push/pull the plugin - PluginReference string `json:"PluginReference,omitempty"` - - // settings - // Required: true - Settings PluginSettings `json:"Settings"` -} - -// PluginConfig The config of a plugin. -// swagger:model PluginConfig -type PluginConfig struct { - - // args - // Required: true - Args PluginConfigArgs `json:"Args"` - - // description - // Required: true - Description string `json:"Description"` - - // Docker Version used to create the plugin - DockerVersion string `json:"DockerVersion,omitempty"` - - // documentation - // Required: true - Documentation string `json:"Documentation"` - - // entrypoint - // Required: true - Entrypoint []string `json:"Entrypoint"` - - // env - // Required: true - Env []PluginEnv `json:"Env"` - - // interface - // Required: true - Interface PluginConfigInterface `json:"Interface"` - - // ipc host - // Required: true - IpcHost bool `json:"IpcHost"` - - // linux - // Required: true - Linux PluginConfigLinux `json:"Linux"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` - - // network - // Required: true - Network PluginConfigNetwork `json:"Network"` - - // pid host - // Required: true - PidHost bool `json:"PidHost"` - - // propagated mount - // Required: true - PropagatedMount string `json:"PropagatedMount"` - - // user - User PluginConfigUser `json:"User,omitempty"` - - // work dir - // Required: true - WorkDir string `json:"WorkDir"` - - // rootfs - Rootfs *PluginConfigRootfs `json:"rootfs,omitempty"` -} - -// PluginConfigArgs plugin config args -// swagger:model PluginConfigArgs -type PluginConfigArgs struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value []string `json:"Value"` -} - -// PluginConfigInterface The interface between Docker and the plugin -// swagger:model PluginConfigInterface -type PluginConfigInterface struct { - - // socket - // Required: true - Socket string `json:"Socket"` - - // types - // Required: true - Types []PluginInterfaceType `json:"Types"` -} - -// PluginConfigLinux plugin config linux -// swagger:model PluginConfigLinux -type PluginConfigLinux struct { - - // allow all devices - // Required: true - AllowAllDevices bool `json:"AllowAllDevices"` - - // capabilities - // Required: true - Capabilities []string `json:"Capabilities"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` -} - -// PluginConfigNetwork plugin config network -// swagger:model PluginConfigNetwork -type PluginConfigNetwork struct { - - // type - // Required: true - Type string `json:"Type"` -} - -// PluginConfigRootfs plugin config rootfs -// swagger:model PluginConfigRootfs -type PluginConfigRootfs struct { - - // diff ids - DiffIds []string `json:"diff_ids"` - - // type - Type string `json:"type,omitempty"` -} - -// PluginConfigUser plugin config user -// swagger:model PluginConfigUser -type PluginConfigUser struct { - - // g ID - GID uint32 `json:"GID,omitempty"` - - // UID - UID uint32 `json:"UID,omitempty"` -} - -// PluginSettings Settings that can be modified by users. -// swagger:model PluginSettings -type PluginSettings struct { - - // args - // Required: true - Args []string `json:"Args"` - - // devices - // Required: true - Devices []PluginDevice `json:"Devices"` - - // env - // Required: true - Env []string `json:"Env"` - - // mounts - // Required: true - Mounts []PluginMount `json:"Mounts"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_device.go b/vendor/github.com/docker/docker/api/types/plugin_device.go deleted file mode 100644 index 5699010675..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_device.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginDevice plugin device -// swagger:model PluginDevice -type PluginDevice struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // path - // Required: true - Path *string `json:"Path"` - - // settable - // Required: true - Settable []string `json:"Settable"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_env.go b/vendor/github.com/docker/docker/api/types/plugin_env.go deleted file mode 100644 index 32962dc2eb..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_env.go +++ /dev/null @@ -1,25 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginEnv plugin env -// swagger:model PluginEnv -type PluginEnv struct { - - // description - // Required: true - Description string `json:"Description"` - - // name - // Required: true - Name string `json:"Name"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // value - // Required: true - Value *string `json:"Value"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go b/vendor/github.com/docker/docker/api/types/plugin_interface_type.go deleted file mode 100644 index c82f204e87..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_interface_type.go +++ /dev/null @@ -1,21 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginInterfaceType plugin interface type -// swagger:model PluginInterfaceType -type PluginInterfaceType struct { - - // capability - // Required: true - Capability string `json:"Capability"` - - // prefix - // Required: true - Prefix string `json:"Prefix"` - - // version - // Required: true - Version string `json:"Version"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_mount.go b/vendor/github.com/docker/docker/api/types/plugin_mount.go deleted file mode 100644 index 5c031cf8b5..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_mount.go +++ /dev/null @@ -1,37 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// PluginMount plugin mount -// swagger:model PluginMount -type PluginMount struct { - - // description - // Required: true - Description string `json:"Description"` - - // destination - // Required: true - Destination string `json:"Destination"` - - // name - // Required: true - Name string `json:"Name"` - - // options - // Required: true - Options []string `json:"Options"` - - // settable - // Required: true - Settable []string `json:"Settable"` - - // source - // Required: true - Source *string `json:"Source"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/plugin_responses.go b/vendor/github.com/docker/docker/api/types/plugin_responses.go deleted file mode 100644 index 1c6461f2d9..0000000000 --- a/vendor/github.com/docker/docker/api/types/plugin_responses.go +++ /dev/null @@ -1,79 +0,0 @@ -package types - -import ( - "encoding/json" - "fmt" - "sort" -) - -// PluginsListResponse contains the response for the Engine API -type PluginsListResponse []*Plugin - -const ( - authzDriver = "AuthzDriver" - graphDriver = "GraphDriver" - ipamDriver = "IpamDriver" - networkDriver = "NetworkDriver" - volumeDriver = "VolumeDriver" -) - -// UnmarshalJSON implements json.Unmarshaler for PluginInterfaceType -func (t *PluginInterfaceType) UnmarshalJSON(p []byte) error { - versionIndex := len(p) - prefixIndex := 0 - if len(p) < 2 || p[0] != '"' || p[len(p)-1] != '"' { - return fmt.Errorf("%q is not a plugin interface type", p) - } - p = p[1 : len(p)-1] -loop: - for i, b := range p { - switch b { - case '.': - prefixIndex = i - case '/': - versionIndex = i - break loop - } - } - t.Prefix = string(p[:prefixIndex]) - t.Capability = string(p[prefixIndex+1 : versionIndex]) - if versionIndex < len(p) { - t.Version = string(p[versionIndex+1:]) - } - return nil -} - -// MarshalJSON implements json.Marshaler for PluginInterfaceType -func (t *PluginInterfaceType) MarshalJSON() ([]byte, error) { - return json.Marshal(t.String()) -} - -// String implements fmt.Stringer for PluginInterfaceType -func (t PluginInterfaceType) String() string { - return fmt.Sprintf("%s.%s/%s", t.Prefix, t.Capability, t.Version) -} - -// PluginPrivilege describes a permission the user has to accept -// upon installing a plugin. -type PluginPrivilege struct { - Name string - Description string - Value []string -} - -// PluginPrivileges is a list of PluginPrivilege -type PluginPrivileges []PluginPrivilege - -func (s PluginPrivileges) Len() int { - return len(s) -} - -func (s PluginPrivileges) Less(i, j int) bool { - return s[i].Name < s[j].Name -} - -func (s PluginPrivileges) Swap(i, j int) { - sort.Strings(s[i].Value) - sort.Strings(s[j].Value) - s[i], s[j] = s[j], s[i] -} diff --git a/vendor/github.com/docker/docker/api/types/port.go b/vendor/github.com/docker/docker/api/types/port.go deleted file mode 100644 index ad52d46d56..0000000000 --- a/vendor/github.com/docker/docker/api/types/port.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Port An open port on a container -// swagger:model Port -type Port struct { - - // IP - IP string `json:"IP,omitempty"` - - // Port on the container - // Required: true - PrivatePort uint16 `json:"PrivatePort"` - - // Port exposed on the host - PublicPort uint16 `json:"PublicPort,omitempty"` - - // type - // Required: true - Type string `json:"Type"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/authenticate.go b/vendor/github.com/docker/docker/api/types/registry/authenticate.go deleted file mode 100644 index 42cac4430a..0000000000 --- a/vendor/github.com/docker/docker/api/types/registry/authenticate.go +++ /dev/null @@ -1,21 +0,0 @@ -package registry - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// AuthenticateOKBody authenticate o k body -// swagger:model AuthenticateOKBody -type AuthenticateOKBody struct { - - // An opaque token used to authenticate a user after a successful login - // Required: true - IdentityToken string `json:"IdentityToken"` - - // The status of the authentication - // Required: true - Status string `json:"Status"` -} diff --git a/vendor/github.com/docker/docker/api/types/registry/registry.go b/vendor/github.com/docker/docker/api/types/registry/registry.go deleted file mode 100644 index 28fafab901..0000000000 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ /dev/null @@ -1,104 +0,0 @@ -package registry - -import ( - "encoding/json" - "net" -) - -// ServiceConfig stores daemon registry services configuration. -type ServiceConfig struct { - InsecureRegistryCIDRs []*NetIPNet `json:"InsecureRegistryCIDRs"` - IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` - Mirrors []string -} - -// NetIPNet is the net.IPNet type, which can be marshalled and -// unmarshalled to JSON -type NetIPNet net.IPNet - -// String returns the CIDR notation of ipnet -func (ipnet *NetIPNet) String() string { - return (*net.IPNet)(ipnet).String() -} - -// MarshalJSON returns the JSON representation of the IPNet -func (ipnet *NetIPNet) MarshalJSON() ([]byte, error) { - return json.Marshal((*net.IPNet)(ipnet).String()) -} - -// UnmarshalJSON sets the IPNet from a byte array of JSON -func (ipnet *NetIPNet) UnmarshalJSON(b []byte) (err error) { - var ipnetStr string - if err = json.Unmarshal(b, &ipnetStr); err == nil { - var cidr *net.IPNet - if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { - *ipnet = NetIPNet(*cidr) - } - } - return -} - -// IndexInfo contains information about a registry -// -// RepositoryInfo Examples: -// { -// "Index" : { -// "Name" : "docker.io", -// "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], -// "Secure" : true, -// "Official" : true, -// }, -// "RemoteName" : "library/debian", -// "LocalName" : "debian", -// "CanonicalName" : "docker.io/debian" -// "Official" : true, -// } -// -// { -// "Index" : { -// "Name" : "127.0.0.1:5000", -// "Mirrors" : [], -// "Secure" : false, -// "Official" : false, -// }, -// "RemoteName" : "user/repo", -// "LocalName" : "127.0.0.1:5000/user/repo", -// "CanonicalName" : "127.0.0.1:5000/user/repo", -// "Official" : false, -// } -type IndexInfo struct { - // Name is the name of the registry, such as "docker.io" - Name string - // Mirrors is a list of mirrors, expressed as URIs - Mirrors []string - // Secure is set to false if the registry is part of the list of - // insecure registries. Insecure registries accept HTTP and/or accept - // HTTPS with certificates from unknown CAs. - Secure bool - // Official indicates whether this is an official registry - Official bool -} - -// SearchResult describes a search result returned from a registry -type SearchResult struct { - // StarCount indicates the number of stars this repository has - StarCount int `json:"star_count"` - // IsOfficial is true if the result is from an official repository. - IsOfficial bool `json:"is_official"` - // Name is the name of the repository - Name string `json:"name"` - // IsAutomated indicates whether the result is automated - IsAutomated bool `json:"is_automated"` - // Description is a textual description of the repository - Description string `json:"description"` -} - -// SearchResults lists a collection search results returned from a registry -type SearchResults struct { - // Query contains the query string that generated the search results - Query string `json:"query"` - // NumResults indicates the number of results the query returned - NumResults int `json:"num_results"` - // Results is a slice containing the actual results for the search - Results []SearchResult `json:"results"` -} diff --git a/vendor/github.com/docker/docker/api/types/seccomp.go b/vendor/github.com/docker/docker/api/types/seccomp.go deleted file mode 100644 index 7d62c9a43f..0000000000 --- a/vendor/github.com/docker/docker/api/types/seccomp.go +++ /dev/null @@ -1,93 +0,0 @@ -package types - -// Seccomp represents the config for a seccomp profile for syscall restriction. -type Seccomp struct { - DefaultAction Action `json:"defaultAction"` - // Architectures is kept to maintain backward compatibility with the old - // seccomp profile. - Architectures []Arch `json:"architectures,omitempty"` - ArchMap []Architecture `json:"archMap,omitempty"` - Syscalls []*Syscall `json:"syscalls"` -} - -// Architecture is used to represent a specific architecture -// and its sub-architectures -type Architecture struct { - Arch Arch `json:"architecture"` - SubArches []Arch `json:"subArchitectures"` -} - -// Arch used for architectures -type Arch string - -// Additional architectures permitted to be used for system calls -// By default only the native architecture of the kernel is permitted -const ( - ArchX86 Arch = "SCMP_ARCH_X86" - ArchX86_64 Arch = "SCMP_ARCH_X86_64" - ArchX32 Arch = "SCMP_ARCH_X32" - ArchARM Arch = "SCMP_ARCH_ARM" - ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" - ArchMIPS Arch = "SCMP_ARCH_MIPS" - ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" - ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" - ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" - ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" - ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" - ArchPPC Arch = "SCMP_ARCH_PPC" - ArchPPC64 Arch = "SCMP_ARCH_PPC64" - ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" - ArchS390 Arch = "SCMP_ARCH_S390" - ArchS390X Arch = "SCMP_ARCH_S390X" -) - -// Action taken upon Seccomp rule match -type Action string - -// Define actions for Seccomp rules -const ( - ActKill Action = "SCMP_ACT_KILL" - ActTrap Action = "SCMP_ACT_TRAP" - ActErrno Action = "SCMP_ACT_ERRNO" - ActTrace Action = "SCMP_ACT_TRACE" - ActAllow Action = "SCMP_ACT_ALLOW" -) - -// Operator used to match syscall arguments in Seccomp -type Operator string - -// Define operators for syscall arguments in Seccomp -const ( - OpNotEqual Operator = "SCMP_CMP_NE" - OpLessThan Operator = "SCMP_CMP_LT" - OpLessEqual Operator = "SCMP_CMP_LE" - OpEqualTo Operator = "SCMP_CMP_EQ" - OpGreaterEqual Operator = "SCMP_CMP_GE" - OpGreaterThan Operator = "SCMP_CMP_GT" - OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" -) - -// Arg used for matching specific syscall arguments in Seccomp -type Arg struct { - Index uint `json:"index"` - Value uint64 `json:"value"` - ValueTwo uint64 `json:"valueTwo"` - Op Operator `json:"op"` -} - -// Filter is used to conditionally apply Seccomp rules -type Filter struct { - Caps []string `json:"caps,omitempty"` - Arches []string `json:"arches,omitempty"` -} - -// Syscall is used to match a group of syscalls in Seccomp -type Syscall struct { - Name string `json:"name,omitempty"` - Names []string `json:"names,omitempty"` - Action Action `json:"action"` - Args []*Arg `json:"args"` - Comment string `json:"comment"` - Includes Filter `json:"includes"` - Excludes Filter `json:"excludes"` -} diff --git a/vendor/github.com/docker/docker/api/types/service_update_response.go b/vendor/github.com/docker/docker/api/types/service_update_response.go deleted file mode 100644 index 74ea64b1bb..0000000000 --- a/vendor/github.com/docker/docker/api/types/service_update_response.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// ServiceUpdateResponse service update response -// swagger:model ServiceUpdateResponse -type ServiceUpdateResponse struct { - - // Optional warning messages - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/api/types/stats.go b/vendor/github.com/docker/docker/api/types/stats.go deleted file mode 100644 index 7ca76a5b63..0000000000 --- a/vendor/github.com/docker/docker/api/types/stats.go +++ /dev/null @@ -1,181 +0,0 @@ -// Package types is used for API stability in the types and response to the -// consumers of the API stats endpoint. -package types - -import "time" - -// ThrottlingData stores CPU throttling stats of one running container. -// Not used on Windows. -type ThrottlingData struct { - // Number of periods with throttling active - Periods uint64 `json:"periods"` - // Number of periods when the container hits its throttling limit. - ThrottledPeriods uint64 `json:"throttled_periods"` - // Aggregate time the container was throttled for in nanoseconds. - ThrottledTime uint64 `json:"throttled_time"` -} - -// CPUUsage stores All CPU stats aggregated since container inception. -type CPUUsage struct { - // Total CPU time consumed. - // Units: nanoseconds (Linux) - // Units: 100's of nanoseconds (Windows) - TotalUsage uint64 `json:"total_usage"` - - // Total CPU time consumed per core (Linux). Not used on Windows. - // Units: nanoseconds. - PercpuUsage []uint64 `json:"percpu_usage,omitempty"` - - // Time spent by tasks of the cgroup in kernel mode (Linux). - // Time spent by all container processes in kernel mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers. - UsageInKernelmode uint64 `json:"usage_in_kernelmode"` - - // Time spent by tasks of the cgroup in user mode (Linux). - // Time spent by all container processes in user mode (Windows). - // Units: nanoseconds (Linux). - // Units: 100's of nanoseconds (Windows). Not populated for Hyper-V Containers - UsageInUsermode uint64 `json:"usage_in_usermode"` -} - -// CPUStats aggregates and wraps all CPU related info of container -type CPUStats struct { - // CPU Usage. Linux and Windows. - CPUUsage CPUUsage `json:"cpu_usage"` - - // System Usage. Linux only. - SystemUsage uint64 `json:"system_cpu_usage,omitempty"` - - // Online CPUs. Linux only. - OnlineCPUs uint32 `json:"online_cpus,omitempty"` - - // Throttling Data. Linux only. - ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` -} - -// MemoryStats aggregates all memory stats since container inception on Linux. -// Windows returns stats for commit and private working set only. -type MemoryStats struct { - // Linux Memory Stats - - // current res_counter usage for memory - Usage uint64 `json:"usage,omitempty"` - // maximum usage ever recorded. - MaxUsage uint64 `json:"max_usage,omitempty"` - // TODO(vishh): Export these as stronger types. - // all the stats exported via memory.stat. - Stats map[string]uint64 `json:"stats,omitempty"` - // number of times memory usage hits limits. - Failcnt uint64 `json:"failcnt,omitempty"` - Limit uint64 `json:"limit,omitempty"` - - // Windows Memory Stats - // See https://technet.microsoft.com/en-us/magazine/ff382715.aspx - - // committed bytes - Commit uint64 `json:"commitbytes,omitempty"` - // peak committed bytes - CommitPeak uint64 `json:"commitpeakbytes,omitempty"` - // private working set - PrivateWorkingSet uint64 `json:"privateworkingset,omitempty"` -} - -// BlkioStatEntry is one small entity to store a piece of Blkio stats -// Not used on Windows. -type BlkioStatEntry struct { - Major uint64 `json:"major"` - Minor uint64 `json:"minor"` - Op string `json:"op"` - Value uint64 `json:"value"` -} - -// BlkioStats stores All IO service stats for data read and write. -// This is a Linux specific structure as the differences between expressing -// block I/O on Windows and Linux are sufficiently significant to make -// little sense attempting to morph into a combined structure. -type BlkioStats struct { - // number of bytes transferred to and from the block device - IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` - IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` - IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` - IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` - IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` - IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` - IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` - SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` -} - -// StorageStats is the disk I/O stats for read/write on Windows. -type StorageStats struct { - ReadCountNormalized uint64 `json:"read_count_normalized,omitempty"` - ReadSizeBytes uint64 `json:"read_size_bytes,omitempty"` - WriteCountNormalized uint64 `json:"write_count_normalized,omitempty"` - WriteSizeBytes uint64 `json:"write_size_bytes,omitempty"` -} - -// NetworkStats aggregates the network stats of one container -type NetworkStats struct { - // Bytes received. Windows and Linux. - RxBytes uint64 `json:"rx_bytes"` - // Packets received. Windows and Linux. - RxPackets uint64 `json:"rx_packets"` - // Received errors. Not used on Windows. Note that we dont `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - RxErrors uint64 `json:"rx_errors"` - // Incoming packets dropped. Windows and Linux. - RxDropped uint64 `json:"rx_dropped"` - // Bytes sent. Windows and Linux. - TxBytes uint64 `json:"tx_bytes"` - // Packets sent. Windows and Linux. - TxPackets uint64 `json:"tx_packets"` - // Sent errors. Not used on Windows. Note that we dont `omitempty` this - // field as it is expected in the >=v1.21 API stats structure. - TxErrors uint64 `json:"tx_errors"` - // Outgoing packets dropped. Windows and Linux. - TxDropped uint64 `json:"tx_dropped"` - // Endpoint ID. Not used on Linux. - EndpointID string `json:"endpoint_id,omitempty"` - // Instance ID. Not used on Linux. - InstanceID string `json:"instance_id,omitempty"` -} - -// PidsStats contains the stats of a container's pids -type PidsStats struct { - // Current is the number of pids in the cgroup - Current uint64 `json:"current,omitempty"` - // Limit is the hard limit on the number of pids in the cgroup. - // A "Limit" of 0 means that there is no limit. - Limit uint64 `json:"limit,omitempty"` -} - -// Stats is Ultimate struct aggregating all types of stats of one container -type Stats struct { - // Common stats - Read time.Time `json:"read"` - PreRead time.Time `json:"preread"` - - // Linux specific stats, not populated on Windows. - PidsStats PidsStats `json:"pids_stats,omitempty"` - BlkioStats BlkioStats `json:"blkio_stats,omitempty"` - - // Windows specific stats, not populated on Linux. - NumProcs uint32 `json:"num_procs"` - StorageStats StorageStats `json:"storage_stats,omitempty"` - - // Shared stats - CPUStats CPUStats `json:"cpu_stats,omitempty"` - PreCPUStats CPUStats `json:"precpu_stats,omitempty"` // "Pre"="Previous" - MemoryStats MemoryStats `json:"memory_stats,omitempty"` -} - -// StatsJSON is newly used Networks -type StatsJSON struct { - Stats - - Name string `json:"name,omitempty"` - ID string `json:"id,omitempty"` - - // Networks request version >=1.21 - Networks map[string]NetworkStats `json:"networks,omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/strslice/strslice.go b/vendor/github.com/docker/docker/api/types/strslice/strslice.go deleted file mode 100644 index bad493fb89..0000000000 --- a/vendor/github.com/docker/docker/api/types/strslice/strslice.go +++ /dev/null @@ -1,30 +0,0 @@ -package strslice - -import "encoding/json" - -// StrSlice represents a string or an array of strings. -// We need to override the json decoder to accept both options. -type StrSlice []string - -// UnmarshalJSON decodes the byte slice whether it's a string or an array of -// strings. This method is needed to implement json.Unmarshaler. -func (e *StrSlice) UnmarshalJSON(b []byte) error { - if len(b) == 0 { - // With no input, we preserve the existing value by returning nil and - // leaving the target alone. This allows defining default values for - // the type. - return nil - } - - p := make([]string, 0, 1) - if err := json.Unmarshal(b, &p); err != nil { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - p = append(p, s) - } - - *e = p - return nil -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/common.go b/vendor/github.com/docker/docker/api/types/swarm/common.go deleted file mode 100644 index dc76a146bb..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/common.go +++ /dev/null @@ -1,27 +0,0 @@ -package swarm - -import "time" - -// Version represents the internal object version. -type Version struct { - Index uint64 `json:",omitempty"` -} - -// Meta is a base object inherited by most of the other once. -type Meta struct { - Version Version `json:",omitempty"` - CreatedAt time.Time `json:",omitempty"` - UpdatedAt time.Time `json:",omitempty"` -} - -// Annotations represents how to describe an object. -type Annotations struct { - Name string `json:",omitempty"` - Labels map[string]string `json:"Labels"` -} - -// Driver represents a driver (network, logging). -type Driver struct { - Name string `json:",omitempty"` - Options map[string]string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/container.go b/vendor/github.com/docker/docker/api/types/swarm/container.go deleted file mode 100644 index 135f7cbbfc..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ /dev/null @@ -1,71 +0,0 @@ -package swarm - -import ( - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/mount" -) - -// DNSConfig specifies DNS related configurations in resolver configuration file (resolv.conf) -// Detailed documentation is available in: -// http://man7.org/linux/man-pages/man5/resolv.conf.5.html -// `nameserver`, `search`, `options` have been supported. -// TODO: `domain` is not supported yet. -type DNSConfig struct { - // Nameservers specifies the IP addresses of the name servers - Nameservers []string `json:",omitempty"` - // Search specifies the search list for host-name lookup - Search []string `json:",omitempty"` - // Options allows certain internal resolver variables to be modified - Options []string `json:",omitempty"` -} - -// SELinuxContext contains the SELinux labels of the container. -type SELinuxContext struct { - Disable bool - - User string - Role string - Type string - Level string -} - -// CredentialSpec for managed service account (Windows only) -type CredentialSpec struct { - File string - Registry string -} - -// Privileges defines the security options for the container. -type Privileges struct { - CredentialSpec *CredentialSpec - SELinuxContext *SELinuxContext -} - -// ContainerSpec represents the spec of a container. -type ContainerSpec struct { - Image string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Command []string `json:",omitempty"` - Args []string `json:",omitempty"` - Hostname string `json:",omitempty"` - Env []string `json:",omitempty"` - Dir string `json:",omitempty"` - User string `json:",omitempty"` - Groups []string `json:",omitempty"` - Privileges *Privileges `json:",omitempty"` - StopSignal string `json:",omitempty"` - TTY bool `json:",omitempty"` - OpenStdin bool `json:",omitempty"` - ReadOnly bool `json:",omitempty"` - Mounts []mount.Mount `json:",omitempty"` - StopGracePeriod *time.Duration `json:",omitempty"` - Healthcheck *container.HealthConfig `json:",omitempty"` - // The format of extra hosts on swarmkit is specified in: - // http://man7.org/linux/man-pages/man5/hosts.5.html - // IP_address canonical_hostname [aliases...] - Hosts []string `json:",omitempty"` - DNSConfig *DNSConfig `json:",omitempty"` - Secrets []*SecretReference `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/network.go b/vendor/github.com/docker/docker/api/types/swarm/network.go deleted file mode 100644 index 693f85cce1..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/network.go +++ /dev/null @@ -1,112 +0,0 @@ -package swarm - -// Endpoint represents an endpoint. -type Endpoint struct { - Spec EndpointSpec `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` - VirtualIPs []EndpointVirtualIP `json:",omitempty"` -} - -// EndpointSpec represents the spec of an endpoint. -type EndpointSpec struct { - Mode ResolutionMode `json:",omitempty"` - Ports []PortConfig `json:",omitempty"` -} - -// ResolutionMode represents a resolution mode. -type ResolutionMode string - -const ( - // ResolutionModeVIP VIP - ResolutionModeVIP ResolutionMode = "vip" - // ResolutionModeDNSRR DNSRR - ResolutionModeDNSRR ResolutionMode = "dnsrr" -) - -// PortConfig represents the config of a port. -type PortConfig struct { - Name string `json:",omitempty"` - Protocol PortConfigProtocol `json:",omitempty"` - // TargetPort is the port inside the container - TargetPort uint32 `json:",omitempty"` - // PublishedPort is the port on the swarm hosts - PublishedPort uint32 `json:",omitempty"` - // PublishMode is the mode in which port is published - PublishMode PortConfigPublishMode `json:",omitempty"` -} - -// PortConfigPublishMode represents the mode in which the port is to -// be published. -type PortConfigPublishMode string - -const ( - // PortConfigPublishModeIngress is used for ports published - // for ingress load balancing using routing mesh. - PortConfigPublishModeIngress PortConfigPublishMode = "ingress" - // PortConfigPublishModeHost is used for ports published - // for direct host level access on the host where the task is running. - PortConfigPublishModeHost PortConfigPublishMode = "host" -) - -// PortConfigProtocol represents the protocol of a port. -type PortConfigProtocol string - -const ( - // TODO(stevvooe): These should be used generally, not just for PortConfig. - - // PortConfigProtocolTCP TCP - PortConfigProtocolTCP PortConfigProtocol = "tcp" - // PortConfigProtocolUDP UDP - PortConfigProtocolUDP PortConfigProtocol = "udp" -) - -// EndpointVirtualIP represents the virtual ip of a port. -type EndpointVirtualIP struct { - NetworkID string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Network represents a network. -type Network struct { - ID string - Meta - Spec NetworkSpec `json:",omitempty"` - DriverState Driver `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` -} - -// NetworkSpec represents the spec of a network. -type NetworkSpec struct { - Annotations - DriverConfiguration *Driver `json:",omitempty"` - IPv6Enabled bool `json:",omitempty"` - Internal bool `json:",omitempty"` - Attachable bool `json:",omitempty"` - Ingress bool `json:",omitempty"` - IPAMOptions *IPAMOptions `json:",omitempty"` -} - -// NetworkAttachmentConfig represents the configuration of a network attachment. -type NetworkAttachmentConfig struct { - Target string `json:",omitempty"` - Aliases []string `json:",omitempty"` -} - -// NetworkAttachment represents a network attachment. -type NetworkAttachment struct { - Network Network `json:",omitempty"` - Addresses []string `json:",omitempty"` -} - -// IPAMOptions represents ipam options. -type IPAMOptions struct { - Driver Driver `json:",omitempty"` - Configs []IPAMConfig `json:",omitempty"` -} - -// IPAMConfig represents ipam configuration. -type IPAMConfig struct { - Subnet string `json:",omitempty"` - Range string `json:",omitempty"` - Gateway string `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/node.go b/vendor/github.com/docker/docker/api/types/swarm/node.go deleted file mode 100644 index 379e17a779..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/node.go +++ /dev/null @@ -1,114 +0,0 @@ -package swarm - -// Node represents a node. -type Node struct { - ID string - Meta - // Spec defines the desired state of the node as specified by the user. - // The system will honor this and will *never* modify it. - Spec NodeSpec `json:",omitempty"` - // Description encapsulates the properties of the Node as reported by the - // agent. - Description NodeDescription `json:",omitempty"` - // Status provides the current status of the node, as seen by the manager. - Status NodeStatus `json:",omitempty"` - // ManagerStatus provides the current status of the node's manager - // component, if the node is a manager. - ManagerStatus *ManagerStatus `json:",omitempty"` -} - -// NodeSpec represents the spec of a node. -type NodeSpec struct { - Annotations - Role NodeRole `json:",omitempty"` - Availability NodeAvailability `json:",omitempty"` -} - -// NodeRole represents the role of a node. -type NodeRole string - -const ( - // NodeRoleWorker WORKER - NodeRoleWorker NodeRole = "worker" - // NodeRoleManager MANAGER - NodeRoleManager NodeRole = "manager" -) - -// NodeAvailability represents the availability of a node. -type NodeAvailability string - -const ( - // NodeAvailabilityActive ACTIVE - NodeAvailabilityActive NodeAvailability = "active" - // NodeAvailabilityPause PAUSE - NodeAvailabilityPause NodeAvailability = "pause" - // NodeAvailabilityDrain DRAIN - NodeAvailabilityDrain NodeAvailability = "drain" -) - -// NodeDescription represents the description of a node. -type NodeDescription struct { - Hostname string `json:",omitempty"` - Platform Platform `json:",omitempty"` - Resources Resources `json:",omitempty"` - Engine EngineDescription `json:",omitempty"` -} - -// Platform represents the platform (Arch/OS). -type Platform struct { - Architecture string `json:",omitempty"` - OS string `json:",omitempty"` -} - -// EngineDescription represents the description of an engine. -type EngineDescription struct { - EngineVersion string `json:",omitempty"` - Labels map[string]string `json:",omitempty"` - Plugins []PluginDescription `json:",omitempty"` -} - -// PluginDescription represents the description of an engine plugin. -type PluginDescription struct { - Type string `json:",omitempty"` - Name string `json:",omitempty"` -} - -// NodeStatus represents the status of a node. -type NodeStatus struct { - State NodeState `json:",omitempty"` - Message string `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// Reachability represents the reachability of a node. -type Reachability string - -const ( - // ReachabilityUnknown UNKNOWN - ReachabilityUnknown Reachability = "unknown" - // ReachabilityUnreachable UNREACHABLE - ReachabilityUnreachable Reachability = "unreachable" - // ReachabilityReachable REACHABLE - ReachabilityReachable Reachability = "reachable" -) - -// ManagerStatus represents the status of a manager. -type ManagerStatus struct { - Leader bool `json:",omitempty"` - Reachability Reachability `json:",omitempty"` - Addr string `json:",omitempty"` -} - -// NodeState represents the state of a node. -type NodeState string - -const ( - // NodeStateUnknown UNKNOWN - NodeStateUnknown NodeState = "unknown" - // NodeStateDown DOWN - NodeStateDown NodeState = "down" - // NodeStateReady READY - NodeStateReady NodeState = "ready" - // NodeStateDisconnected DISCONNECTED - NodeStateDisconnected NodeState = "disconnected" -) diff --git a/vendor/github.com/docker/docker/api/types/swarm/runtime.go b/vendor/github.com/docker/docker/api/types/swarm/runtime.go deleted file mode 100644 index c4c731dc82..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime.go +++ /dev/null @@ -1,19 +0,0 @@ -package swarm - -// RuntimeType is the type of runtime used for the TaskSpec -type RuntimeType string - -// RuntimeURL is the proto type url -type RuntimeURL string - -const ( - // RuntimeContainer is the container based runtime - RuntimeContainer RuntimeType = "container" - // RuntimePlugin is the plugin based runtime - RuntimePlugin RuntimeType = "plugin" - - // RuntimeURLContainer is the proto url for the container type - RuntimeURLContainer RuntimeURL = "types.docker.com/RuntimeContainer" - // RuntimeURLPlugin is the proto url for the plugin type - RuntimeURLPlugin RuntimeURL = "types.docker.com/RuntimePlugin" -) diff --git a/vendor/github.com/docker/docker/api/types/swarm/secret.go b/vendor/github.com/docker/docker/api/types/swarm/secret.go deleted file mode 100644 index fdb2388888..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/secret.go +++ /dev/null @@ -1,31 +0,0 @@ -package swarm - -import "os" - -// Secret represents a secret. -type Secret struct { - ID string - Meta - Spec SecretSpec -} - -// SecretSpec represents a secret specification from a secret in swarm -type SecretSpec struct { - Annotations - Data []byte `json:",omitempty"` -} - -// SecretReferenceFileTarget is a file target in a secret reference -type SecretReferenceFileTarget struct { - Name string - UID string - GID string - Mode os.FileMode -} - -// SecretReference is a reference to a secret in swarm -type SecretReference struct { - File *SecretReferenceFileTarget - SecretID string - SecretName string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/service.go b/vendor/github.com/docker/docker/api/types/swarm/service.go deleted file mode 100644 index fa31a7ec86..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ /dev/null @@ -1,124 +0,0 @@ -package swarm - -import "time" - -// Service represents a service. -type Service struct { - ID string - Meta - Spec ServiceSpec `json:",omitempty"` - PreviousSpec *ServiceSpec `json:",omitempty"` - Endpoint Endpoint `json:",omitempty"` - UpdateStatus *UpdateStatus `json:",omitempty"` -} - -// ServiceSpec represents the spec of a service. -type ServiceSpec struct { - Annotations - - // TaskTemplate defines how the service should construct new tasks when - // orchestrating this service. - TaskTemplate TaskSpec `json:",omitempty"` - Mode ServiceMode `json:",omitempty"` - UpdateConfig *UpdateConfig `json:",omitempty"` - RollbackConfig *UpdateConfig `json:",omitempty"` - - // Networks field in ServiceSpec is deprecated. The - // same field in TaskSpec should be used instead. - // This field will be removed in a future release. - Networks []NetworkAttachmentConfig `json:",omitempty"` - EndpointSpec *EndpointSpec `json:",omitempty"` -} - -// ServiceMode represents the mode of a service. -type ServiceMode struct { - Replicated *ReplicatedService `json:",omitempty"` - Global *GlobalService `json:",omitempty"` -} - -// UpdateState is the state of a service update. -type UpdateState string - -const ( - // UpdateStateUpdating is the updating state. - UpdateStateUpdating UpdateState = "updating" - // UpdateStatePaused is the paused state. - UpdateStatePaused UpdateState = "paused" - // UpdateStateCompleted is the completed state. - UpdateStateCompleted UpdateState = "completed" - // UpdateStateRollbackStarted is the state with a rollback in progress. - UpdateStateRollbackStarted UpdateState = "rollback_started" - // UpdateStateRollbackPaused is the state with a rollback in progress. - UpdateStateRollbackPaused UpdateState = "rollback_paused" - // UpdateStateRollbackCompleted is the state with a rollback in progress. - UpdateStateRollbackCompleted UpdateState = "rollback_completed" -) - -// UpdateStatus reports the status of a service update. -type UpdateStatus struct { - State UpdateState `json:",omitempty"` - StartedAt *time.Time `json:",omitempty"` - CompletedAt *time.Time `json:",omitempty"` - Message string `json:",omitempty"` -} - -// ReplicatedService is a kind of ServiceMode. -type ReplicatedService struct { - Replicas *uint64 `json:",omitempty"` -} - -// GlobalService is a kind of ServiceMode. -type GlobalService struct{} - -const ( - // UpdateFailureActionPause PAUSE - UpdateFailureActionPause = "pause" - // UpdateFailureActionContinue CONTINUE - UpdateFailureActionContinue = "continue" - // UpdateFailureActionRollback ROLLBACK - UpdateFailureActionRollback = "rollback" - - // UpdateOrderStopFirst STOP_FIRST - UpdateOrderStopFirst = "stop-first" - // UpdateOrderStartFirst START_FIRST - UpdateOrderStartFirst = "start-first" -) - -// UpdateConfig represents the update configuration. -type UpdateConfig struct { - // Maximum number of tasks to be updated in one iteration. - // 0 means unlimited parallelism. - Parallelism uint64 - - // Amount of time between updates. - Delay time.Duration `json:",omitempty"` - - // FailureAction is the action to take when an update failures. - FailureAction string `json:",omitempty"` - - // Monitor indicates how long to monitor a task for failure after it is - // created. If the task fails by ending up in one of the states - // REJECTED, COMPLETED, or FAILED, within Monitor from its creation, - // this counts as a failure. If it fails after Monitor, it does not - // count as a failure. If Monitor is unspecified, a default value will - // be used. - Monitor time.Duration `json:",omitempty"` - - // MaxFailureRatio is the fraction of tasks that may fail during - // an update before the failure action is invoked. Any task created by - // the current update which ends up in one of the states REJECTED, - // COMPLETED or FAILED within Monitor from its creation counts as a - // failure. The number of failures is divided by the number of tasks - // being updated, and if this fraction is greater than - // MaxFailureRatio, the failure action is invoked. - // - // If the failure action is CONTINUE, there is no effect. - // If the failure action is PAUSE, no more tasks will be updated until - // another update is started. - MaxFailureRatio float32 - - // Order indicates the order of operations when rolling out an updated - // task. Either the old task is shut down before the new task is - // started, or the new task is started before the old task is shut down. - Order string -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/swarm.go b/vendor/github.com/docker/docker/api/types/swarm/swarm.go deleted file mode 100644 index c513274750..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/swarm.go +++ /dev/null @@ -1,199 +0,0 @@ -package swarm - -import "time" - -// ClusterInfo represents info about the cluster for outputing in "info" -// it contains the same information as "Swarm", but without the JoinTokens -type ClusterInfo struct { - ID string - Meta - Spec Spec -} - -// Swarm represents a swarm. -type Swarm struct { - ClusterInfo - JoinTokens JoinTokens -} - -// JoinTokens contains the tokens workers and managers need to join the swarm. -type JoinTokens struct { - // Worker is the join token workers may use to join the swarm. - Worker string - // Manager is the join token managers may use to join the swarm. - Manager string -} - -// Spec represents the spec of a swarm. -type Spec struct { - Annotations - - Orchestration OrchestrationConfig `json:",omitempty"` - Raft RaftConfig `json:",omitempty"` - Dispatcher DispatcherConfig `json:",omitempty"` - CAConfig CAConfig `json:",omitempty"` - TaskDefaults TaskDefaults `json:",omitempty"` - EncryptionConfig EncryptionConfig `json:",omitempty"` -} - -// OrchestrationConfig represents orchestration configuration. -type OrchestrationConfig struct { - // TaskHistoryRetentionLimit is the number of historic tasks to keep per instance or - // node. If negative, never remove completed or failed tasks. - TaskHistoryRetentionLimit *int64 `json:",omitempty"` -} - -// TaskDefaults parameterizes cluster-level task creation with default values. -type TaskDefaults struct { - // LogDriver selects the log driver to use for tasks created in the - // orchestrator if unspecified by a service. - // - // Updating this value will only have an affect on new tasks. Old tasks - // will continue use their previously configured log driver until - // recreated. - LogDriver *Driver `json:",omitempty"` -} - -// EncryptionConfig controls at-rest encryption of data and keys. -type EncryptionConfig struct { - // AutoLockManagers specifies whether or not managers TLS keys and raft data - // should be encrypted at rest in such a way that they must be unlocked - // before the manager node starts up again. - AutoLockManagers bool -} - -// RaftConfig represents raft configuration. -type RaftConfig struct { - // SnapshotInterval is the number of log entries between snapshots. - SnapshotInterval uint64 `json:",omitempty"` - - // KeepOldSnapshots is the number of snapshots to keep beyond the - // current snapshot. - KeepOldSnapshots *uint64 `json:",omitempty"` - - // LogEntriesForSlowFollowers is the number of log entries to keep - // around to sync up slow followers after a snapshot is created. - LogEntriesForSlowFollowers uint64 `json:",omitempty"` - - // ElectionTick is the number of ticks that a follower will wait for a message - // from the leader before becoming a candidate and starting an election. - // ElectionTick must be greater than HeartbeatTick. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - ElectionTick int - - // HeartbeatTick is the number of ticks between heartbeats. Every - // HeartbeatTick ticks, the leader will send a heartbeat to the - // followers. - // - // A tick currently defaults to one second, so these translate directly to - // seconds currently, but this is NOT guaranteed. - HeartbeatTick int -} - -// DispatcherConfig represents dispatcher configuration. -type DispatcherConfig struct { - // HeartbeatPeriod defines how often agent should send heartbeats to - // dispatcher. - HeartbeatPeriod time.Duration `json:",omitempty"` -} - -// CAConfig represents CA configuration. -type CAConfig struct { - // NodeCertExpiry is the duration certificates should be issued for - NodeCertExpiry time.Duration `json:",omitempty"` - - // ExternalCAs is a list of CAs to which a manager node will make - // certificate signing requests for node certificates. - ExternalCAs []*ExternalCA `json:",omitempty"` -} - -// ExternalCAProtocol represents type of external CA. -type ExternalCAProtocol string - -// ExternalCAProtocolCFSSL CFSSL -const ExternalCAProtocolCFSSL ExternalCAProtocol = "cfssl" - -// ExternalCA defines external CA to be used by the cluster. -type ExternalCA struct { - // Protocol is the protocol used by this external CA. - Protocol ExternalCAProtocol - - // URL is the URL where the external CA can be reached. - URL string - - // Options is a set of additional key/value pairs whose interpretation - // depends on the specified CA type. - Options map[string]string `json:",omitempty"` -} - -// InitRequest is the request used to init a swarm. -type InitRequest struct { - ListenAddr string - AdvertiseAddr string - ForceNewCluster bool - Spec Spec - AutoLockManagers bool - Availability NodeAvailability -} - -// JoinRequest is the request used to join a swarm. -type JoinRequest struct { - ListenAddr string - AdvertiseAddr string - RemoteAddrs []string - JoinToken string // accept by secret - Availability NodeAvailability -} - -// UnlockRequest is the request used to unlock a swarm. -type UnlockRequest struct { - // UnlockKey is the unlock key in ASCII-armored format. - UnlockKey string -} - -// LocalNodeState represents the state of the local node. -type LocalNodeState string - -const ( - // LocalNodeStateInactive INACTIVE - LocalNodeStateInactive LocalNodeState = "inactive" - // LocalNodeStatePending PENDING - LocalNodeStatePending LocalNodeState = "pending" - // LocalNodeStateActive ACTIVE - LocalNodeStateActive LocalNodeState = "active" - // LocalNodeStateError ERROR - LocalNodeStateError LocalNodeState = "error" - // LocalNodeStateLocked LOCKED - LocalNodeStateLocked LocalNodeState = "locked" -) - -// Info represents generic information about swarm. -type Info struct { - NodeID string - NodeAddr string - - LocalNodeState LocalNodeState - ControlAvailable bool - Error string - - RemoteManagers []Peer - Nodes int `json:",omitempty"` - Managers int `json:",omitempty"` - - Cluster *ClusterInfo `json:",omitempty"` -} - -// Peer represents a peer. -type Peer struct { - NodeID string - Addr string -} - -// UpdateFlags contains flags for SwarmUpdate. -type UpdateFlags struct { - RotateWorkerToken bool - RotateManagerToken bool - RotateManagerUnlockKey bool -} diff --git a/vendor/github.com/docker/docker/api/types/swarm/task.go b/vendor/github.com/docker/docker/api/types/swarm/task.go deleted file mode 100644 index 99e9a6d58b..0000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/task.go +++ /dev/null @@ -1,147 +0,0 @@ -package swarm - -import "time" - -// TaskState represents the state of a task. -type TaskState string - -const ( - // TaskStateNew NEW - TaskStateNew TaskState = "new" - // TaskStateAllocated ALLOCATED - TaskStateAllocated TaskState = "allocated" - // TaskStatePending PENDING - TaskStatePending TaskState = "pending" - // TaskStateAssigned ASSIGNED - TaskStateAssigned TaskState = "assigned" - // TaskStateAccepted ACCEPTED - TaskStateAccepted TaskState = "accepted" - // TaskStatePreparing PREPARING - TaskStatePreparing TaskState = "preparing" - // TaskStateReady READY - TaskStateReady TaskState = "ready" - // TaskStateStarting STARTING - TaskStateStarting TaskState = "starting" - // TaskStateRunning RUNNING - TaskStateRunning TaskState = "running" - // TaskStateComplete COMPLETE - TaskStateComplete TaskState = "complete" - // TaskStateShutdown SHUTDOWN - TaskStateShutdown TaskState = "shutdown" - // TaskStateFailed FAILED - TaskStateFailed TaskState = "failed" - // TaskStateRejected REJECTED - TaskStateRejected TaskState = "rejected" -) - -// Task represents a task. -type Task struct { - ID string - Meta - Annotations - - Spec TaskSpec `json:",omitempty"` - ServiceID string `json:",omitempty"` - Slot int `json:",omitempty"` - NodeID string `json:",omitempty"` - Status TaskStatus `json:",omitempty"` - DesiredState TaskState `json:",omitempty"` - NetworksAttachments []NetworkAttachment `json:",omitempty"` -} - -// TaskSpec represents the spec of a task. -type TaskSpec struct { - ContainerSpec ContainerSpec `json:",omitempty"` - Resources *ResourceRequirements `json:",omitempty"` - RestartPolicy *RestartPolicy `json:",omitempty"` - Placement *Placement `json:",omitempty"` - Networks []NetworkAttachmentConfig `json:",omitempty"` - - // LogDriver specifies the LogDriver to use for tasks created from this - // spec. If not present, the one on cluster default on swarm.Spec will be - // used, finally falling back to the engine default if not specified. - LogDriver *Driver `json:",omitempty"` - - // ForceUpdate is a counter that triggers an update even if no relevant - // parameters have been changed. - ForceUpdate uint64 - - Runtime RuntimeType `json:",omitempty"` - // TODO (ehazlett): this should be removed and instead - // use struct tags (proto) for the runtimes - RuntimeData []byte `json:",omitempty"` -} - -// Resources represents resources (CPU/Memory). -type Resources struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` -} - -// ResourceRequirements represents resources requirements. -type ResourceRequirements struct { - Limits *Resources `json:",omitempty"` - Reservations *Resources `json:",omitempty"` -} - -// Placement represents orchestration parameters. -type Placement struct { - Constraints []string `json:",omitempty"` - Preferences []PlacementPreference `json:",omitempty"` -} - -// PlacementPreference provides a way to make the scheduler aware of factors -// such as topology. -type PlacementPreference struct { - Spread *SpreadOver -} - -// SpreadOver is a scheduling preference that instructs the scheduler to spread -// tasks evenly over groups of nodes identified by labels. -type SpreadOver struct { - // label descriptor, such as engine.labels.az - SpreadDescriptor string -} - -// RestartPolicy represents the restart policy. -type RestartPolicy struct { - Condition RestartPolicyCondition `json:",omitempty"` - Delay *time.Duration `json:",omitempty"` - MaxAttempts *uint64 `json:",omitempty"` - Window *time.Duration `json:",omitempty"` -} - -// RestartPolicyCondition represents when to restart. -type RestartPolicyCondition string - -const ( - // RestartPolicyConditionNone NONE - RestartPolicyConditionNone RestartPolicyCondition = "none" - // RestartPolicyConditionOnFailure ON_FAILURE - RestartPolicyConditionOnFailure RestartPolicyCondition = "on-failure" - // RestartPolicyConditionAny ANY - RestartPolicyConditionAny RestartPolicyCondition = "any" -) - -// TaskStatus represents the status of a task. -type TaskStatus struct { - Timestamp time.Time `json:",omitempty"` - State TaskState `json:",omitempty"` - Message string `json:",omitempty"` - Err string `json:",omitempty"` - ContainerStatus ContainerStatus `json:",omitempty"` - PortStatus PortStatus `json:",omitempty"` -} - -// ContainerStatus represents the status of a container. -type ContainerStatus struct { - ContainerID string `json:",omitempty"` - PID int `json:",omitempty"` - ExitCode int `json:",omitempty"` -} - -// PortStatus represents the port status of a task's host ports whose -// service has published host ports -type PortStatus struct { - Ports []PortConfig `json:",omitempty"` -} diff --git a/vendor/github.com/docker/docker/api/types/time/duration_convert.go b/vendor/github.com/docker/docker/api/types/time/duration_convert.go deleted file mode 100644 index 63e1eec19e..0000000000 --- a/vendor/github.com/docker/docker/api/types/time/duration_convert.go +++ /dev/null @@ -1,12 +0,0 @@ -package time - -import ( - "strconv" - "time" -) - -// DurationToSecondsString converts the specified duration to the number -// seconds it represents, formatted as a string. -func DurationToSecondsString(duration time.Duration) string { - return strconv.FormatFloat(duration.Seconds(), 'f', 0, 64) -} diff --git a/vendor/github.com/docker/docker/api/types/time/timestamp.go b/vendor/github.com/docker/docker/api/types/time/timestamp.go deleted file mode 100644 index 9aa9702dad..0000000000 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ /dev/null @@ -1,124 +0,0 @@ -package time - -import ( - "fmt" - "math" - "strconv" - "strings" - "time" -) - -// These are additional predefined layouts for use in Time.Format and Time.Parse -// with --since and --until parameters for `docker logs` and `docker events` -const ( - rFC3339Local = "2006-01-02T15:04:05" // RFC3339 with local timezone - rFC3339NanoLocal = "2006-01-02T15:04:05.999999999" // RFC3339Nano with local timezone - dateWithZone = "2006-01-02Z07:00" // RFC3339 with time at 00:00:00 - dateLocal = "2006-01-02" // RFC3339 with local timezone and time at 00:00:00 -) - -// GetTimestamp tries to parse given string as golang duration, -// then RFC3339 time and finally as a Unix timestamp. If -// any of these were successful, it returns a Unix timestamp -// as string otherwise returns the given value back. -// In case of duration input, the returned timestamp is computed -// as the given reference time minus the amount of the duration. -func GetTimestamp(value string, reference time.Time) (string, error) { - if d, err := time.ParseDuration(value); value != "0" && err == nil { - return strconv.FormatInt(reference.Add(-d).Unix(), 10), nil - } - - var format string - var parseInLocation bool - - // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation - parseInLocation = !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) - - if strings.Contains(value, ".") { - if parseInLocation { - format = rFC3339NanoLocal - } else { - format = time.RFC3339Nano - } - } else if strings.Contains(value, "T") { - // we want the number of colons in the T portion of the timestamp - tcolons := strings.Count(value, ":") - // if parseInLocation is off and we have a +/- zone offset (not Z) then - // there will be an extra colon in the input for the tz offset subtract that - // colon from the tcolons count - if !parseInLocation && !strings.ContainsAny(value, "zZ") && tcolons > 0 { - tcolons-- - } - if parseInLocation { - switch tcolons { - case 0: - format = "2006-01-02T15" - case 1: - format = "2006-01-02T15:04" - default: - format = rFC3339Local - } - } else { - switch tcolons { - case 0: - format = "2006-01-02T15Z07:00" - case 1: - format = "2006-01-02T15:04Z07:00" - default: - format = time.RFC3339 - } - } - } else if parseInLocation { - format = dateLocal - } else { - format = dateWithZone - } - - var t time.Time - var err error - - if parseInLocation { - t, err = time.ParseInLocation(format, value, time.FixedZone(reference.Zone())) - } else { - t, err = time.Parse(format, value) - } - - if err != nil { - // if there is a `-` then it's an RFC3339 like timestamp otherwise assume unixtimestamp - if strings.Contains(value, "-") { - return "", err // was probably an RFC3339 like timestamp but the parser failed with an error - } - return value, nil // unixtimestamp in and out case (meaning: the value passed at the command line is already in the right format for passing to the server) - } - - return fmt.Sprintf("%d.%09d", t.Unix(), int64(t.Nanosecond())), nil -} - -// ParseTimestamps returns seconds and nanoseconds from a timestamp that has the -// format "%d.%09d", time.Unix(), int64(time.Nanosecond())) -// if the incoming nanosecond portion is longer or shorter than 9 digits it is -// converted to nanoseconds. The expectation is that the seconds and -// seconds will be used to create a time variable. For example: -// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) -// if err == nil since := time.Unix(seconds, nanoseconds) -// returns seconds as def(aultSeconds) if value == "" -func ParseTimestamps(value string, def int64) (int64, int64, error) { - if value == "" { - return def, 0, nil - } - sa := strings.SplitN(value, ".", 2) - s, err := strconv.ParseInt(sa[0], 10, 64) - if err != nil { - return s, 0, err - } - if len(sa) != 2 { - return s, 0, nil - } - n, err := strconv.ParseInt(sa[1], 10, 64) - if err != nil { - return s, n, err - } - // should already be in nanoseconds but just in case convert n to nanoseconds - n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) - return s, n, nil -} diff --git a/vendor/github.com/docker/docker/api/types/types.go b/vendor/github.com/docker/docker/api/types/types.go deleted file mode 100644 index bbaf2c5531..0000000000 --- a/vendor/github.com/docker/docker/api/types/types.go +++ /dev/null @@ -1,530 +0,0 @@ -package types - -import ( - "errors" - "fmt" - "io" - "os" - "strings" - "time" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/mount" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - "github.com/docker/go-connections/nat" -) - -// RootFS returns Image's RootFS description including the layer IDs. -type RootFS struct { - Type string - Layers []string `json:",omitempty"` - BaseLayer string `json:",omitempty"` -} - -// ImageInspect contains response of Engine API: -// GET "/images/{name:.*}/json" -type ImageInspect struct { - ID string `json:"Id"` - RepoTags []string - RepoDigests []string - Parent string - Comment string - Created string - Container string - ContainerConfig *container.Config - DockerVersion string - Author string - Config *container.Config - Architecture string - Os string - OsVersion string `json:",omitempty"` - Size int64 - VirtualSize int64 - GraphDriver GraphDriverData - RootFS RootFS -} - -// Container contains response of Engine API: -// GET "/containers/json" -type Container struct { - ID string `json:"Id"` - Names []string - Image string - ImageID string - Command string - Created int64 - Ports []Port - SizeRw int64 `json:",omitempty"` - SizeRootFs int64 `json:",omitempty"` - Labels map[string]string - State string - Status string - HostConfig struct { - NetworkMode string `json:",omitempty"` - } - NetworkSettings *SummaryNetworkSettings - Mounts []MountPoint -} - -// CopyConfig contains request body of Engine API: -// POST "/containers/"+containerID+"/copy" -type CopyConfig struct { - Resource string -} - -// ContainerPathStat is used to encode the header from -// GET "/containers/{name:.*}/archive" -// "Name" is the file or directory name. -type ContainerPathStat struct { - Name string `json:"name"` - Size int64 `json:"size"` - Mode os.FileMode `json:"mode"` - Mtime time.Time `json:"mtime"` - LinkTarget string `json:"linkTarget"` -} - -// ContainerStats contains response of Engine API: -// GET "/stats" -type ContainerStats struct { - Body io.ReadCloser `json:"body"` - OSType string `json:"ostype"` -} - -// Ping contains response of Engine API: -// GET "/_ping" -type Ping struct { - APIVersion string - OSType string - Experimental bool -} - -// Version contains response of Engine API: -// GET "/version" -type Version struct { - Version string - APIVersion string `json:"ApiVersion"` - MinAPIVersion string `json:"MinAPIVersion,omitempty"` - GitCommit string - GoVersion string - Os string - Arch string - KernelVersion string `json:",omitempty"` - Experimental bool `json:",omitempty"` - BuildTime string `json:",omitempty"` -} - -// Commit holds the Git-commit (SHA1) that a binary was built from, as reported -// in the version-string of external tools, such as containerd, or runC. -type Commit struct { - ID string // ID is the actual commit ID of external tool. - Expected string // Expected is the commit ID of external tool expected by dockerd as set at build time. -} - -// Info contains response of Engine API: -// GET "/info" -type Info struct { - ID string - Containers int - ContainersRunning int - ContainersPaused int - ContainersStopped int - Images int - Driver string - DriverStatus [][2]string - SystemStatus [][2]string - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool - CPUCfsPeriod bool `json:"CpuCfsPeriod"` - CPUCfsQuota bool `json:"CpuCfsQuota"` - CPUShares bool - CPUSet bool - IPv4Forwarding bool - BridgeNfIptables bool - BridgeNfIP6tables bool `json:"BridgeNfIp6tables"` - Debug bool - NFd int - OomKillDisable bool - NGoroutines int - SystemTime string - LoggingDriver string - CgroupDriver string - NEventsListener int - KernelVersion string - OperatingSystem string - OSType string - Architecture string - IndexServerAddress string - RegistryConfig *registry.ServiceConfig - NCPU int - MemTotal int64 - DockerRootDir string - HTTPProxy string `json:"HttpProxy"` - HTTPSProxy string `json:"HttpsProxy"` - NoProxy string - Name string - Labels []string - ExperimentalBuild bool - ServerVersion string - ClusterStore string - ClusterAdvertise string - Runtimes map[string]Runtime - DefaultRuntime string - Swarm swarm.Info - // LiveRestoreEnabled determines whether containers should be kept - // running when the daemon is shutdown or upon daemon start if - // running containers are detected - LiveRestoreEnabled bool - Isolation container.Isolation - InitBinary string - ContainerdCommit Commit - RuncCommit Commit - InitCommit Commit - SecurityOptions []string -} - -// KeyValue holds a key/value pair -type KeyValue struct { - Key, Value string -} - -// SecurityOpt contains the name and options of a security option -type SecurityOpt struct { - Name string - Options []KeyValue -} - -// DecodeSecurityOptions decodes a security options string slice to a type safe -// SecurityOpt -func DecodeSecurityOptions(opts []string) ([]SecurityOpt, error) { - so := []SecurityOpt{} - for _, opt := range opts { - // support output from a < 1.13 docker daemon - if !strings.Contains(opt, "=") { - so = append(so, SecurityOpt{Name: opt}) - continue - } - secopt := SecurityOpt{} - split := strings.Split(opt, ",") - for _, s := range split { - kv := strings.SplitN(s, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("invalid security option %q", s) - } - if kv[0] == "" || kv[1] == "" { - return nil, errors.New("invalid empty security option") - } - if kv[0] == "name" { - secopt.Name = kv[1] - continue - } - secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) - } - so = append(so, secopt) - } - return so, nil -} - -// PluginsInfo is a temp struct holding Plugins name -// registered with docker daemon. It is used by Info struct -type PluginsInfo struct { - // List of Volume plugins registered - Volume []string - // List of Network plugins registered - Network []string - // List of Authorization plugins registered - Authorization []string -} - -// ExecStartCheck is a temp struct used by execStart -// Config fields is part of ExecConfig in runconfig package -type ExecStartCheck struct { - // ExecStart will first check if it's detached - Detach bool - // Check if there's a tty - Tty bool -} - -// HealthcheckResult stores information about a single run of a healthcheck probe -type HealthcheckResult struct { - Start time.Time // Start is the time this check started - End time.Time // End is the time this check ended - ExitCode int // ExitCode meanings: 0=healthy, 1=unhealthy, 2=reserved (considered unhealthy), else=error running probe - Output string // Output from last check -} - -// Health states -const ( - NoHealthcheck = "none" // Indicates there is no healthcheck - Starting = "starting" // Starting indicates that the container is not yet ready - Healthy = "healthy" // Healthy indicates that the container is running correctly - Unhealthy = "unhealthy" // Unhealthy indicates that the container has a problem -) - -// Health stores information about the container's healthcheck results -type Health struct { - Status string // Status is one of Starting, Healthy or Unhealthy - FailingStreak int // FailingStreak is the number of consecutive failures - Log []*HealthcheckResult // Log contains the last few results (oldest first) -} - -// ContainerState stores container's running state -// it's part of ContainerJSONBase and will return by "inspect" command -type ContainerState struct { - Status string - Running bool - Paused bool - Restarting bool - OOMKilled bool - Dead bool - Pid int - ExitCode int - Error string - StartedAt string - FinishedAt string - Health *Health `json:",omitempty"` -} - -// ContainerNode stores information about the node that a container -// is running on. It's only available in Docker Swarm -type ContainerNode struct { - ID string - IPAddress string `json:"IP"` - Addr string - Name string - Cpus int - Memory int64 - Labels map[string]string -} - -// ContainerJSONBase contains response of Engine API: -// GET "/containers/{name:.*}/json" -type ContainerJSONBase struct { - ID string `json:"Id"` - Created string - Path string - Args []string - State *ContainerState - Image string - ResolvConfPath string - HostnamePath string - HostsPath string - LogPath string - Node *ContainerNode `json:",omitempty"` - Name string - RestartCount int - Driver string - MountLabel string - ProcessLabel string - AppArmorProfile string - ExecIDs []string - HostConfig *container.HostConfig - GraphDriver GraphDriverData - SizeRw *int64 `json:",omitempty"` - SizeRootFs *int64 `json:",omitempty"` -} - -// ContainerJSON is newly used struct along with MountPoint -type ContainerJSON struct { - *ContainerJSONBase - Mounts []MountPoint - Config *container.Config - NetworkSettings *NetworkSettings -} - -// NetworkSettings exposes the network settings in the api -type NetworkSettings struct { - NetworkSettingsBase - DefaultNetworkSettings - Networks map[string]*network.EndpointSettings -} - -// SummaryNetworkSettings provides a summary of container's networks -// in /containers/json -type SummaryNetworkSettings struct { - Networks map[string]*network.EndpointSettings -} - -// NetworkSettingsBase holds basic information about networks -type NetworkSettingsBase struct { - Bridge string // Bridge is the Bridge name the network uses(e.g. `docker0`) - SandboxID string // SandboxID uniquely represents a container's network stack - HairpinMode bool // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface - LinkLocalIPv6Address string // LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix - LinkLocalIPv6PrefixLen int // LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address - Ports nat.PortMap // Ports is a collection of PortBinding indexed by Port - SandboxKey string // SandboxKey identifies the sandbox - SecondaryIPAddresses []network.Address - SecondaryIPv6Addresses []network.Address -} - -// DefaultNetworkSettings holds network information -// during the 2 release deprecation period. -// It will be removed in Docker 1.11. -type DefaultNetworkSettings struct { - EndpointID string // EndpointID uniquely represents a service endpoint in a Sandbox - Gateway string // Gateway holds the gateway address for the network - GlobalIPv6Address string // GlobalIPv6Address holds network's global IPv6 address - GlobalIPv6PrefixLen int // GlobalIPv6PrefixLen represents mask length of network's global IPv6 address - IPAddress string // IPAddress holds the IPv4 address for the network - IPPrefixLen int // IPPrefixLen represents mask length of network's IPv4 address - IPv6Gateway string // IPv6Gateway holds gateway address specific for IPv6 - MacAddress string // MacAddress holds the MAC address for the network -} - -// MountPoint represents a mount point configuration inside the container. -// This is used for reporting the mountpoints in use by a container. -type MountPoint struct { - Type mount.Type `json:",omitempty"` - Name string `json:",omitempty"` - Source string - Destination string - Driver string `json:",omitempty"` - Mode string - RW bool - Propagation mount.Propagation -} - -// NetworkResource is the body of the "get network" http response message -type NetworkResource struct { - Name string // Name is the requested name of the network - ID string `json:"Id"` // ID uniquely identifies a network on a single machine - Created time.Time // Created is the time the network created - Scope string // Scope describes the level at which the network exists (e.g. `global` for cluster-wide or `local` for machine level) - Driver string // Driver is the Driver name used to create the network (e.g. `bridge`, `overlay`) - EnableIPv6 bool // EnableIPv6 represents whether to enable IPv6 - IPAM network.IPAM // IPAM is the network's IP Address Management - Internal bool // Internal represents if the network is used internal only - Attachable bool // Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode. - Ingress bool // Ingress indicates the network is providing the routing-mesh for the swarm cluster. - Containers map[string]EndpointResource // Containers contains endpoints belonging to the network - Options map[string]string // Options holds the network specific options to use for when creating the network - Labels map[string]string // Labels holds metadata specific to the network being created - Peers []network.PeerInfo `json:",omitempty"` // List of peer nodes for an overlay network - Services map[string]network.ServiceInfo `json:",omitempty"` -} - -// EndpointResource contains network resources allocated and used for a container in a network -type EndpointResource struct { - Name string - EndpointID string - MacAddress string - IPv4Address string - IPv6Address string -} - -// NetworkCreate is the expected body of the "create network" http request message -type NetworkCreate struct { - // Check for networks with duplicate names. - // Network is primarily keyed based on a random ID and not on the name. - // Network name is strictly a user-friendly alias to the network - // which is uniquely identified using ID. - // And there is no guaranteed way to check for duplicates. - // Option CheckDuplicate is there to provide a best effort checking of any networks - // which has the same name but it is not guaranteed to catch all name collisions. - CheckDuplicate bool - Driver string - EnableIPv6 bool - IPAM *network.IPAM - Internal bool - Attachable bool - Ingress bool - Options map[string]string - Labels map[string]string -} - -// NetworkCreateRequest is the request message sent to the server for network create call. -type NetworkCreateRequest struct { - NetworkCreate - Name string -} - -// NetworkCreateResponse is the response message sent by the server for network create call -type NetworkCreateResponse struct { - ID string `json:"Id"` - Warning string -} - -// NetworkConnect represents the data to be used to connect a container to the network -type NetworkConnect struct { - Container string - EndpointConfig *network.EndpointSettings `json:",omitempty"` -} - -// NetworkDisconnect represents the data to be used to disconnect a container from the network -type NetworkDisconnect struct { - Container string - Force bool -} - -// Checkpoint represents the details of a checkpoint -type Checkpoint struct { - Name string // Name is the name of the checkpoint -} - -// Runtime describes an OCI runtime -type Runtime struct { - Path string `json:"path"` - Args []string `json:"runtimeArgs,omitempty"` -} - -// DiskUsage contains response of Engine API: -// GET "/system/df" -type DiskUsage struct { - LayersSize int64 - Images []*ImageSummary - Containers []*Container - Volumes []*Volume -} - -// ContainersPruneReport contains the response for Engine API: -// POST "/containers/prune" -type ContainersPruneReport struct { - ContainersDeleted []string - SpaceReclaimed uint64 -} - -// VolumesPruneReport contains the response for Engine API: -// POST "/volumes/prune" -type VolumesPruneReport struct { - VolumesDeleted []string - SpaceReclaimed uint64 -} - -// ImagesPruneReport contains the response for Engine API: -// POST "/images/prune" -type ImagesPruneReport struct { - ImagesDeleted []ImageDeleteResponseItem - SpaceReclaimed uint64 -} - -// NetworksPruneReport contains the response for Engine API: -// POST "/networks/prune" -type NetworksPruneReport struct { - NetworksDeleted []string -} - -// SecretCreateResponse contains the information returned to a client -// on the creation of a new secret. -type SecretCreateResponse struct { - // ID is the id of the created secret. - ID string -} - -// SecretListOptions holds parameters to list secrets -type SecretListOptions struct { - Filters filters.Args -} - -// PushResult contains the tag, manifest digest, and manifest size from the -// push. It's used to signal this information to the trust code in the client -// so it can sign the manifest if necessary. -type PushResult struct { - Tag string - Digest string - Size int -} diff --git a/vendor/github.com/docker/docker/api/types/versions/README.md b/vendor/github.com/docker/docker/api/types/versions/README.md deleted file mode 100644 index 1ef911edb0..0000000000 --- a/vendor/github.com/docker/docker/api/types/versions/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# Legacy API type versions - -This package includes types for legacy API versions. The stable version of the API types live in `api/types/*.go`. - -Consider moving a type here when you need to keep backwards compatibility in the API. This legacy types are organized by the latest API version they appear in. For instance, types in the `v1p19` package are valid for API versions below or equal `1.19`. Types in the `v1p20` package are valid for the API version `1.20`, since the versions below that will use the legacy types in `v1p19`. - -## Package name conventions - -The package name convention is to use `v` as a prefix for the version number and `p`(patch) as a separator. We use this nomenclature due to a few restrictions in the Go package name convention: - -1. We cannot use `.` because it's interpreted by the language, think of `v1.20.CallFunction`. -2. We cannot use `_` because golint complains about it. The code is actually valid, but it looks probably more weird: `v1_20.CallFunction`. - -For instance, if you want to modify a type that was available in the version `1.21` of the API but it will have different fields in the version `1.22`, you want to create a new package under `api/types/versions/v1p21`. diff --git a/vendor/github.com/docker/docker/api/types/versions/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go deleted file mode 100644 index 611d4fed66..0000000000 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ /dev/null @@ -1,62 +0,0 @@ -package versions - -import ( - "strconv" - "strings" -) - -// compare compares two version strings -// returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise. -func compare(v1, v2 string) int { - var ( - currTab = strings.Split(v1, ".") - otherTab = strings.Split(v2, ".") - ) - - max := len(currTab) - if len(otherTab) > max { - max = len(otherTab) - } - for i := 0; i < max; i++ { - var currInt, otherInt int - - if len(currTab) > i { - currInt, _ = strconv.Atoi(currTab[i]) - } - if len(otherTab) > i { - otherInt, _ = strconv.Atoi(otherTab[i]) - } - if currInt > otherInt { - return 1 - } - if otherInt > currInt { - return -1 - } - } - return 0 -} - -// LessThan checks if a version is less than another -func LessThan(v, other string) bool { - return compare(v, other) == -1 -} - -// LessThanOrEqualTo checks if a version is less than or equal to another -func LessThanOrEqualTo(v, other string) bool { - return compare(v, other) <= 0 -} - -// GreaterThan checks if a version is greater than another -func GreaterThan(v, other string) bool { - return compare(v, other) == 1 -} - -// GreaterThanOrEqualTo checks if a version is greater than or equal to another -func GreaterThanOrEqualTo(v, other string) bool { - return compare(v, other) >= 0 -} - -// Equal checks if a version is equal to another -func Equal(v, other string) bool { - return compare(v, other) == 0 -} diff --git a/vendor/github.com/docker/docker/api/types/volume.go b/vendor/github.com/docker/docker/api/types/volume.go deleted file mode 100644 index da4f8ebd9c..0000000000 --- a/vendor/github.com/docker/docker/api/types/volume.go +++ /dev/null @@ -1,58 +0,0 @@ -package types - -// This file was generated by the swagger tool. -// Editing this file might prove futile when you re-run the swagger generate command - -// Volume volume -// swagger:model Volume -type Volume struct { - - // Name of the volume driver used by the volume. - // Required: true - Driver string `json:"Driver"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // Mount path of the volume on the host. - // Required: true - Mountpoint string `json:"Mountpoint"` - - // Name of the volume. - // Required: true - Name string `json:"Name"` - - // The driver specific options used when creating the volume. - // Required: true - Options map[string]string `json:"Options"` - - // The level at which the volume exists. Either `global` for cluster-wide, or `local` for machine level. - // Required: true - Scope string `json:"Scope"` - - // Low-level details about the volume, provided by the volume driver. - // Details are returned as a map with key/value pairs: - // `{"key":"value","key2":"value2"}`. - // - // The `Status` field is optional, and is omitted if the volume driver - // does not support this feature. - // - Status map[string]interface{} `json:"Status,omitempty"` - - // usage data - UsageData *VolumeUsageData `json:"UsageData,omitempty"` -} - -// VolumeUsageData volume usage data -// swagger:model VolumeUsageData -type VolumeUsageData struct { - - // The number of containers referencing this volume. - // Required: true - RefCount int64 `json:"RefCount"` - - // The disk space used by the volume (local driver only) - // Required: true - Size int64 `json:"Size"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volumes_create.go b/vendor/github.com/docker/docker/api/types/volume/volumes_create.go deleted file mode 100644 index 9f70e43ca4..0000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volumes_create.go +++ /dev/null @@ -1,29 +0,0 @@ -package volume - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// VolumesCreateBody volumes create body -// swagger:model VolumesCreateBody -type VolumesCreateBody struct { - - // Name of the volume driver to use. - // Required: true - Driver string `json:"Driver"` - - // A mapping of driver options and values. These options are passed directly to the driver and are driver specific. - // Required: true - DriverOpts map[string]string `json:"DriverOpts"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // The new volume's name. If not specified, Docker generates a name. - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volumes_list.go b/vendor/github.com/docker/docker/api/types/volume/volumes_list.go deleted file mode 100644 index 833dad9330..0000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volumes_list.go +++ /dev/null @@ -1,23 +0,0 @@ -package volume - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -import "github.com/docker/docker/api/types" - -// VolumesListOKBody volumes list o k body -// swagger:model VolumesListOKBody -type VolumesListOKBody struct { - - // List of volumes - // Required: true - Volumes []*types.Volume `json:"Volumes"` - - // Warnings that occurred when fetching the list of volumes - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/client/README.md b/vendor/github.com/docker/docker/client/README.md deleted file mode 100644 index 059dfb3ce7..0000000000 --- a/vendor/github.com/docker/docker/client/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Go client for the Docker Engine API - -The `docker` command uses this package to communicate with the daemon. It can also be used by your own Go applications to do anything the command-line interface does – running containers, pulling images, managing swarms, etc. - -For example, to list running containers (the equivalent of `docker ps`): - -```go -package main - -import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" -) - -func main() { - cli, err := client.NewEnvClient() - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } -} -``` - -[Full documentation is available on GoDoc.](https://godoc.org/github.com/docker/docker/client) diff --git a/vendor/github.com/docker/docker/client/checkpoint_create.go b/vendor/github.com/docker/docker/client/checkpoint_create.go deleted file mode 100644 index 0effe498be..0000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_create.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// CheckpointCreate creates a checkpoint from the given container with the given name -func (cli *Client) CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error { - resp, err := cli.post(ctx, "/containers/"+container+"/checkpoints", nil, options, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_delete.go b/vendor/github.com/docker/docker/client/checkpoint_delete.go deleted file mode 100644 index e6e75588b1..0000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_delete.go +++ /dev/null @@ -1,20 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// CheckpointDelete deletes the checkpoint with the given name from the given container -func (cli *Client) CheckpointDelete(ctx context.Context, containerID string, options types.CheckpointDeleteOptions) error { - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.delete(ctx, "/containers/"+containerID+"/checkpoints/"+options.CheckpointID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/checkpoint_list.go b/vendor/github.com/docker/docker/client/checkpoint_list.go deleted file mode 100644 index ffe44bc976..0000000000 --- a/vendor/github.com/docker/docker/client/checkpoint_list.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "encoding/json" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// CheckpointList returns the checkpoints of the given container in the docker host -func (cli *Client) CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) { - var checkpoints []types.Checkpoint - - query := url.Values{} - if options.CheckpointDir != "" { - query.Set("dir", options.CheckpointDir) - } - - resp, err := cli.get(ctx, "/containers/"+container+"/checkpoints", query, nil) - if err != nil { - if resp.statusCode == http.StatusNotFound { - return checkpoints, containerNotFoundError{container} - } - return checkpoints, err - } - - err = json.NewDecoder(resp.body).Decode(&checkpoints) - ensureReaderClosed(resp) - return checkpoints, err -} diff --git a/vendor/github.com/docker/docker/client/client.go b/vendor/github.com/docker/docker/client/client.go deleted file mode 100644 index df3698adc6..0000000000 --- a/vendor/github.com/docker/docker/client/client.go +++ /dev/null @@ -1,261 +0,0 @@ -/* -Package client is a Go client for the Docker Engine API. - -The "docker" command uses this package to communicate with the daemon. It can also -be used by your own Go applications to do anything the command-line interface does -- running containers, pulling images, managing swarms, etc. - -For more information about the Engine API, see the documentation: -https://docs.docker.com/engine/reference/api/ - -Usage - -You use the library by creating a client object and calling methods on it. The -client can be created either from environment variables with NewEnvClient, or -configured manually with NewClient. - -For example, to list running containers (the equivalent of "docker ps"): - - package main - - import ( - "context" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - ) - - func main() { - cli, err := client.NewEnvClient() - if err != nil { - panic(err) - } - - containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{}) - if err != nil { - panic(err) - } - - for _, container := range containers { - fmt.Printf("%s %s\n", container.ID[:10], container.Image) - } - } - -*/ -package client - -import ( - "fmt" - "net/http" - "net/url" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/api" - "github.com/docker/go-connections/sockets" - "github.com/docker/go-connections/tlsconfig" -) - -// Client is the API client that performs all operations -// against a docker server. -type Client struct { - // scheme sets the scheme for the client - scheme string - // host holds the server address to connect to - host string - // proto holds the client protocol i.e. unix. - proto string - // addr holds the client address. - addr string - // basePath holds the path to prepend to the requests. - basePath string - // client used to send and receive http requests. - client *http.Client - // version of the server to talk to. - version string - // custom http headers configured by users. - customHTTPHeaders map[string]string - // manualOverride is set to true when the version was set by users. - manualOverride bool -} - -// NewEnvClient initializes a new API client based on environment variables. -// Use DOCKER_HOST to set the url to the docker server. -// Use DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest. -// Use DOCKER_CERT_PATH to load the TLS certificates from. -// Use DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default. -func NewEnvClient() (*Client, error) { - var client *http.Client - if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" { - options := tlsconfig.Options{ - CAFile: filepath.Join(dockerCertPath, "ca.pem"), - CertFile: filepath.Join(dockerCertPath, "cert.pem"), - KeyFile: filepath.Join(dockerCertPath, "key.pem"), - InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "", - } - tlsc, err := tlsconfig.Client(options) - if err != nil { - return nil, err - } - - client = &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: tlsc, - }, - } - } - - host := os.Getenv("DOCKER_HOST") - if host == "" { - host = DefaultDockerHost - } - version := os.Getenv("DOCKER_API_VERSION") - if version == "" { - version = api.DefaultVersion - } - - cli, err := NewClient(host, version, client, nil) - if err != nil { - return cli, err - } - if os.Getenv("DOCKER_API_VERSION") != "" { - cli.manualOverride = true - } - return cli, nil -} - -// NewClient initializes a new API client for the given host and API version. -// It uses the given http client as transport. -// It also initializes the custom http headers to add to each request. -// -// It won't send any version information if the version number is empty. It is -// highly recommended that you set a version or your client may break if the -// server is upgraded. -func NewClient(host string, version string, client *http.Client, httpHeaders map[string]string) (*Client, error) { - proto, addr, basePath, err := ParseHost(host) - if err != nil { - return nil, err - } - - if client != nil { - if _, ok := client.Transport.(*http.Transport); !ok { - return nil, fmt.Errorf("unable to verify TLS configuration, invalid transport %v", client.Transport) - } - } else { - transport := new(http.Transport) - sockets.ConfigureTransport(transport, proto, addr) - client = &http.Client{ - Transport: transport, - } - } - - scheme := "http" - tlsConfig := resolveTLSConfig(client.Transport) - if tlsConfig != nil { - // TODO(stevvooe): This isn't really the right way to write clients in Go. - // `NewClient` should probably only take an `*http.Client` and work from there. - // Unfortunately, the model of having a host-ish/url-thingy as the connection - // string has us confusing protocol and transport layers. We continue doing - // this to avoid breaking existing clients but this should be addressed. - scheme = "https" - } - - return &Client{ - scheme: scheme, - host: host, - proto: proto, - addr: addr, - basePath: basePath, - client: client, - version: version, - customHTTPHeaders: httpHeaders, - }, nil -} - -// Close ensures that transport.Client is closed -// especially needed while using NewClient with *http.Client = nil -// for example -// client.NewClient("unix:///var/run/docker.sock", nil, "v1.18", map[string]string{"User-Agent": "engine-api-cli-1.0"}) -func (cli *Client) Close() error { - - if t, ok := cli.client.Transport.(*http.Transport); ok { - t.CloseIdleConnections() - } - - return nil -} - -// getAPIPath returns the versioned request path to call the api. -// It appends the query parameters to the path if they are not empty. -func (cli *Client) getAPIPath(p string, query url.Values) string { - var apiPath string - if cli.version != "" { - v := strings.TrimPrefix(cli.version, "v") - apiPath = fmt.Sprintf("%s/v%s%s", cli.basePath, v, p) - } else { - apiPath = fmt.Sprintf("%s%s", cli.basePath, p) - } - - u := &url.URL{ - Path: apiPath, - } - if len(query) > 0 { - u.RawQuery = query.Encode() - } - return u.String() -} - -// ClientVersion returns the version string associated with this -// instance of the Client. Note that this value can be changed -// via the DOCKER_API_VERSION env var. -// This operation doesn't acquire a mutex. -func (cli *Client) ClientVersion() string { - return cli.version -} - -// UpdateClientVersion updates the version string associated with this -// instance of the Client. This operation doesn't acquire a mutex. -func (cli *Client) UpdateClientVersion(v string) { - if !cli.manualOverride { - cli.version = v - } - -} - -// ParseHost verifies that the given host strings is valid. -func ParseHost(host string) (string, string, string, error) { - protoAddrParts := strings.SplitN(host, "://", 2) - if len(protoAddrParts) == 1 { - return "", "", "", fmt.Errorf("unable to parse docker host `%s`", host) - } - - var basePath string - proto, addr := protoAddrParts[0], protoAddrParts[1] - if proto == "tcp" { - parsed, err := url.Parse("tcp://" + addr) - if err != nil { - return "", "", "", err - } - addr = parsed.Host - basePath = parsed.Path - } - return proto, addr, basePath, nil -} - -// CustomHTTPHeaders returns the custom http headers associated with this -// instance of the Client. This operation doesn't acquire a mutex. -func (cli *Client) CustomHTTPHeaders() map[string]string { - m := make(map[string]string) - for k, v := range cli.customHTTPHeaders { - m[k] = v - } - return m -} - -// SetCustomHTTPHeaders updates the custom http headers associated with this -// instance of the Client. This operation doesn't acquire a mutex. -func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) { - cli.customHTTPHeaders = headers -} diff --git a/vendor/github.com/docker/docker/client/client_unix.go b/vendor/github.com/docker/docker/client/client_unix.go deleted file mode 100644 index 89de892c85..0000000000 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build linux freebsd solaris openbsd darwin - -package client - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "unix:///var/run/docker.sock" diff --git a/vendor/github.com/docker/docker/client/client_windows.go b/vendor/github.com/docker/docker/client/client_windows.go deleted file mode 100644 index 07c0c7a774..0000000000 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ /dev/null @@ -1,4 +0,0 @@ -package client - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "npipe:////./pipe/docker_engine" diff --git a/vendor/github.com/docker/docker/client/container_attach.go b/vendor/github.com/docker/docker/client/container_attach.go deleted file mode 100644 index eea4682158..0000000000 --- a/vendor/github.com/docker/docker/client/container_attach.go +++ /dev/null @@ -1,37 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerAttach attaches a connection to a container in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -func (cli *Client) ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) { - query := url.Values{} - if options.Stream { - query.Set("stream", "1") - } - if options.Stdin { - query.Set("stdin", "1") - } - if options.Stdout { - query.Set("stdout", "1") - } - if options.Stderr { - query.Set("stderr", "1") - } - if options.DetachKeys != "" { - query.Set("detachKeys", options.DetachKeys) - } - if options.Logs { - query.Set("logs", "1") - } - - headers := map[string][]string{"Content-Type": {"text/plain"}} - return cli.postHijacked(ctx, "/containers/"+container+"/attach", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/container_commit.go b/vendor/github.com/docker/docker/client/container_commit.go deleted file mode 100644 index 531d796ee7..0000000000 --- a/vendor/github.com/docker/docker/client/container_commit.go +++ /dev/null @@ -1,55 +0,0 @@ -package client - -import ( - "encoding/json" - "errors" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerCommit applies changes into a container and creates a new tagged image. -func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) { - var repository, tag string - if options.Reference != "" { - ref, err := reference.ParseNormalizedNamed(options.Reference) - if err != nil { - return types.IDResponse{}, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference") - } - ref = reference.TagNameOnly(ref) - - if tagged, ok := ref.(reference.Tagged); ok { - tag = tagged.Tag() - } - repository = reference.FamiliarName(ref) - } - - query := url.Values{} - query.Set("container", container) - query.Set("repo", repository) - query.Set("tag", tag) - query.Set("comment", options.Comment) - query.Set("author", options.Author) - for _, change := range options.Changes { - query.Add("changes", change) - } - if options.Pause != true { - query.Set("pause", "0") - } - - var response types.IDResponse - resp, err := cli.post(ctx, "/commit", query, options.Config, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_copy.go b/vendor/github.com/docker/docker/client/container_copy.go deleted file mode 100644 index 545aa54383..0000000000 --- a/vendor/github.com/docker/docker/client/container_copy.go +++ /dev/null @@ -1,101 +0,0 @@ -package client - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path/filepath" - "strings" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" -) - -// ContainerStatPath returns Stat information about a path inside the container filesystem. -func (cli *Client) ContainerStatPath(ctx context.Context, containerID, path string) (types.ContainerPathStat, error) { - query := url.Values{} - query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. - - urlStr := fmt.Sprintf("/containers/%s/archive", containerID) - response, err := cli.head(ctx, urlStr, query, nil) - if err != nil { - return types.ContainerPathStat{}, err - } - defer ensureReaderClosed(response) - return getContainerPathStatFromHeader(response.header) -} - -// CopyToContainer copies content into the container filesystem. -func (cli *Client) CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error { - query := url.Values{} - query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. - // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. - if !options.AllowOverwriteDirWithFile { - query.Set("noOverwriteDirNonDir", "true") - } - - if options.CopyUIDGID { - query.Set("copyUIDGID", "true") - } - - apiPath := fmt.Sprintf("/containers/%s/archive", container) - - response, err := cli.putRaw(ctx, apiPath, query, content, nil) - if err != nil { - return err - } - defer ensureReaderClosed(response) - - if response.statusCode != http.StatusOK { - return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - return nil -} - -// CopyFromContainer gets the content from the container and returns it as a Reader -// to manipulate it in the host. It's up to the caller to close the reader. -func (cli *Client) CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - query := make(url.Values, 1) - query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. - - apiPath := fmt.Sprintf("/containers/%s/archive", container) - response, err := cli.get(ctx, apiPath, query, nil) - if err != nil { - return nil, types.ContainerPathStat{}, err - } - - if response.statusCode != http.StatusOK { - return nil, types.ContainerPathStat{}, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - // In order to get the copy behavior right, we need to know information - // about both the source and the destination. The response headers include - // stat info about the source that we can use in deciding exactly how to - // copy it locally. Along with the stat info about the local destination, - // we have everything we need to handle the multiple possibilities there - // can be when copying a file/dir from one location to another file/dir. - stat, err := getContainerPathStatFromHeader(response.header) - if err != nil { - return nil, stat, fmt.Errorf("unable to get resource stat from response: %s", err) - } - return response.body, stat, err -} - -func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { - var stat types.ContainerPathStat - - encodedStat := header.Get("X-Docker-Container-Path-Stat") - statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) - - err := json.NewDecoder(statDecoder).Decode(&stat) - if err != nil { - err = fmt.Errorf("unable to decode container path stat header: %s", err) - } - - return stat, err -} diff --git a/vendor/github.com/docker/docker/client/container_create.go b/vendor/github.com/docker/docker/client/container_create.go deleted file mode 100644 index 6841b0b282..0000000000 --- a/vendor/github.com/docker/docker/client/container_create.go +++ /dev/null @@ -1,56 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - "strings" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/versions" - "golang.org/x/net/context" -) - -type configWrapper struct { - *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig -} - -// ContainerCreate creates a new container based in the given configuration. -// It can be associated with a name, but it's not mandatory. -func (cli *Client) ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) { - var response container.ContainerCreateCreatedBody - - if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { - return response, err - } - - // When using API 1.24 and under, the client is responsible for removing the container - if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") { - hostConfig.AutoRemove = false - } - - query := url.Values{} - if containerName != "" { - query.Set("name", containerName) - } - - body := configWrapper{ - Config: config, - HostConfig: hostConfig, - NetworkingConfig: networkingConfig, - } - - serverResp, err := cli.post(ctx, "/containers/create", query, body, nil) - if err != nil { - if serverResp.statusCode == 404 && strings.Contains(err.Error(), "No such image") { - return response, imageNotFoundError{config.Image} - } - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_diff.go b/vendor/github.com/docker/docker/client/container_diff.go deleted file mode 100644 index 884dc9feef..0000000000 --- a/vendor/github.com/docker/docker/client/container_diff.go +++ /dev/null @@ -1,23 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" - "golang.org/x/net/context" -) - -// ContainerDiff shows differences in a container filesystem since it was started. -func (cli *Client) ContainerDiff(ctx context.Context, containerID string) ([]container.ContainerChangeResponseItem, error) { - var changes []container.ContainerChangeResponseItem - - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/changes", url.Values{}, nil) - if err != nil { - return changes, err - } - - err = json.NewDecoder(serverResp.body).Decode(&changes) - ensureReaderClosed(serverResp) - return changes, err -} diff --git a/vendor/github.com/docker/docker/client/container_exec.go b/vendor/github.com/docker/docker/client/container_exec.go deleted file mode 100644 index 0665c54fbd..0000000000 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerExecCreate creates a new exec configuration to run an exec process. -func (cli *Client) ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) { - var response types.IDResponse - - if err := cli.NewVersionError("1.25", "env"); len(config.Env) != 0 && err != nil { - return response, err - } - - resp, err := cli.post(ctx, "/containers/"+container+"/exec", nil, config, nil) - if err != nil { - return response, err - } - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} - -// ContainerExecStart starts an exec process already created in the docker host. -func (cli *Client) ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error { - resp, err := cli.post(ctx, "/exec/"+execID+"/start", nil, config, nil) - ensureReaderClosed(resp) - return err -} - -// ContainerExecAttach attaches a connection to an exec process in the server. -// It returns a types.HijackedConnection with the hijacked connection -// and the a reader to get output. It's up to the called to close -// the hijacked connection by calling types.HijackedResponse.Close. -func (cli *Client) ContainerExecAttach(ctx context.Context, execID string, config types.ExecConfig) (types.HijackedResponse, error) { - headers := map[string][]string{"Content-Type": {"application/json"}} - return cli.postHijacked(ctx, "/exec/"+execID+"/start", nil, config, headers) -} - -// ContainerExecInspect returns information about a specific exec process on the docker host. -func (cli *Client) ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) { - var response types.ContainerExecInspect - resp, err := cli.get(ctx, "/exec/"+execID+"/json", nil, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_export.go b/vendor/github.com/docker/docker/client/container_export.go deleted file mode 100644 index 52194f3d34..0000000000 --- a/vendor/github.com/docker/docker/client/container_export.go +++ /dev/null @@ -1,20 +0,0 @@ -package client - -import ( - "io" - "net/url" - - "golang.org/x/net/context" -) - -// ContainerExport retrieves the raw contents of a container -// and returns them as an io.ReadCloser. It's up to the caller -// to close the stream. -func (cli *Client) ContainerExport(ctx context.Context, containerID string) (io.ReadCloser, error) { - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/export", url.Values{}, nil) - if err != nil { - return nil, err - } - - return serverResp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_inspect.go b/vendor/github.com/docker/docker/client/container_inspect.go deleted file mode 100644 index 17f1809747..0000000000 --- a/vendor/github.com/docker/docker/client/container_inspect.go +++ /dev/null @@ -1,54 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerInspect returns the container information. -func (cli *Client) ContainerInspect(ctx context.Context, containerID string) (types.ContainerJSON, error) { - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", nil, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return types.ContainerJSON{}, containerNotFoundError{containerID} - } - return types.ContainerJSON{}, err - } - - var response types.ContainerJSON - err = json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} - -// ContainerInspectWithRaw returns the container information and its raw representation. -func (cli *Client) ContainerInspectWithRaw(ctx context.Context, containerID string, getSize bool) (types.ContainerJSON, []byte, error) { - query := url.Values{} - if getSize { - query.Set("size", "1") - } - serverResp, err := cli.get(ctx, "/containers/"+containerID+"/json", query, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return types.ContainerJSON{}, nil, containerNotFoundError{containerID} - } - return types.ContainerJSON{}, nil, err - } - defer ensureReaderClosed(serverResp) - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return types.ContainerJSON{}, nil, err - } - - var response types.ContainerJSON - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/container_kill.go b/vendor/github.com/docker/docker/client/container_kill.go deleted file mode 100644 index 29f80c73ad..0000000000 --- a/vendor/github.com/docker/docker/client/container_kill.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - "net/url" - - "golang.org/x/net/context" -) - -// ContainerKill terminates the container process but does not remove the container from the docker host. -func (cli *Client) ContainerKill(ctx context.Context, containerID, signal string) error { - query := url.Values{} - query.Set("signal", signal) - - resp, err := cli.post(ctx, "/containers/"+containerID+"/kill", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_list.go b/vendor/github.com/docker/docker/client/container_list.go deleted file mode 100644 index 4398912197..0000000000 --- a/vendor/github.com/docker/docker/client/container_list.go +++ /dev/null @@ -1,56 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// ContainerList returns the list of containers in the docker host. -func (cli *Client) ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) { - query := url.Values{} - - if options.All { - query.Set("all", "1") - } - - if options.Limit != -1 { - query.Set("limit", strconv.Itoa(options.Limit)) - } - - if options.Since != "" { - query.Set("since", options.Since) - } - - if options.Before != "" { - query.Set("before", options.Before) - } - - if options.Size { - query.Set("size", "1") - } - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/containers/json", query, nil) - if err != nil { - return nil, err - } - - var containers []types.Container - err = json.NewDecoder(resp.body).Decode(&containers) - ensureReaderClosed(resp) - return containers, err -} diff --git a/vendor/github.com/docker/docker/client/container_logs.go b/vendor/github.com/docker/docker/client/container_logs.go deleted file mode 100644 index 69056b6321..0000000000 --- a/vendor/github.com/docker/docker/client/container_logs.go +++ /dev/null @@ -1,52 +0,0 @@ -package client - -import ( - "io" - "net/url" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" -) - -// ContainerLogs returns the logs generated by a container in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/containers/"+container+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/container_pause.go b/vendor/github.com/docker/docker/client/container_pause.go deleted file mode 100644 index 412067a782..0000000000 --- a/vendor/github.com/docker/docker/client/container_pause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import "golang.org/x/net/context" - -// ContainerPause pauses the main process of a given container without terminating it. -func (cli *Client) ContainerPause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/pause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_prune.go b/vendor/github.com/docker/docker/client/container_prune.go deleted file mode 100644 index b582170867..0000000000 --- a/vendor/github.com/docker/docker/client/container_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// ContainersPrune requests the daemon to delete unused data -func (cli *Client) ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) { - var report types.ContainersPruneReport - - if err := cli.NewVersionError("1.25", "container prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/containers/prune", query, nil, nil) - if err != nil { - return report, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/container_remove.go b/vendor/github.com/docker/docker/client/container_remove.go deleted file mode 100644 index 3a79590ced..0000000000 --- a/vendor/github.com/docker/docker/client/container_remove.go +++ /dev/null @@ -1,27 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerRemove kills and removes a container from the docker host. -func (cli *Client) ContainerRemove(ctx context.Context, containerID string, options types.ContainerRemoveOptions) error { - query := url.Values{} - if options.RemoveVolumes { - query.Set("v", "1") - } - if options.RemoveLinks { - query.Set("link", "1") - } - - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/containers/"+containerID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_rename.go b/vendor/github.com/docker/docker/client/container_rename.go deleted file mode 100644 index 0e718da7c6..0000000000 --- a/vendor/github.com/docker/docker/client/container_rename.go +++ /dev/null @@ -1,16 +0,0 @@ -package client - -import ( - "net/url" - - "golang.org/x/net/context" -) - -// ContainerRename changes the name of a given container. -func (cli *Client) ContainerRename(ctx context.Context, containerID, newContainerName string) error { - query := url.Values{} - query.Set("name", newContainerName) - resp, err := cli.post(ctx, "/containers/"+containerID+"/rename", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_resize.go b/vendor/github.com/docker/docker/client/container_resize.go deleted file mode 100644 index 66c3cc1940..0000000000 --- a/vendor/github.com/docker/docker/client/container_resize.go +++ /dev/null @@ -1,29 +0,0 @@ -package client - -import ( - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerResize changes the size of the tty for a container. -func (cli *Client) ContainerResize(ctx context.Context, containerID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/containers/"+containerID, options.Height, options.Width) -} - -// ContainerExecResize changes the size of the tty for an exec process running inside a container. -func (cli *Client) ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error { - return cli.resize(ctx, "/exec/"+execID, options.Height, options.Width) -} - -func (cli *Client) resize(ctx context.Context, basePath string, height, width uint) error { - query := url.Values{} - query.Set("h", strconv.Itoa(int(height))) - query.Set("w", strconv.Itoa(int(width))) - - resp, err := cli.post(ctx, basePath+"/resize", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_restart.go b/vendor/github.com/docker/docker/client/container_restart.go deleted file mode 100644 index 74d7455f02..0000000000 --- a/vendor/github.com/docker/docker/client/container_restart.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" - "golang.org/x/net/context" -) - -// ContainerRestart stops and starts a container again. -// It makes the daemon to wait for the container to be up again for -// a specific amount of time, given the timeout. -func (cli *Client) ContainerRestart(ctx context.Context, containerID string, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/restart", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_start.go b/vendor/github.com/docker/docker/client/container_start.go deleted file mode 100644 index b1f08de416..0000000000 --- a/vendor/github.com/docker/docker/client/container_start.go +++ /dev/null @@ -1,24 +0,0 @@ -package client - -import ( - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" -) - -// ContainerStart sends a request to the docker daemon to start a container. -func (cli *Client) ContainerStart(ctx context.Context, containerID string, options types.ContainerStartOptions) error { - query := url.Values{} - if len(options.CheckpointID) != 0 { - query.Set("checkpoint", options.CheckpointID) - } - if len(options.CheckpointDir) != 0 { - query.Set("checkpoint-dir", options.CheckpointDir) - } - - resp, err := cli.post(ctx, "/containers/"+containerID+"/start", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_stats.go b/vendor/github.com/docker/docker/client/container_stats.go deleted file mode 100644 index 4758c66e32..0000000000 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ /dev/null @@ -1,26 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ContainerStats returns near realtime stats for a given container. -// It's up to the caller to close the io.ReadCloser returned. -func (cli *Client) ContainerStats(ctx context.Context, containerID string, stream bool) (types.ContainerStats, error) { - query := url.Values{} - query.Set("stream", "0") - if stream { - query.Set("stream", "1") - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/stats", query, nil) - if err != nil { - return types.ContainerStats{}, err - } - - osType := getDockerOS(resp.header.Get("Server")) - return types.ContainerStats{Body: resp.body, OSType: osType}, err -} diff --git a/vendor/github.com/docker/docker/client/container_stop.go b/vendor/github.com/docker/docker/client/container_stop.go deleted file mode 100644 index b5418ae8c8..0000000000 --- a/vendor/github.com/docker/docker/client/container_stop.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" - "golang.org/x/net/context" -) - -// ContainerStop stops a container without terminating the process. -// The process is blocked until the container stops or the timeout expires. -func (cli *Client) ContainerStop(ctx context.Context, containerID string, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - resp, err := cli.post(ctx, "/containers/"+containerID+"/stop", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_top.go b/vendor/github.com/docker/docker/client/container_top.go deleted file mode 100644 index 9689123a40..0000000000 --- a/vendor/github.com/docker/docker/client/container_top.go +++ /dev/null @@ -1,28 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - "strings" - - "github.com/docker/docker/api/types/container" - "golang.org/x/net/context" -) - -// ContainerTop shows process information from within a container. -func (cli *Client) ContainerTop(ctx context.Context, containerID string, arguments []string) (container.ContainerTopOKBody, error) { - var response container.ContainerTopOKBody - query := url.Values{} - if len(arguments) > 0 { - query.Set("ps_args", strings.Join(arguments, " ")) - } - - resp, err := cli.get(ctx, "/containers/"+containerID+"/top", query, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_unpause.go b/vendor/github.com/docker/docker/client/container_unpause.go deleted file mode 100644 index 5c76211256..0000000000 --- a/vendor/github.com/docker/docker/client/container_unpause.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import "golang.org/x/net/context" - -// ContainerUnpause resumes the process execution within a container -func (cli *Client) ContainerUnpause(ctx context.Context, containerID string) error { - resp, err := cli.post(ctx, "/containers/"+containerID+"/unpause", nil, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/container_update.go b/vendor/github.com/docker/docker/client/container_update.go deleted file mode 100644 index 5082f22dfa..0000000000 --- a/vendor/github.com/docker/docker/client/container_update.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types/container" - "golang.org/x/net/context" -) - -// ContainerUpdate updates resources of a container -func (cli *Client) ContainerUpdate(ctx context.Context, containerID string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) { - var response container.ContainerUpdateOKBody - serverResp, err := cli.post(ctx, "/containers/"+containerID+"/update", nil, updateConfig, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(serverResp.body).Decode(&response) - - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/container_wait.go b/vendor/github.com/docker/docker/client/container_wait.go deleted file mode 100644 index 93212c70ee..0000000000 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ /dev/null @@ -1,26 +0,0 @@ -package client - -import ( - "encoding/json" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types/container" -) - -// ContainerWait pauses execution until a container exits. -// It returns the API status code as response of its readiness. -func (cli *Client) ContainerWait(ctx context.Context, containerID string) (int64, error) { - resp, err := cli.post(ctx, "/containers/"+containerID+"/wait", nil, nil, nil) - if err != nil { - return -1, err - } - defer ensureReaderClosed(resp) - - var res container.ContainerWaitOKBody - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - return -1, err - } - - return res.StatusCode, nil -} diff --git a/vendor/github.com/docker/docker/client/disk_usage.go b/vendor/github.com/docker/docker/client/disk_usage.go deleted file mode 100644 index 03c80b39af..0000000000 --- a/vendor/github.com/docker/docker/client/disk_usage.go +++ /dev/null @@ -1,26 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// DiskUsage requests the current data usage from the daemon -func (cli *Client) DiskUsage(ctx context.Context) (types.DiskUsage, error) { - var du types.DiskUsage - - serverResp, err := cli.get(ctx, "/system/df", nil, nil) - if err != nil { - return du, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&du); err != nil { - return du, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return du, nil -} diff --git a/vendor/github.com/docker/docker/client/errors.go b/vendor/github.com/docker/docker/client/errors.go deleted file mode 100644 index 4f767bd8d3..0000000000 --- a/vendor/github.com/docker/docker/client/errors.go +++ /dev/null @@ -1,278 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/docker/docker/api/types/versions" - "github.com/pkg/errors" -) - -// errConnectionFailed implements an error returned when connection failed. -type errConnectionFailed struct { - host string -} - -// Error returns a string representation of an errConnectionFailed -func (err errConnectionFailed) Error() string { - if err.host == "" { - return "Cannot connect to the Docker daemon. Is the docker daemon running on this host?" - } - return fmt.Sprintf("Cannot connect to the Docker daemon at %s. Is the docker daemon running?", err.host) -} - -// IsErrConnectionFailed returns true if the error is caused by connection failed. -func IsErrConnectionFailed(err error) bool { - _, ok := errors.Cause(err).(errConnectionFailed) - return ok -} - -// ErrorConnectionFailed returns an error with host in the error message when connection to docker daemon failed. -func ErrorConnectionFailed(host string) error { - return errConnectionFailed{host: host} -} - -type notFound interface { - error - NotFound() bool // Is the error a NotFound error -} - -// IsErrNotFound returns true if the error is caused with an -// object (image, container, network, volume, …) is not found in the docker host. -func IsErrNotFound(err error) bool { - te, ok := err.(notFound) - return ok && te.NotFound() -} - -// imageNotFoundError implements an error returned when an image is not in the docker host. -type imageNotFoundError struct { - imageID string -} - -// NotFound indicates that this error type is of NotFound -func (e imageNotFoundError) NotFound() bool { - return true -} - -// Error returns a string representation of an imageNotFoundError -func (e imageNotFoundError) Error() string { - return fmt.Sprintf("Error: No such image: %s", e.imageID) -} - -// IsErrImageNotFound returns true if the error is caused -// when an image is not found in the docker host. -func IsErrImageNotFound(err error) bool { - return IsErrNotFound(err) -} - -// containerNotFoundError implements an error returned when a container is not in the docker host. -type containerNotFoundError struct { - containerID string -} - -// NotFound indicates that this error type is of NotFound -func (e containerNotFoundError) NotFound() bool { - return true -} - -// Error returns a string representation of a containerNotFoundError -func (e containerNotFoundError) Error() string { - return fmt.Sprintf("Error: No such container: %s", e.containerID) -} - -// IsErrContainerNotFound returns true if the error is caused -// when a container is not found in the docker host. -func IsErrContainerNotFound(err error) bool { - return IsErrNotFound(err) -} - -// networkNotFoundError implements an error returned when a network is not in the docker host. -type networkNotFoundError struct { - networkID string -} - -// NotFound indicates that this error type is of NotFound -func (e networkNotFoundError) NotFound() bool { - return true -} - -// Error returns a string representation of a networkNotFoundError -func (e networkNotFoundError) Error() string { - return fmt.Sprintf("Error: No such network: %s", e.networkID) -} - -// IsErrNetworkNotFound returns true if the error is caused -// when a network is not found in the docker host. -func IsErrNetworkNotFound(err error) bool { - return IsErrNotFound(err) -} - -// volumeNotFoundError implements an error returned when a volume is not in the docker host. -type volumeNotFoundError struct { - volumeID string -} - -// NotFound indicates that this error type is of NotFound -func (e volumeNotFoundError) NotFound() bool { - return true -} - -// Error returns a string representation of a volumeNotFoundError -func (e volumeNotFoundError) Error() string { - return fmt.Sprintf("Error: No such volume: %s", e.volumeID) -} - -// IsErrVolumeNotFound returns true if the error is caused -// when a volume is not found in the docker host. -func IsErrVolumeNotFound(err error) bool { - return IsErrNotFound(err) -} - -// unauthorizedError represents an authorization error in a remote registry. -type unauthorizedError struct { - cause error -} - -// Error returns a string representation of an unauthorizedError -func (u unauthorizedError) Error() string { - return u.cause.Error() -} - -// IsErrUnauthorized returns true if the error is caused -// when a remote registry authentication fails -func IsErrUnauthorized(err error) bool { - _, ok := err.(unauthorizedError) - return ok -} - -// nodeNotFoundError implements an error returned when a node is not found. -type nodeNotFoundError struct { - nodeID string -} - -// Error returns a string representation of a nodeNotFoundError -func (e nodeNotFoundError) Error() string { - return fmt.Sprintf("Error: No such node: %s", e.nodeID) -} - -// NotFound indicates that this error type is of NotFound -func (e nodeNotFoundError) NotFound() bool { - return true -} - -// IsErrNodeNotFound returns true if the error is caused -// when a node is not found. -func IsErrNodeNotFound(err error) bool { - _, ok := err.(nodeNotFoundError) - return ok -} - -// serviceNotFoundError implements an error returned when a service is not found. -type serviceNotFoundError struct { - serviceID string -} - -// Error returns a string representation of a serviceNotFoundError -func (e serviceNotFoundError) Error() string { - return fmt.Sprintf("Error: No such service: %s", e.serviceID) -} - -// NotFound indicates that this error type is of NotFound -func (e serviceNotFoundError) NotFound() bool { - return true -} - -// IsErrServiceNotFound returns true if the error is caused -// when a service is not found. -func IsErrServiceNotFound(err error) bool { - _, ok := err.(serviceNotFoundError) - return ok -} - -// taskNotFoundError implements an error returned when a task is not found. -type taskNotFoundError struct { - taskID string -} - -// Error returns a string representation of a taskNotFoundError -func (e taskNotFoundError) Error() string { - return fmt.Sprintf("Error: No such task: %s", e.taskID) -} - -// NotFound indicates that this error type is of NotFound -func (e taskNotFoundError) NotFound() bool { - return true -} - -// IsErrTaskNotFound returns true if the error is caused -// when a task is not found. -func IsErrTaskNotFound(err error) bool { - _, ok := err.(taskNotFoundError) - return ok -} - -type pluginPermissionDenied struct { - name string -} - -func (e pluginPermissionDenied) Error() string { - return "Permission denied while installing plugin " + e.name -} - -// IsErrPluginPermissionDenied returns true if the error is caused -// when a user denies a plugin's permissions -func IsErrPluginPermissionDenied(err error) bool { - _, ok := err.(pluginPermissionDenied) - return ok -} - -// NewVersionError returns an error if the APIVersion required -// if less than the current supported version -func (cli *Client) NewVersionError(APIrequired, feature string) error { - if versions.LessThan(cli.version, APIrequired) { - return fmt.Errorf("%q requires API version %s, but the Docker daemon API version is %s", feature, APIrequired, cli.version) - } - return nil -} - -// secretNotFoundError implements an error returned when a secret is not found. -type secretNotFoundError struct { - name string -} - -// Error returns a string representation of a secretNotFoundError -func (e secretNotFoundError) Error() string { - return fmt.Sprintf("Error: no such secret: %s", e.name) -} - -// NotFound indicates that this error type is of NotFound -func (e secretNotFoundError) NotFound() bool { - return true -} - -// IsErrSecretNotFound returns true if the error is caused -// when a secret is not found. -func IsErrSecretNotFound(err error) bool { - _, ok := err.(secretNotFoundError) - return ok -} - -// pluginNotFoundError implements an error returned when a plugin is not in the docker host. -type pluginNotFoundError struct { - name string -} - -// NotFound indicates that this error type is of NotFound -func (e pluginNotFoundError) NotFound() bool { - return true -} - -// Error returns a string representation of a pluginNotFoundError -func (e pluginNotFoundError) Error() string { - return fmt.Sprintf("Error: No such plugin: %s", e.name) -} - -// IsErrPluginNotFound returns true if the error is caused -// when a plugin is not found in the docker host. -func IsErrPluginNotFound(err error) bool { - return IsErrNotFound(err) -} diff --git a/vendor/github.com/docker/docker/client/events.go b/vendor/github.com/docker/docker/client/events.go deleted file mode 100644 index af47aefa74..0000000000 --- a/vendor/github.com/docker/docker/client/events.go +++ /dev/null @@ -1,102 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - timetypes "github.com/docker/docker/api/types/time" -) - -// Events returns a stream of events in the daemon. It's up to the caller to close the stream -// by cancelling the context. Once the stream has been completely read an io.EOF error will -// be sent over the error channel. If an error is sent all processing will be stopped. It's up -// to the caller to reopen the stream in the event of an error by reinvoking this method. -func (cli *Client) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) { - - messages := make(chan events.Message) - errs := make(chan error, 1) - - started := make(chan struct{}) - go func() { - defer close(errs) - - query, err := buildEventsQueryParams(cli.version, options) - if err != nil { - close(started) - errs <- err - return - } - - resp, err := cli.get(ctx, "/events", query, nil) - if err != nil { - close(started) - errs <- err - return - } - defer resp.body.Close() - - decoder := json.NewDecoder(resp.body) - - close(started) - for { - select { - case <-ctx.Done(): - errs <- ctx.Err() - return - default: - var event events.Message - if err := decoder.Decode(&event); err != nil { - errs <- err - return - } - - select { - case messages <- event: - case <-ctx.Done(): - errs <- ctx.Err() - return - } - } - } - }() - <-started - - return messages, errs -} - -func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url.Values, error) { - query := url.Values{} - ref := time.Now() - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, ref) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Until != "" { - ts, err := timetypes.GetTimestamp(options.Until, ref) - if err != nil { - return nil, err - } - query.Set("until", ts) - } - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters) - if err != nil { - return nil, err - } - query.Set("filters", filterJSON) - } - - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/hijack.go b/vendor/github.com/docker/docker/client/hijack.go deleted file mode 100644 index 74c53f52b3..0000000000 --- a/vendor/github.com/docker/docker/client/hijack.go +++ /dev/null @@ -1,177 +0,0 @@ -package client - -import ( - "crypto/tls" - "errors" - "fmt" - "net" - "net/http" - "net/http/httputil" - "net/url" - "strings" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/pkg/tlsconfig" - "github.com/docker/go-connections/sockets" - "golang.org/x/net/context" -) - -// tlsClientCon holds tls information and a dialed connection. -type tlsClientCon struct { - *tls.Conn - rawConn net.Conn -} - -func (c *tlsClientCon) CloseWrite() error { - // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it - // on its underlying connection. - if conn, ok := c.rawConn.(types.CloseWriter); ok { - return conn.CloseWrite() - } - return nil -} - -// postHijacked sends a POST request and hijacks the connection. -func (cli *Client) postHijacked(ctx context.Context, path string, query url.Values, body interface{}, headers map[string][]string) (types.HijackedResponse, error) { - bodyEncoded, err := encodeData(body) - if err != nil { - return types.HijackedResponse{}, err - } - - apiPath := cli.getAPIPath(path, query) - req, err := http.NewRequest("POST", apiPath, bodyEncoded) - if err != nil { - return types.HijackedResponse{}, err - } - req = cli.addHeaders(req, headers) - - req.Host = cli.addr - req.Header.Set("Connection", "Upgrade") - req.Header.Set("Upgrade", "tcp") - - conn, err := dial(cli.proto, cli.addr, resolveTLSConfig(cli.client.Transport)) - if err != nil { - if strings.Contains(err.Error(), "connection refused") { - return types.HijackedResponse{}, fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker daemon' running on this host?") - } - return types.HijackedResponse{}, err - } - - // When we set up a TCP connection for hijack, there could be long periods - // of inactivity (a long running command with no output) that in certain - // network setups may cause ECONNTIMEOUT, leaving the client in an unknown - // state. Setting TCP KeepAlive on the socket connection will prohibit - // ECONNTIMEOUT unless the socket connection truly is broken - if tcpConn, ok := conn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(30 * time.Second) - } - - clientconn := httputil.NewClientConn(conn, nil) - defer clientconn.Close() - - // Server hijacks the connection, error 'connection closed' expected - _, err = clientconn.Do(req) - - rwc, br := clientconn.Hijack() - - return types.HijackedResponse{Conn: rwc, Reader: br}, err -} - -func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { - return tlsDialWithDialer(new(net.Dialer), network, addr, config) -} - -// We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in -// order to return our custom tlsClientCon struct which holds both the tls.Conn -// object _and_ its underlying raw connection. The rationale for this is that -// we need to be able to close the write end of the connection when attaching, -// which tls.Conn does not provide. -func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { - // We want the Timeout and Deadline values from dialer to cover the - // whole process: TCP connection and TLS handshake. This means that we - // also need to start our own timers now. - timeout := dialer.Timeout - - if !dialer.Deadline.IsZero() { - deadlineTimeout := dialer.Deadline.Sub(time.Now()) - if timeout == 0 || deadlineTimeout < timeout { - timeout = deadlineTimeout - } - } - - var errChannel chan error - - if timeout != 0 { - errChannel = make(chan error, 2) - time.AfterFunc(timeout, func() { - errChannel <- errors.New("") - }) - } - - proxyDialer, err := sockets.DialerFromEnvironment(dialer) - if err != nil { - return nil, err - } - - rawConn, err := proxyDialer.Dial(network, addr) - if err != nil { - return nil, err - } - // When we set up a TCP connection for hijack, there could be long periods - // of inactivity (a long running command with no output) that in certain - // network setups may cause ECONNTIMEOUT, leaving the client in an unknown - // state. Setting TCP KeepAlive on the socket connection will prohibit - // ECONNTIMEOUT unless the socket connection truly is broken - if tcpConn, ok := rawConn.(*net.TCPConn); ok { - tcpConn.SetKeepAlive(true) - tcpConn.SetKeepAlivePeriod(30 * time.Second) - } - - colonPos := strings.LastIndex(addr, ":") - if colonPos == -1 { - colonPos = len(addr) - } - hostname := addr[:colonPos] - - // If no ServerName is set, infer the ServerName - // from the hostname we're connecting to. - if config.ServerName == "" { - // Make a copy to avoid polluting argument or default. - config = tlsconfig.Clone(config) - config.ServerName = hostname - } - - conn := tls.Client(rawConn, config) - - if timeout == 0 { - err = conn.Handshake() - } else { - go func() { - errChannel <- conn.Handshake() - }() - - err = <-errChannel - } - - if err != nil { - rawConn.Close() - return nil, err - } - - // This is Docker difference with standard's crypto/tls package: returned a - // wrapper which holds both the TLS and raw connections. - return &tlsClientCon{conn, rawConn}, nil -} - -func dial(proto, addr string, tlsConfig *tls.Config) (net.Conn, error) { - if tlsConfig != nil && proto != "unix" && proto != "npipe" { - // Notice this isn't Go standard's tls.Dial function - return tlsDial(proto, addr, tlsConfig) - } - if proto == "npipe" { - return sockets.DialPipe(addr, 32*time.Second) - } - return net.Dial(proto, addr) -} diff --git a/vendor/github.com/docker/docker/client/image_build.go b/vendor/github.com/docker/docker/client/image_build.go deleted file mode 100644 index bb69143e99..0000000000 --- a/vendor/github.com/docker/docker/client/image_build.go +++ /dev/null @@ -1,125 +0,0 @@ -package client - -import ( - "encoding/base64" - "encoding/json" - "io" - "net/http" - "net/url" - "strconv" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" -) - -// ImageBuild sends request to the daemon to build images. -// The Body in the response implement an io.ReadCloser and it's up to the caller to -// close it. -func (cli *Client) ImageBuild(ctx context.Context, buildContext io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) { - query, err := cli.imageBuildOptionsToQuery(options) - if err != nil { - return types.ImageBuildResponse{}, err - } - - headers := http.Header(make(map[string][]string)) - buf, err := json.Marshal(options.AuthConfigs) - if err != nil { - return types.ImageBuildResponse{}, err - } - headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) - headers.Set("Content-Type", "application/x-tar") - - serverResp, err := cli.postRaw(ctx, "/build", query, buildContext, headers) - if err != nil { - return types.ImageBuildResponse{}, err - } - - osType := getDockerOS(serverResp.header.Get("Server")) - - return types.ImageBuildResponse{ - Body: serverResp.body, - OSType: osType, - }, nil -} - -func (cli *Client) imageBuildOptionsToQuery(options types.ImageBuildOptions) (url.Values, error) { - query := url.Values{ - "t": options.Tags, - "securityopt": options.SecurityOpt, - "extrahosts": options.ExtraHosts, - } - if options.SuppressOutput { - query.Set("q", "1") - } - if options.RemoteContext != "" { - query.Set("remote", options.RemoteContext) - } - if options.NoCache { - query.Set("nocache", "1") - } - if options.Remove { - query.Set("rm", "1") - } else { - query.Set("rm", "0") - } - - if options.ForceRemove { - query.Set("forcerm", "1") - } - - if options.PullParent { - query.Set("pull", "1") - } - - if options.Squash { - if err := cli.NewVersionError("1.25", "squash"); err != nil { - return query, err - } - query.Set("squash", "1") - } - - if !container.Isolation.IsDefault(options.Isolation) { - query.Set("isolation", string(options.Isolation)) - } - - query.Set("cpusetcpus", options.CPUSetCPUs) - query.Set("networkmode", options.NetworkMode) - query.Set("cpusetmems", options.CPUSetMems) - query.Set("cpushares", strconv.FormatInt(options.CPUShares, 10)) - query.Set("cpuquota", strconv.FormatInt(options.CPUQuota, 10)) - query.Set("cpuperiod", strconv.FormatInt(options.CPUPeriod, 10)) - query.Set("memory", strconv.FormatInt(options.Memory, 10)) - query.Set("memswap", strconv.FormatInt(options.MemorySwap, 10)) - query.Set("cgroupparent", options.CgroupParent) - query.Set("shmsize", strconv.FormatInt(options.ShmSize, 10)) - query.Set("dockerfile", options.Dockerfile) - query.Set("target", options.Target) - - ulimitsJSON, err := json.Marshal(options.Ulimits) - if err != nil { - return query, err - } - query.Set("ulimits", string(ulimitsJSON)) - - buildArgsJSON, err := json.Marshal(options.BuildArgs) - if err != nil { - return query, err - } - query.Set("buildargs", string(buildArgsJSON)) - - labelsJSON, err := json.Marshal(options.Labels) - if err != nil { - return query, err - } - query.Set("labels", string(labelsJSON)) - - cacheFromJSON, err := json.Marshal(options.CacheFrom) - if err != nil { - return query, err - } - query.Set("cachefrom", string(cacheFromJSON)) - - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/image_create.go b/vendor/github.com/docker/docker/client/image_create.go deleted file mode 100644 index 4436abb0dd..0000000000 --- a/vendor/github.com/docker/docker/client/image_create.go +++ /dev/null @@ -1,34 +0,0 @@ -package client - -import ( - "io" - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImageCreate creates a new image based in the parent options. -// It returns the JSON content in the response body. -func (cli *Client) ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(parentReference) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - query.Set("tag", getAPITagFromNamedRef(ref)) - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImageCreate(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/images/create", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_history.go b/vendor/github.com/docker/docker/client/image_history.go deleted file mode 100644 index 7b4babcba3..0000000000 --- a/vendor/github.com/docker/docker/client/image_history.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/image" - "golang.org/x/net/context" -) - -// ImageHistory returns the changes in an image in history format. -func (cli *Client) ImageHistory(ctx context.Context, imageID string) ([]image.HistoryResponseItem, error) { - var history []image.HistoryResponseItem - serverResp, err := cli.get(ctx, "/images/"+imageID+"/history", url.Values{}, nil) - if err != nil { - return history, err - } - - err = json.NewDecoder(serverResp.body).Decode(&history) - ensureReaderClosed(serverResp) - return history, err -} diff --git a/vendor/github.com/docker/docker/client/image_import.go b/vendor/github.com/docker/docker/client/image_import.go deleted file mode 100644 index d7dedd8232..0000000000 --- a/vendor/github.com/docker/docker/client/image_import.go +++ /dev/null @@ -1,37 +0,0 @@ -package client - -import ( - "io" - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImageImport creates a new image based in the source options. -// It returns the JSON content in the response body. -func (cli *Client) ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - if ref != "" { - //Check if the given image name can be resolved - if _, err := reference.ParseNormalizedNamed(ref); err != nil { - return nil, err - } - } - - query := url.Values{} - query.Set("fromSrc", source.SourceName) - query.Set("repo", ref) - query.Set("tag", options.Tag) - query.Set("message", options.Message) - for _, change := range options.Changes { - query.Add("changes", change) - } - - resp, err := cli.postRaw(ctx, "/images/create", query, source.Source, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_inspect.go b/vendor/github.com/docker/docker/client/image_inspect.go deleted file mode 100644 index b3a64ce2f8..0000000000 --- a/vendor/github.com/docker/docker/client/image_inspect.go +++ /dev/null @@ -1,33 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ImageInspectWithRaw returns the image information and its raw representation. -func (cli *Client) ImageInspectWithRaw(ctx context.Context, imageID string) (types.ImageInspect, []byte, error) { - serverResp, err := cli.get(ctx, "/images/"+imageID+"/json", nil, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return types.ImageInspect{}, nil, imageNotFoundError{imageID} - } - return types.ImageInspect{}, nil, err - } - defer ensureReaderClosed(serverResp) - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return types.ImageInspect{}, nil, err - } - - var response types.ImageInspect - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/image_list.go b/vendor/github.com/docker/docker/client/image_list.go deleted file mode 100644 index f26464f67c..0000000000 --- a/vendor/github.com/docker/docker/client/image_list.go +++ /dev/null @@ -1,45 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/versions" - "golang.org/x/net/context" -) - -// ImageList returns a list of images in the docker host. -func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) { - var images []types.ImageSummary - query := url.Values{} - - optionFilters := options.Filters - referenceFilters := optionFilters.Get("reference") - if versions.LessThan(cli.version, "1.25") && len(referenceFilters) > 0 { - query.Set("filter", referenceFilters[0]) - for _, filterValue := range referenceFilters { - optionFilters.Del("reference", filterValue) - } - } - if optionFilters.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters) - if err != nil { - return images, err - } - query.Set("filters", filterJSON) - } - if options.All { - query.Set("all", "1") - } - - serverResp, err := cli.get(ctx, "/images/json", query, nil) - if err != nil { - return images, err - } - - err = json.NewDecoder(serverResp.body).Decode(&images) - ensureReaderClosed(serverResp) - return images, err -} diff --git a/vendor/github.com/docker/docker/client/image_load.go b/vendor/github.com/docker/docker/client/image_load.go deleted file mode 100644 index 77aaf1af36..0000000000 --- a/vendor/github.com/docker/docker/client/image_load.go +++ /dev/null @@ -1,30 +0,0 @@ -package client - -import ( - "io" - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" -) - -// ImageLoad loads an image in the docker host from the client host. -// It's up to the caller to close the io.ReadCloser in the -// ImageLoadResponse returned by this function. -func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) { - v := url.Values{} - v.Set("quiet", "0") - if quiet { - v.Set("quiet", "1") - } - headers := map[string][]string{"Content-Type": {"application/x-tar"}} - resp, err := cli.postRaw(ctx, "/images/load", v, input, headers) - if err != nil { - return types.ImageLoadResponse{}, err - } - return types.ImageLoadResponse{ - Body: resp.body, - JSON: resp.header.Get("Content-Type") == "application/json", - }, nil -} diff --git a/vendor/github.com/docker/docker/client/image_prune.go b/vendor/github.com/docker/docker/client/image_prune.go deleted file mode 100644 index 5ef98b7f02..0000000000 --- a/vendor/github.com/docker/docker/client/image_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// ImagesPrune requests the daemon to delete unused data -func (cli *Client) ImagesPrune(ctx context.Context, pruneFilters filters.Args) (types.ImagesPruneReport, error) { - var report types.ImagesPruneReport - - if err := cli.NewVersionError("1.25", "image prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/images/prune", query, nil, nil) - if err != nil { - return report, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/image_pull.go b/vendor/github.com/docker/docker/client/image_pull.go deleted file mode 100644 index a72b9bf7fc..0000000000 --- a/vendor/github.com/docker/docker/client/image_pull.go +++ /dev/null @@ -1,61 +0,0 @@ -package client - -import ( - "io" - "net/http" - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImagePull requests the docker host to pull an image from a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -// -// FIXME(vdemeester): there is currently used in a few way in docker/docker -// - if not in trusted content, ref is used to pass the whole reference, and tag is empty -// - if in trusted content, ref is used to pass the reference name, and tag for the digest -func (cli *Client) ImagePull(ctx context.Context, refStr string, options types.ImagePullOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(refStr) - if err != nil { - return nil, err - } - - query := url.Values{} - query.Set("fromImage", reference.FamiliarName(ref)) - if !options.All { - query.Set("tag", getAPITagFromNamedRef(ref)) - } - - resp, err := cli.tryImageCreate(ctx, query, options.RegistryAuth) - if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImageCreate(ctx, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -// getAPITagFromNamedRef returns a tag from the specified reference. -// This function is necessary as long as the docker "server" api expects -// digests to be sent as tags and makes a distinction between the name -// and tag/digest part of a reference. -func getAPITagFromNamedRef(ref reference.Named) string { - if digested, ok := ref.(reference.Digested); ok { - return digested.Digest().String() - } - ref = reference.TagNameOnly(ref) - if tagged, ok := ref.(reference.Tagged); ok { - return tagged.Tag() - } - return "" -} diff --git a/vendor/github.com/docker/docker/client/image_push.go b/vendor/github.com/docker/docker/client/image_push.go deleted file mode 100644 index 410d2fb91d..0000000000 --- a/vendor/github.com/docker/docker/client/image_push.go +++ /dev/null @@ -1,56 +0,0 @@ -package client - -import ( - "errors" - "io" - "net/http" - "net/url" - - "golang.org/x/net/context" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" -) - -// ImagePush requests the docker host to push an image to a remote registry. -// It executes the privileged function if the operation is unauthorized -// and it tries one more time. -// It's up to the caller to handle the io.ReadCloser and close it properly. -func (cli *Client) ImagePush(ctx context.Context, image string, options types.ImagePushOptions) (io.ReadCloser, error) { - ref, err := reference.ParseNormalizedNamed(image) - if err != nil { - return nil, err - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return nil, errors.New("cannot push a digest reference") - } - - tag := "" - name := reference.FamiliarName(ref) - - if nameTaggedRef, isNamedTagged := ref.(reference.NamedTagged); isNamedTagged { - tag = nameTaggedRef.Tag() - } - - query := url.Values{} - query.Set("tag", tag) - - resp, err := cli.tryImagePush(ctx, name, query, options.RegistryAuth) - if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return nil, privilegeErr - } - resp, err = cli.tryImagePush(ctx, name, query, newAuthHeader) - } - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryImagePush(ctx context.Context, imageID string, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/images/"+imageID+"/push", query, nil, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_remove.go b/vendor/github.com/docker/docker/client/image_remove.go deleted file mode 100644 index 6921209ee1..0000000000 --- a/vendor/github.com/docker/docker/client/image_remove.go +++ /dev/null @@ -1,31 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ImageRemove removes an image from the docker host. -func (cli *Client) ImageRemove(ctx context.Context, imageID string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - query := url.Values{} - - if options.Force { - query.Set("force", "1") - } - if !options.PruneChildren { - query.Set("noprune", "1") - } - - resp, err := cli.delete(ctx, "/images/"+imageID, query, nil) - if err != nil { - return nil, err - } - - var dels []types.ImageDeleteResponseItem - err = json.NewDecoder(resp.body).Decode(&dels) - ensureReaderClosed(resp) - return dels, err -} diff --git a/vendor/github.com/docker/docker/client/image_save.go b/vendor/github.com/docker/docker/client/image_save.go deleted file mode 100644 index ecac880a32..0000000000 --- a/vendor/github.com/docker/docker/client/image_save.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "io" - "net/url" - - "golang.org/x/net/context" -) - -// ImageSave retrieves one or more images from the docker host as an io.ReadCloser. -// It's up to the caller to store the images and close the stream. -func (cli *Client) ImageSave(ctx context.Context, imageIDs []string) (io.ReadCloser, error) { - query := url.Values{ - "names": imageIDs, - } - - resp, err := cli.get(ctx, "/images/get", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/image_search.go b/vendor/github.com/docker/docker/client/image_search.go deleted file mode 100644 index b0fcd5c23d..0000000000 --- a/vendor/github.com/docker/docker/client/image_search.go +++ /dev/null @@ -1,51 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/registry" - "golang.org/x/net/context" -) - -// ImageSearch makes the docker host to search by a term in a remote registry. -// The list of results is not sorted in any fashion. -func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) { - var results []registry.SearchResult - query := url.Values{} - query.Set("term", term) - query.Set("limit", fmt.Sprintf("%d", options.Limit)) - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParam(options.Filters) - if err != nil { - return results, err - } - query.Set("filters", filterJSON) - } - - resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth) - if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil { - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - return results, privilegeErr - } - resp, err = cli.tryImageSearch(ctx, query, newAuthHeader) - } - if err != nil { - return results, err - } - - err = json.NewDecoder(resp.body).Decode(&results) - ensureReaderClosed(resp) - return results, err -} - -func (cli *Client) tryImageSearch(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.get(ctx, "/images/search", query, headers) -} diff --git a/vendor/github.com/docker/docker/client/image_tag.go b/vendor/github.com/docker/docker/client/image_tag.go deleted file mode 100644 index 8924f71eb3..0000000000 --- a/vendor/github.com/docker/docker/client/image_tag.go +++ /dev/null @@ -1,37 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/distribution/reference" - "github.com/pkg/errors" - "golang.org/x/net/context" -) - -// ImageTag tags an image in the docker host -func (cli *Client) ImageTag(ctx context.Context, source, target string) error { - if _, err := reference.ParseAnyReference(source); err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", source) - } - - ref, err := reference.ParseNormalizedNamed(target) - if err != nil { - return errors.Wrapf(err, "Error parsing reference: %q is not a valid repository/tag", target) - } - - if _, isCanonical := ref.(reference.Canonical); isCanonical { - return errors.New("refusing to create a tag with a digest reference") - } - - ref = reference.TagNameOnly(ref) - - query := url.Values{} - query.Set("repo", reference.FamiliarName(ref)) - if tagged, ok := ref.(reference.Tagged); ok { - query.Set("tag", tagged.Tag()) - } - - resp, err := cli.post(ctx, "/images/"+source+"/tag", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/info.go b/vendor/github.com/docker/docker/client/info.go deleted file mode 100644 index ac07961224..0000000000 --- a/vendor/github.com/docker/docker/client/info.go +++ /dev/null @@ -1,26 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// Info returns information about the docker server. -func (cli *Client) Info(ctx context.Context) (types.Info, error) { - var info types.Info - serverResp, err := cli.get(ctx, "/info", url.Values{}, nil) - if err != nil { - return info, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&info); err != nil { - return info, fmt.Errorf("Error reading remote info: %v", err) - } - - return info, nil -} diff --git a/vendor/github.com/docker/docker/client/interface.go b/vendor/github.com/docker/docker/client/interface.go deleted file mode 100644 index 8dbe4300dc..0000000000 --- a/vendor/github.com/docker/docker/client/interface.go +++ /dev/null @@ -1,173 +0,0 @@ -package client - -import ( - "io" - "time" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/events" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/image" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - volumetypes "github.com/docker/docker/api/types/volume" - "golang.org/x/net/context" -) - -// CommonAPIClient is the common methods between stable and experimental versions of APIClient. -type CommonAPIClient interface { - ContainerAPIClient - ImageAPIClient - NodeAPIClient - NetworkAPIClient - PluginAPIClient - ServiceAPIClient - SwarmAPIClient - SecretAPIClient - SystemAPIClient - VolumeAPIClient - ClientVersion() string - ServerVersion(ctx context.Context) (types.Version, error) - UpdateClientVersion(v string) -} - -// ContainerAPIClient defines API client methods for the containers -type ContainerAPIClient interface { - ContainerAttach(ctx context.Context, container string, options types.ContainerAttachOptions) (types.HijackedResponse, error) - ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) - ContainerCreate(ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, containerName string) (container.ContainerCreateCreatedBody, error) - ContainerDiff(ctx context.Context, container string) ([]container.ContainerChangeResponseItem, error) - ContainerExecAttach(ctx context.Context, execID string, config types.ExecConfig) (types.HijackedResponse, error) - ContainerExecCreate(ctx context.Context, container string, config types.ExecConfig) (types.IDResponse, error) - ContainerExecInspect(ctx context.Context, execID string) (types.ContainerExecInspect, error) - ContainerExecResize(ctx context.Context, execID string, options types.ResizeOptions) error - ContainerExecStart(ctx context.Context, execID string, config types.ExecStartCheck) error - ContainerExport(ctx context.Context, container string) (io.ReadCloser, error) - ContainerInspect(ctx context.Context, container string) (types.ContainerJSON, error) - ContainerInspectWithRaw(ctx context.Context, container string, getSize bool) (types.ContainerJSON, []byte, error) - ContainerKill(ctx context.Context, container, signal string) error - ContainerList(ctx context.Context, options types.ContainerListOptions) ([]types.Container, error) - ContainerLogs(ctx context.Context, container string, options types.ContainerLogsOptions) (io.ReadCloser, error) - ContainerPause(ctx context.Context, container string) error - ContainerRemove(ctx context.Context, container string, options types.ContainerRemoveOptions) error - ContainerRename(ctx context.Context, container, newContainerName string) error - ContainerResize(ctx context.Context, container string, options types.ResizeOptions) error - ContainerRestart(ctx context.Context, container string, timeout *time.Duration) error - ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) - ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) - ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error - ContainerStop(ctx context.Context, container string, timeout *time.Duration) error - ContainerTop(ctx context.Context, container string, arguments []string) (container.ContainerTopOKBody, error) - ContainerUnpause(ctx context.Context, container string) error - ContainerUpdate(ctx context.Context, container string, updateConfig container.UpdateConfig) (container.ContainerUpdateOKBody, error) - ContainerWait(ctx context.Context, container string) (int64, error) - CopyFromContainer(ctx context.Context, container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) - CopyToContainer(ctx context.Context, container, path string, content io.Reader, options types.CopyToContainerOptions) error - ContainersPrune(ctx context.Context, pruneFilters filters.Args) (types.ContainersPruneReport, error) -} - -// ImageAPIClient defines API client methods for the images -type ImageAPIClient interface { - ImageBuild(ctx context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) - ImageCreate(ctx context.Context, parentReference string, options types.ImageCreateOptions) (io.ReadCloser, error) - ImageHistory(ctx context.Context, image string) ([]image.HistoryResponseItem, error) - ImageImport(ctx context.Context, source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) - ImageInspectWithRaw(ctx context.Context, image string) (types.ImageInspect, []byte, error) - ImageList(ctx context.Context, options types.ImageListOptions) ([]types.ImageSummary, error) - ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) - ImagePull(ctx context.Context, ref string, options types.ImagePullOptions) (io.ReadCloser, error) - ImagePush(ctx context.Context, ref string, options types.ImagePushOptions) (io.ReadCloser, error) - ImageRemove(ctx context.Context, image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) - ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) - ImageSave(ctx context.Context, images []string) (io.ReadCloser, error) - ImageTag(ctx context.Context, image, ref string) error - ImagesPrune(ctx context.Context, pruneFilter filters.Args) (types.ImagesPruneReport, error) -} - -// NetworkAPIClient defines API client methods for the networks -type NetworkAPIClient interface { - NetworkConnect(ctx context.Context, networkID, container string, config *network.EndpointSettings) error - NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) - NetworkDisconnect(ctx context.Context, networkID, container string, force bool) error - NetworkInspect(ctx context.Context, networkID string, verbose bool) (types.NetworkResource, error) - NetworkInspectWithRaw(ctx context.Context, networkID string, verbose bool) (types.NetworkResource, []byte, error) - NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) - NetworkRemove(ctx context.Context, networkID string) error - NetworksPrune(ctx context.Context, pruneFilter filters.Args) (types.NetworksPruneReport, error) -} - -// NodeAPIClient defines API client methods for the nodes -type NodeAPIClient interface { - NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) - NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) - NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error - NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error -} - -// PluginAPIClient defines API client methods for the plugins -type PluginAPIClient interface { - PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) - PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error - PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error - PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error - PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (io.ReadCloser, error) - PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) - PluginSet(ctx context.Context, name string, args []string) error - PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) - PluginCreate(ctx context.Context, createContext io.Reader, options types.PluginCreateOptions) error -} - -// ServiceAPIClient defines API client methods for the services -type ServiceAPIClient interface { - ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) - ServiceInspectWithRaw(ctx context.Context, serviceID string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) - ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) - ServiceRemove(ctx context.Context, serviceID string) error - ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) - ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) - TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) - TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) -} - -// SwarmAPIClient defines API client methods for the swarm -type SwarmAPIClient interface { - SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) - SwarmJoin(ctx context.Context, req swarm.JoinRequest) error - SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) - SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error - SwarmLeave(ctx context.Context, force bool) error - SwarmInspect(ctx context.Context) (swarm.Swarm, error) - SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error -} - -// SystemAPIClient defines API client methods for the system -type SystemAPIClient interface { - Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error) - Info(ctx context.Context) (types.Info, error) - RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) - DiskUsage(ctx context.Context) (types.DiskUsage, error) - Ping(ctx context.Context) (types.Ping, error) -} - -// VolumeAPIClient defines API client methods for the volumes -type VolumeAPIClient interface { - VolumeCreate(ctx context.Context, options volumetypes.VolumesCreateBody) (types.Volume, error) - VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) - VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) - VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumesListOKBody, error) - VolumeRemove(ctx context.Context, volumeID string, force bool) error - VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, error) -} - -// SecretAPIClient defines API client methods for secrets -type SecretAPIClient interface { - SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) - SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) - SecretRemove(ctx context.Context, id string) error - SecretInspectWithRaw(ctx context.Context, name string) (swarm.Secret, []byte, error) - SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error -} diff --git a/vendor/github.com/docker/docker/client/interface_experimental.go b/vendor/github.com/docker/docker/client/interface_experimental.go deleted file mode 100644 index 51da98ecdd..0000000000 --- a/vendor/github.com/docker/docker/client/interface_experimental.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -type apiClientExperimental interface { - CheckpointAPIClient -} - -// CheckpointAPIClient defines API client methods for the checkpoints -type CheckpointAPIClient interface { - CheckpointCreate(ctx context.Context, container string, options types.CheckpointCreateOptions) error - CheckpointDelete(ctx context.Context, container string, options types.CheckpointDeleteOptions) error - CheckpointList(ctx context.Context, container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) -} diff --git a/vendor/github.com/docker/docker/client/interface_stable.go b/vendor/github.com/docker/docker/client/interface_stable.go deleted file mode 100644 index cc90a3cbb9..0000000000 --- a/vendor/github.com/docker/docker/client/interface_stable.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -// APIClient is an interface that clients that talk with a docker server must implement. -type APIClient interface { - CommonAPIClient - apiClientExperimental -} - -// Ensure that Client always implements APIClient. -var _ APIClient = &Client{} diff --git a/vendor/github.com/docker/docker/client/login.go b/vendor/github.com/docker/docker/client/login.go deleted file mode 100644 index 79219ff59c..0000000000 --- a/vendor/github.com/docker/docker/client/login.go +++ /dev/null @@ -1,29 +0,0 @@ -package client - -import ( - "encoding/json" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/registry" - "golang.org/x/net/context" -) - -// RegistryLogin authenticates the docker server with a given docker registry. -// It returns unauthorizedError when the authentication fails. -func (cli *Client) RegistryLogin(ctx context.Context, auth types.AuthConfig) (registry.AuthenticateOKBody, error) { - resp, err := cli.post(ctx, "/auth", url.Values{}, auth, nil) - - if resp.statusCode == http.StatusUnauthorized { - return registry.AuthenticateOKBody{}, unauthorizedError{err} - } - if err != nil { - return registry.AuthenticateOKBody{}, err - } - - var response registry.AuthenticateOKBody - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_connect.go b/vendor/github.com/docker/docker/client/network_connect.go deleted file mode 100644 index c022c17b5b..0000000000 --- a/vendor/github.com/docker/docker/client/network_connect.go +++ /dev/null @@ -1,18 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/network" - "golang.org/x/net/context" -) - -// NetworkConnect connects a container to an existent network in the docker host. -func (cli *Client) NetworkConnect(ctx context.Context, networkID, containerID string, config *network.EndpointSettings) error { - nc := types.NetworkConnect{ - Container: containerID, - EndpointConfig: config, - } - resp, err := cli.post(ctx, "/networks/"+networkID+"/connect", nil, nc, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_create.go b/vendor/github.com/docker/docker/client/network_create.go deleted file mode 100644 index 4067a541ff..0000000000 --- a/vendor/github.com/docker/docker/client/network_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// NetworkCreate creates a new network in the docker host. -func (cli *Client) NetworkCreate(ctx context.Context, name string, options types.NetworkCreate) (types.NetworkCreateResponse, error) { - networkCreateRequest := types.NetworkCreateRequest{ - NetworkCreate: options, - Name: name, - } - var response types.NetworkCreateResponse - serverResp, err := cli.post(ctx, "/networks/create", nil, networkCreateRequest, nil) - if err != nil { - return response, err - } - - json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/network_disconnect.go b/vendor/github.com/docker/docker/client/network_disconnect.go deleted file mode 100644 index 24b58e3c12..0000000000 --- a/vendor/github.com/docker/docker/client/network_disconnect.go +++ /dev/null @@ -1,14 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// NetworkDisconnect disconnects a container from an existent network in the docker host. -func (cli *Client) NetworkDisconnect(ctx context.Context, networkID, containerID string, force bool) error { - nd := types.NetworkDisconnect{Container: containerID, Force: force} - resp, err := cli.post(ctx, "/networks/"+networkID+"/disconnect", nil, nd, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/network_inspect.go b/vendor/github.com/docker/docker/client/network_inspect.go deleted file mode 100644 index 7242304025..0000000000 --- a/vendor/github.com/docker/docker/client/network_inspect.go +++ /dev/null @@ -1,47 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// NetworkInspect returns the information for a specific network configured in the docker host. -func (cli *Client) NetworkInspect(ctx context.Context, networkID string, verbose bool) (types.NetworkResource, error) { - networkResource, _, err := cli.NetworkInspectWithRaw(ctx, networkID, verbose) - return networkResource, err -} - -// NetworkInspectWithRaw returns the information for a specific network configured in the docker host and its raw representation. -func (cli *Client) NetworkInspectWithRaw(ctx context.Context, networkID string, verbose bool) (types.NetworkResource, []byte, error) { - var ( - networkResource types.NetworkResource - resp serverResponse - err error - ) - query := url.Values{} - if verbose { - query.Set("verbose", "true") - } - resp, err = cli.get(ctx, "/networks/"+networkID, query, nil) - if err != nil { - if resp.statusCode == http.StatusNotFound { - return networkResource, nil, networkNotFoundError{networkID} - } - return networkResource, nil, err - } - defer ensureReaderClosed(resp) - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return networkResource, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&networkResource) - return networkResource, body, err -} diff --git a/vendor/github.com/docker/docker/client/network_list.go b/vendor/github.com/docker/docker/client/network_list.go deleted file mode 100644 index e566a93e23..0000000000 --- a/vendor/github.com/docker/docker/client/network_list.go +++ /dev/null @@ -1,31 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// NetworkList returns the list of networks configured in the docker host. -func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { - query := url.Values{} - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - var networkResources []types.NetworkResource - resp, err := cli.get(ctx, "/networks", query, nil) - if err != nil { - return networkResources, err - } - err = json.NewDecoder(resp.body).Decode(&networkResources) - ensureReaderClosed(resp) - return networkResources, err -} diff --git a/vendor/github.com/docker/docker/client/network_prune.go b/vendor/github.com/docker/docker/client/network_prune.go deleted file mode 100644 index 7352a7f0c5..0000000000 --- a/vendor/github.com/docker/docker/client/network_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// NetworksPrune requests the daemon to delete unused networks -func (cli *Client) NetworksPrune(ctx context.Context, pruneFilters filters.Args) (types.NetworksPruneReport, error) { - var report types.NetworksPruneReport - - if err := cli.NewVersionError("1.25", "network prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/networks/prune", query, nil, nil) - if err != nil { - return report, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving network prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/network_remove.go b/vendor/github.com/docker/docker/client/network_remove.go deleted file mode 100644 index 6bd6748924..0000000000 --- a/vendor/github.com/docker/docker/client/network_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import "golang.org/x/net/context" - -// NetworkRemove removes an existent network from the docker host. -func (cli *Client) NetworkRemove(ctx context.Context, networkID string) error { - resp, err := cli.delete(ctx, "/networks/"+networkID, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/node_inspect.go b/vendor/github.com/docker/docker/client/node_inspect.go deleted file mode 100644 index abf505d29c..0000000000 --- a/vendor/github.com/docker/docker/client/node_inspect.go +++ /dev/null @@ -1,33 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// NodeInspectWithRaw returns the node information. -func (cli *Client) NodeInspectWithRaw(ctx context.Context, nodeID string) (swarm.Node, []byte, error) { - serverResp, err := cli.get(ctx, "/nodes/"+nodeID, nil, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return swarm.Node{}, nil, nodeNotFoundError{nodeID} - } - return swarm.Node{}, nil, err - } - defer ensureReaderClosed(serverResp) - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Node{}, nil, err - } - - var response swarm.Node - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/node_list.go b/vendor/github.com/docker/docker/client/node_list.go deleted file mode 100644 index 3e8440f08e..0000000000 --- a/vendor/github.com/docker/docker/client/node_list.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// NodeList returns the list of nodes. -func (cli *Client) NodeList(ctx context.Context, options types.NodeListOptions) ([]swarm.Node, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParam(options.Filters) - - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/nodes", query, nil) - if err != nil { - return nil, err - } - - var nodes []swarm.Node - err = json.NewDecoder(resp.body).Decode(&nodes) - ensureReaderClosed(resp) - return nodes, err -} diff --git a/vendor/github.com/docker/docker/client/node_remove.go b/vendor/github.com/docker/docker/client/node_remove.go deleted file mode 100644 index 0a77f3d578..0000000000 --- a/vendor/github.com/docker/docker/client/node_remove.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - - "golang.org/x/net/context" -) - -// NodeRemove removes a Node. -func (cli *Client) NodeRemove(ctx context.Context, nodeID string, options types.NodeRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/nodes/"+nodeID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/node_update.go b/vendor/github.com/docker/docker/client/node_update.go deleted file mode 100644 index 3ca9760282..0000000000 --- a/vendor/github.com/docker/docker/client/node_update.go +++ /dev/null @@ -1,18 +0,0 @@ -package client - -import ( - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// NodeUpdate updates a Node. -func (cli *Client) NodeUpdate(ctx context.Context, nodeID string, version swarm.Version, node swarm.NodeSpec) error { - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - resp, err := cli.post(ctx, "/nodes/"+nodeID+"/update", query, node, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/ping.go b/vendor/github.com/docker/docker/client/ping.go deleted file mode 100644 index d6212ef8bb..0000000000 --- a/vendor/github.com/docker/docker/client/ping.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// Ping pings the server and returns the value of the "Docker-Experimental", "OS-Type" & "API-Version" headers -func (cli *Client) Ping(ctx context.Context) (types.Ping, error) { - var ping types.Ping - req, err := cli.buildRequest("GET", fmt.Sprintf("%s/_ping", cli.basePath), nil, nil) - if err != nil { - return ping, err - } - serverResp, err := cli.doRequest(ctx, req) - if err != nil { - return ping, err - } - defer ensureReaderClosed(serverResp) - - ping.APIVersion = serverResp.header.Get("API-Version") - - if serverResp.header.Get("Docker-Experimental") == "true" { - ping.Experimental = true - } - - ping.OSType = serverResp.header.Get("OSType") - - return ping, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_create.go b/vendor/github.com/docker/docker/client/plugin_create.go deleted file mode 100644 index 27954aa573..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_create.go +++ /dev/null @@ -1,26 +0,0 @@ -package client - -import ( - "io" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// PluginCreate creates a plugin -func (cli *Client) PluginCreate(ctx context.Context, createContext io.Reader, createOptions types.PluginCreateOptions) error { - headers := http.Header(make(map[string][]string)) - headers.Set("Content-Type", "application/x-tar") - - query := url.Values{} - query.Set("name", createOptions.RepoName) - - resp, err := cli.postRaw(ctx, "/plugins/create", query, createContext, headers) - if err != nil { - return err - } - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_disable.go b/vendor/github.com/docker/docker/client/plugin_disable.go deleted file mode 100644 index 30467db742..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_disable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// PluginDisable disables a plugin -func (cli *Client) PluginDisable(ctx context.Context, name string, options types.PluginDisableOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/plugins/"+name+"/disable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_enable.go b/vendor/github.com/docker/docker/client/plugin_enable.go deleted file mode 100644 index 95517c4b80..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_enable.go +++ /dev/null @@ -1,19 +0,0 @@ -package client - -import ( - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// PluginEnable enables a plugin -func (cli *Client) PluginEnable(ctx context.Context, name string, options types.PluginEnableOptions) error { - query := url.Values{} - query.Set("timeout", strconv.Itoa(options.Timeout)) - - resp, err := cli.post(ctx, "/plugins/"+name+"/enable", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_inspect.go b/vendor/github.com/docker/docker/client/plugin_inspect.go deleted file mode 100644 index 89f39ee2c6..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_inspect.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// PluginInspectWithRaw inspects an existing plugin -func (cli *Client) PluginInspectWithRaw(ctx context.Context, name string) (*types.Plugin, []byte, error) { - resp, err := cli.get(ctx, "/plugins/"+name+"/json", nil, nil) - if err != nil { - if resp.statusCode == http.StatusNotFound { - return nil, nil, pluginNotFoundError{name} - } - return nil, nil, err - } - - defer ensureReaderClosed(resp) - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return nil, nil, err - } - var p types.Plugin - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&p) - return &p, body, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_install.go b/vendor/github.com/docker/docker/client/plugin_install.go deleted file mode 100644 index ce3e0506e5..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ /dev/null @@ -1,113 +0,0 @@ -package client - -import ( - "encoding/json" - "io" - "net/http" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" - "golang.org/x/net/context" -) - -// PluginInstall installs a plugin -func (cli *Client) PluginInstall(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - // set name for plugin pull, if empty should default to remote reference - query.Set("name", name) - - resp, err := cli.tryPluginPull(ctx, query, privileges, options.RegistryAuth) - if err != nil { - return nil, err - } - - name = resp.header.Get("Docker-Plugin-Name") - - pr, pw := io.Pipe() - go func() { // todo: the client should probably be designed more around the actual api - _, err := io.Copy(pw, resp.body) - if err != nil { - pw.CloseWithError(err) - return - } - defer func() { - if err != nil { - delResp, _ := cli.delete(ctx, "/plugins/"+name, nil, nil) - ensureReaderClosed(delResp) - } - }() - if len(options.Args) > 0 { - if err := cli.PluginSet(ctx, name, options.Args); err != nil { - pw.CloseWithError(err) - return - } - } - - if options.Disabled { - pw.Close() - return - } - - enableErr := cli.PluginEnable(ctx, name, types.PluginEnableOptions{Timeout: 0}) - pw.CloseWithError(enableErr) - }() - return pr, nil -} - -func (cli *Client) tryPluginPrivileges(ctx context.Context, query url.Values, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.get(ctx, "/plugins/privileges", query, headers) -} - -func (cli *Client) tryPluginPull(ctx context.Context, query url.Values, privileges types.PluginPrivileges, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, "/plugins/pull", query, privileges, headers) -} - -func (cli *Client) checkPluginPermissions(ctx context.Context, query url.Values, options types.PluginInstallOptions) (types.PluginPrivileges, error) { - resp, err := cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - if resp.statusCode == http.StatusUnauthorized && options.PrivilegeFunc != nil { - // todo: do inspect before to check existing name before checking privileges - newAuthHeader, privilegeErr := options.PrivilegeFunc() - if privilegeErr != nil { - ensureReaderClosed(resp) - return nil, privilegeErr - } - options.RegistryAuth = newAuthHeader - resp, err = cli.tryPluginPrivileges(ctx, query, options.RegistryAuth) - } - if err != nil { - ensureReaderClosed(resp) - return nil, err - } - - var privileges types.PluginPrivileges - if err := json.NewDecoder(resp.body).Decode(&privileges); err != nil { - ensureReaderClosed(resp) - return nil, err - } - ensureReaderClosed(resp) - - if !options.AcceptAllPermissions && options.AcceptPermissionsFunc != nil && len(privileges) > 0 { - accept, err := options.AcceptPermissionsFunc(privileges) - if err != nil { - return nil, err - } - if !accept { - return nil, pluginPermissionDenied{options.RemoteRef} - } - } - return privileges, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_list.go b/vendor/github.com/docker/docker/client/plugin_list.go deleted file mode 100644 index 3acde3b966..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_list.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// PluginList returns the installed plugins -func (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.PluginsListResponse, error) { - var plugins types.PluginsListResponse - query := url.Values{} - - if filter.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - if err != nil { - return plugins, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/plugins", query, nil) - if err != nil { - return plugins, err - } - - err = json.NewDecoder(resp.body).Decode(&plugins) - ensureReaderClosed(resp) - return plugins, err -} diff --git a/vendor/github.com/docker/docker/client/plugin_push.go b/vendor/github.com/docker/docker/client/plugin_push.go deleted file mode 100644 index 1e5f963251..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ /dev/null @@ -1,17 +0,0 @@ -package client - -import ( - "io" - - "golang.org/x/net/context" -) - -// PluginPush pushes a plugin to a registry -func (cli *Client) PluginPush(ctx context.Context, name string, registryAuth string) (io.ReadCloser, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - resp, err := cli.post(ctx, "/plugins/"+name+"/push", nil, nil, headers) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/plugin_remove.go b/vendor/github.com/docker/docker/client/plugin_remove.go deleted file mode 100644 index b017e4d348..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_remove.go +++ /dev/null @@ -1,20 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// PluginRemove removes a plugin -func (cli *Client) PluginRemove(ctx context.Context, name string, options types.PluginRemoveOptions) error { - query := url.Values{} - if options.Force { - query.Set("force", "1") - } - - resp, err := cli.delete(ctx, "/plugins/"+name, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_set.go b/vendor/github.com/docker/docker/client/plugin_set.go deleted file mode 100644 index 3260d2a90d..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_set.go +++ /dev/null @@ -1,12 +0,0 @@ -package client - -import ( - "golang.org/x/net/context" -) - -// PluginSet modifies settings for an existing plugin -func (cli *Client) PluginSet(ctx context.Context, name string, args []string) error { - resp, err := cli.post(ctx, "/plugins/"+name+"/set", nil, args, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/plugin_upgrade.go b/vendor/github.com/docker/docker/client/plugin_upgrade.go deleted file mode 100644 index 24293c5073..0000000000 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ /dev/null @@ -1,37 +0,0 @@ -package client - -import ( - "fmt" - "io" - "net/url" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/pkg/errors" - "golang.org/x/net/context" -) - -// PluginUpgrade upgrades a plugin -func (cli *Client) PluginUpgrade(ctx context.Context, name string, options types.PluginInstallOptions) (rc io.ReadCloser, err error) { - query := url.Values{} - if _, err := reference.ParseNormalizedNamed(options.RemoteRef); err != nil { - return nil, errors.Wrap(err, "invalid remote reference") - } - query.Set("remote", options.RemoteRef) - - privileges, err := cli.checkPluginPermissions(ctx, query, options) - if err != nil { - return nil, err - } - - resp, err := cli.tryPluginUpgrade(ctx, query, privileges, name, options.RegistryAuth) - if err != nil { - return nil, err - } - return resp.body, nil -} - -func (cli *Client) tryPluginUpgrade(ctx context.Context, query url.Values, privileges types.PluginPrivileges, name, registryAuth string) (serverResponse, error) { - headers := map[string][]string{"X-Registry-Auth": {registryAuth}} - return cli.post(ctx, fmt.Sprintf("/plugins/%s/upgrade", name), query, privileges, headers) -} diff --git a/vendor/github.com/docker/docker/client/request.go b/vendor/github.com/docker/docker/client/request.go deleted file mode 100644 index 6457b316a3..0000000000 --- a/vendor/github.com/docker/docker/client/request.go +++ /dev/null @@ -1,247 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/versions" - "github.com/pkg/errors" - "golang.org/x/net/context" - "golang.org/x/net/context/ctxhttp" -) - -// serverResponse is a wrapper for http API responses. -type serverResponse struct { - body io.ReadCloser - header http.Header - statusCode int -} - -// head sends an http request to the docker API using the method HEAD. -func (cli *Client) head(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "HEAD", path, query, nil, headers) -} - -// get sends an http request to the docker API using the method GET with a specific Go context. -func (cli *Client) get(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "GET", path, query, nil, headers) -} - -// post sends an http request to the docker API using the method POST with a specific Go context. -func (cli *Client) post(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, "POST", path, query, body, headers) -} - -func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "POST", path, query, body, headers) -} - -// put sends an http request to the docker API using the method PUT. -func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, "PUT", path, query, body, headers) -} - -// putRaw sends an http request to the docker API using the method PUT. -func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "PUT", path, query, body, headers) -} - -// delete sends an http request to the docker API using the method DELETE. -func (cli *Client) delete(ctx context.Context, path string, query url.Values, headers map[string][]string) (serverResponse, error) { - return cli.sendRequest(ctx, "DELETE", path, query, nil, headers) -} - -type headers map[string][]string - -func encodeBody(obj interface{}, headers headers) (io.Reader, headers, error) { - if obj == nil { - return nil, headers, nil - } - - body, err := encodeData(obj) - if err != nil { - return nil, headers, err - } - if headers == nil { - headers = make(map[string][]string) - } - headers["Content-Type"] = []string{"application/json"} - return body, headers, nil -} - -func (cli *Client) buildRequest(method, path string, body io.Reader, headers headers) (*http.Request, error) { - expectedPayload := (method == "POST" || method == "PUT") - if expectedPayload && body == nil { - body = bytes.NewReader([]byte{}) - } - - req, err := http.NewRequest(method, path, body) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, headers) - - if cli.proto == "unix" || cli.proto == "npipe" { - // For local communications, it doesn't matter what the host is. We just - // need a valid and meaningful host name. (See #189) - req.Host = "docker" - } - - req.URL.Host = cli.addr - req.URL.Scheme = cli.scheme - - if expectedPayload && req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "text/plain") - } - return req, nil -} - -func (cli *Client) sendRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, headers headers) (serverResponse, error) { - req, err := cli.buildRequest(method, cli.getAPIPath(path, query), body, headers) - if err != nil { - return serverResponse{}, err - } - return cli.doRequest(ctx, req) -} - -func (cli *Client) doRequest(ctx context.Context, req *http.Request) (serverResponse, error) { - serverResp := serverResponse{statusCode: -1} - - resp, err := ctxhttp.Do(ctx, cli.client, req) - if err != nil { - if cli.scheme != "https" && strings.Contains(err.Error(), "malformed HTTP response") { - return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?", err) - } - - if cli.scheme == "https" && strings.Contains(err.Error(), "bad certificate") { - return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err) - } - - // Don't decorate context sentinel errors; users may be comparing to - // them directly. - switch err { - case context.Canceled, context.DeadlineExceeded: - return serverResp, err - } - - if nErr, ok := err.(*url.Error); ok { - if nErr, ok := nErr.Err.(*net.OpError); ok { - if os.IsPermission(nErr.Err) { - return serverResp, errors.Wrapf(err, "Got permission denied while trying to connect to the Docker daemon socket at %v", cli.host) - } - } - } - - if err, ok := err.(net.Error); ok { - if err.Timeout() { - return serverResp, ErrorConnectionFailed(cli.host) - } - if !err.Temporary() { - if strings.Contains(err.Error(), "connection refused") || strings.Contains(err.Error(), "dial unix") { - return serverResp, ErrorConnectionFailed(cli.host) - } - } - } - - // Although there's not a strongly typed error for this in go-winio, - // lots of people are using the default configuration for the docker - // daemon on Windows where the daemon is listening on a named pipe - // `//./pipe/docker_engine, and the client must be running elevated. - // Give users a clue rather than the not-overly useful message - // such as `error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info: - // open //./pipe/docker_engine: The system cannot find the file specified.`. - // Note we can't string compare "The system cannot find the file specified" as - // this is localised - for example in French the error would be - // `open //./pipe/docker_engine: Le fichier spécifié est introuvable.` - if strings.Contains(err.Error(), `open //./pipe/docker_engine`) { - err = errors.New(err.Error() + " In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.") - } - - return serverResp, errors.Wrap(err, "error during connect") - } - - if resp != nil { - serverResp.statusCode = resp.StatusCode - } - - if serverResp.statusCode < 200 || serverResp.statusCode >= 400 { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return serverResp, err - } - if len(body) == 0 { - return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL) - } - - var errorMessage string - if (cli.version == "" || versions.GreaterThan(cli.version, "1.23")) && - resp.Header.Get("Content-Type") == "application/json" { - var errorResponse types.ErrorResponse - if err := json.Unmarshal(body, &errorResponse); err != nil { - return serverResp, fmt.Errorf("Error reading JSON: %v", err) - } - errorMessage = errorResponse.Message - } else { - errorMessage = string(body) - } - - return serverResp, fmt.Errorf("Error response from daemon: %s", strings.TrimSpace(errorMessage)) - } - - serverResp.body = resp.Body - serverResp.header = resp.Header - return serverResp, nil -} - -func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request { - // Add CLI Config's HTTP Headers BEFORE we set the Docker headers - // then the user can't change OUR headers - for k, v := range cli.customHTTPHeaders { - if versions.LessThan(cli.version, "1.25") && k == "User-Agent" { - continue - } - req.Header.Set(k, v) - } - - if headers != nil { - for k, v := range headers { - req.Header[k] = v - } - } - return req -} - -func encodeData(data interface{}) (*bytes.Buffer, error) { - params := bytes.NewBuffer(nil) - if data != nil { - if err := json.NewEncoder(params).Encode(data); err != nil { - return nil, err - } - } - return params, nil -} - -func ensureReaderClosed(response serverResponse) { - if body := response.body; body != nil { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(ioutil.Discard, body, 512) - response.body.Close() - } -} diff --git a/vendor/github.com/docker/docker/client/secret_create.go b/vendor/github.com/docker/docker/client/secret_create.go deleted file mode 100644 index b5325a560f..0000000000 --- a/vendor/github.com/docker/docker/client/secret_create.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SecretCreate creates a new Secret. -func (cli *Client) SecretCreate(ctx context.Context, secret swarm.SecretSpec) (types.SecretCreateResponse, error) { - var response types.SecretCreateResponse - resp, err := cli.post(ctx, "/secrets/create", nil, secret, nil) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/secret_inspect.go b/vendor/github.com/docker/docker/client/secret_inspect.go deleted file mode 100644 index f774576118..0000000000 --- a/vendor/github.com/docker/docker/client/secret_inspect.go +++ /dev/null @@ -1,34 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SecretInspectWithRaw returns the secret information with raw data -func (cli *Client) SecretInspectWithRaw(ctx context.Context, id string) (swarm.Secret, []byte, error) { - resp, err := cli.get(ctx, "/secrets/"+id, nil, nil) - if err != nil { - if resp.statusCode == http.StatusNotFound { - return swarm.Secret{}, nil, secretNotFoundError{id} - } - return swarm.Secret{}, nil, err - } - defer ensureReaderClosed(resp) - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return swarm.Secret{}, nil, err - } - - var secret swarm.Secret - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&secret) - - return secret, body, err -} diff --git a/vendor/github.com/docker/docker/client/secret_list.go b/vendor/github.com/docker/docker/client/secret_list.go deleted file mode 100644 index 7e9d5ec167..0000000000 --- a/vendor/github.com/docker/docker/client/secret_list.go +++ /dev/null @@ -1,35 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SecretList returns the list of secrets. -func (cli *Client) SecretList(ctx context.Context, options types.SecretListOptions) ([]swarm.Secret, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParam(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/secrets", query, nil) - if err != nil { - return nil, err - } - - var secrets []swarm.Secret - err = json.NewDecoder(resp.body).Decode(&secrets) - ensureReaderClosed(resp) - return secrets, err -} diff --git a/vendor/github.com/docker/docker/client/secret_remove.go b/vendor/github.com/docker/docker/client/secret_remove.go deleted file mode 100644 index 1955b988a9..0000000000 --- a/vendor/github.com/docker/docker/client/secret_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import "golang.org/x/net/context" - -// SecretRemove removes a Secret. -func (cli *Client) SecretRemove(ctx context.Context, id string) error { - resp, err := cli.delete(ctx, "/secrets/"+id, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/secret_update.go b/vendor/github.com/docker/docker/client/secret_update.go deleted file mode 100644 index 42cdbbe176..0000000000 --- a/vendor/github.com/docker/docker/client/secret_update.go +++ /dev/null @@ -1,18 +0,0 @@ -package client - -import ( - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SecretUpdate attempts to updates a Secret -func (cli *Client) SecretUpdate(ctx context.Context, id string, version swarm.Version, secret swarm.SecretSpec) error { - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - resp, err := cli.post(ctx, "/secrets/"+id+"/update", query, secret, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/service_create.go b/vendor/github.com/docker/docker/client/service_create.go deleted file mode 100644 index 3d1be225bd..0000000000 --- a/vendor/github.com/docker/docker/client/service_create.go +++ /dev/null @@ -1,30 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// ServiceCreate creates a new Service. -func (cli *Client) ServiceCreate(ctx context.Context, service swarm.ServiceSpec, options types.ServiceCreateOptions) (types.ServiceCreateResponse, error) { - var headers map[string][]string - - if options.EncodedRegistryAuth != "" { - headers = map[string][]string{ - "X-Registry-Auth": {options.EncodedRegistryAuth}, - } - } - - var response types.ServiceCreateResponse - resp, err := cli.post(ctx, "/services/create", nil, service, headers) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/service_inspect.go b/vendor/github.com/docker/docker/client/service_inspect.go deleted file mode 100644 index d7e051e3a4..0000000000 --- a/vendor/github.com/docker/docker/client/service_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// ServiceInspectWithRaw returns the service information and the raw data. -func (cli *Client) ServiceInspectWithRaw(ctx context.Context, serviceID string, opts types.ServiceInspectOptions) (swarm.Service, []byte, error) { - query := url.Values{} - query.Set("insertDefaults", fmt.Sprintf("%v", opts.InsertDefaults)) - serverResp, err := cli.get(ctx, "/services/"+serviceID, query, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return swarm.Service{}, nil, serviceNotFoundError{serviceID} - } - return swarm.Service{}, nil, err - } - defer ensureReaderClosed(serverResp) - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Service{}, nil, err - } - - var response swarm.Service - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/service_list.go b/vendor/github.com/docker/docker/client/service_list.go deleted file mode 100644 index c29e6d407d..0000000000 --- a/vendor/github.com/docker/docker/client/service_list.go +++ /dev/null @@ -1,35 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// ServiceList returns the list of services. -func (cli *Client) ServiceList(ctx context.Context, options types.ServiceListOptions) ([]swarm.Service, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParam(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/services", query, nil) - if err != nil { - return nil, err - } - - var services []swarm.Service - err = json.NewDecoder(resp.body).Decode(&services) - ensureReaderClosed(resp) - return services, err -} diff --git a/vendor/github.com/docker/docker/client/service_logs.go b/vendor/github.com/docker/docker/client/service_logs.go deleted file mode 100644 index 24384e3ec0..0000000000 --- a/vendor/github.com/docker/docker/client/service_logs.go +++ /dev/null @@ -1,52 +0,0 @@ -package client - -import ( - "io" - "net/url" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" -) - -// ServiceLogs returns the logs generated by a service in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/services/"+serviceID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/service_remove.go b/vendor/github.com/docker/docker/client/service_remove.go deleted file mode 100644 index a9331f92c2..0000000000 --- a/vendor/github.com/docker/docker/client/service_remove.go +++ /dev/null @@ -1,10 +0,0 @@ -package client - -import "golang.org/x/net/context" - -// ServiceRemove kills and removes a service. -func (cli *Client) ServiceRemove(ctx context.Context, serviceID string) error { - resp, err := cli.delete(ctx, "/services/"+serviceID, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/service_update.go b/vendor/github.com/docker/docker/client/service_update.go deleted file mode 100644 index 873a1e0556..0000000000 --- a/vendor/github.com/docker/docker/client/service_update.go +++ /dev/null @@ -1,45 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// ServiceUpdate updates a Service. -func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) { - var ( - headers map[string][]string - query = url.Values{} - ) - - if options.EncodedRegistryAuth != "" { - headers = map[string][]string{ - "X-Registry-Auth": {options.EncodedRegistryAuth}, - } - } - - if options.RegistryAuthFrom != "" { - query.Set("registryAuthFrom", options.RegistryAuthFrom) - } - - if options.Rollback != "" { - query.Set("rollback", options.Rollback) - } - - query.Set("version", strconv.FormatUint(version.Index, 10)) - - var response types.ServiceUpdateResponse - resp, err := cli.post(ctx, "/services/"+serviceID+"/update", query, service, headers) - if err != nil { - return response, err - } - - err = json.NewDecoder(resp.body).Decode(&response) - ensureReaderClosed(resp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go b/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go deleted file mode 100644 index be28d32628..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_get_unlock_key.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// SwarmGetUnlockKey retrieves the swarm's unlock key. -func (cli *Client) SwarmGetUnlockKey(ctx context.Context) (types.SwarmUnlockKeyResponse, error) { - serverResp, err := cli.get(ctx, "/swarm/unlockkey", nil, nil) - if err != nil { - return types.SwarmUnlockKeyResponse{}, err - } - - var response types.SwarmUnlockKeyResponse - err = json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_init.go b/vendor/github.com/docker/docker/client/swarm_init.go deleted file mode 100644 index 9e65e1cca4..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_init.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SwarmInit initializes the swarm. -func (cli *Client) SwarmInit(ctx context.Context, req swarm.InitRequest) (string, error) { - serverResp, err := cli.post(ctx, "/swarm/init", nil, req, nil) - if err != nil { - return "", err - } - - var response string - err = json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_inspect.go b/vendor/github.com/docker/docker/client/swarm_inspect.go deleted file mode 100644 index 77e72f8466..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_inspect.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SwarmInspect inspects the swarm. -func (cli *Client) SwarmInspect(ctx context.Context) (swarm.Swarm, error) { - serverResp, err := cli.get(ctx, "/swarm", nil, nil) - if err != nil { - return swarm.Swarm{}, err - } - - var response swarm.Swarm - err = json.NewDecoder(serverResp.body).Decode(&response) - ensureReaderClosed(serverResp) - return response, err -} diff --git a/vendor/github.com/docker/docker/client/swarm_join.go b/vendor/github.com/docker/docker/client/swarm_join.go deleted file mode 100644 index 19e5192b9e..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_join.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SwarmJoin joins the swarm. -func (cli *Client) SwarmJoin(ctx context.Context, req swarm.JoinRequest) error { - resp, err := cli.post(ctx, "/swarm/join", nil, req, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_leave.go b/vendor/github.com/docker/docker/client/swarm_leave.go deleted file mode 100644 index 3a205cf3b5..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_leave.go +++ /dev/null @@ -1,18 +0,0 @@ -package client - -import ( - "net/url" - - "golang.org/x/net/context" -) - -// SwarmLeave leaves the swarm. -func (cli *Client) SwarmLeave(ctx context.Context, force bool) error { - query := url.Values{} - if force { - query.Set("force", "1") - } - resp, err := cli.post(ctx, "/swarm/leave", query, nil, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_unlock.go b/vendor/github.com/docker/docker/client/swarm_unlock.go deleted file mode 100644 index 9ee441fed2..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_unlock.go +++ /dev/null @@ -1,13 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SwarmUnlock unlocks locked swarm. -func (cli *Client) SwarmUnlock(ctx context.Context, req swarm.UnlockRequest) error { - serverResp, err := cli.post(ctx, "/swarm/unlock", nil, req, nil) - ensureReaderClosed(serverResp) - return err -} diff --git a/vendor/github.com/docker/docker/client/swarm_update.go b/vendor/github.com/docker/docker/client/swarm_update.go deleted file mode 100644 index 7245fd4e38..0000000000 --- a/vendor/github.com/docker/docker/client/swarm_update.go +++ /dev/null @@ -1,22 +0,0 @@ -package client - -import ( - "fmt" - "net/url" - "strconv" - - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// SwarmUpdate updates the swarm. -func (cli *Client) SwarmUpdate(ctx context.Context, version swarm.Version, swarm swarm.Spec, flags swarm.UpdateFlags) error { - query := url.Values{} - query.Set("version", strconv.FormatUint(version.Index, 10)) - query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) - query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken)) - query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", flags.RotateManagerUnlockKey)) - resp, err := cli.post(ctx, "/swarm/update", query, swarm, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/client/task_inspect.go b/vendor/github.com/docker/docker/client/task_inspect.go deleted file mode 100644 index bc8058fc32..0000000000 --- a/vendor/github.com/docker/docker/client/task_inspect.go +++ /dev/null @@ -1,34 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types/swarm" - - "golang.org/x/net/context" -) - -// TaskInspectWithRaw returns the task information and its raw representation.. -func (cli *Client) TaskInspectWithRaw(ctx context.Context, taskID string) (swarm.Task, []byte, error) { - serverResp, err := cli.get(ctx, "/tasks/"+taskID, nil, nil) - if err != nil { - if serverResp.statusCode == http.StatusNotFound { - return swarm.Task{}, nil, taskNotFoundError{taskID} - } - return swarm.Task{}, nil, err - } - defer ensureReaderClosed(serverResp) - - body, err := ioutil.ReadAll(serverResp.body) - if err != nil { - return swarm.Task{}, nil, err - } - - var response swarm.Task - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&response) - return response, body, err -} diff --git a/vendor/github.com/docker/docker/client/task_list.go b/vendor/github.com/docker/docker/client/task_list.go deleted file mode 100644 index 66324da959..0000000000 --- a/vendor/github.com/docker/docker/client/task_list.go +++ /dev/null @@ -1,35 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/swarm" - "golang.org/x/net/context" -) - -// TaskList returns the list of tasks. -func (cli *Client) TaskList(ctx context.Context, options types.TaskListOptions) ([]swarm.Task, error) { - query := url.Values{} - - if options.Filters.Len() > 0 { - filterJSON, err := filters.ToParam(options.Filters) - if err != nil { - return nil, err - } - - query.Set("filters", filterJSON) - } - - resp, err := cli.get(ctx, "/tasks", query, nil) - if err != nil { - return nil, err - } - - var tasks []swarm.Task - err = json.NewDecoder(resp.body).Decode(&tasks) - ensureReaderClosed(resp) - return tasks, err -} diff --git a/vendor/github.com/docker/docker/client/task_logs.go b/vendor/github.com/docker/docker/client/task_logs.go deleted file mode 100644 index 2ed19543a4..0000000000 --- a/vendor/github.com/docker/docker/client/task_logs.go +++ /dev/null @@ -1,52 +0,0 @@ -package client - -import ( - "io" - "net/url" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - timetypes "github.com/docker/docker/api/types/time" -) - -// TaskLogs returns the logs generated by a task in an io.ReadCloser. -// It's up to the caller to close the stream. -func (cli *Client) TaskLogs(ctx context.Context, taskID string, options types.ContainerLogsOptions) (io.ReadCloser, error) { - query := url.Values{} - if options.ShowStdout { - query.Set("stdout", "1") - } - - if options.ShowStderr { - query.Set("stderr", "1") - } - - if options.Since != "" { - ts, err := timetypes.GetTimestamp(options.Since, time.Now()) - if err != nil { - return nil, err - } - query.Set("since", ts) - } - - if options.Timestamps { - query.Set("timestamps", "1") - } - - if options.Details { - query.Set("details", "1") - } - - if options.Follow { - query.Set("follow", "1") - } - query.Set("tail", options.Tail) - - resp, err := cli.get(ctx, "/tasks/"+taskID+"/logs", query, nil) - if err != nil { - return nil, err - } - return resp.body, nil -} diff --git a/vendor/github.com/docker/docker/client/transport.go b/vendor/github.com/docker/docker/client/transport.go deleted file mode 100644 index 401ab15d30..0000000000 --- a/vendor/github.com/docker/docker/client/transport.go +++ /dev/null @@ -1,25 +0,0 @@ -package client - -import ( - "crypto/tls" - "net/http" -) - -// transportFunc allows us to inject a mock transport for testing. We define it -// here so we can detect the tlsconfig and return nil for only this type. -type transportFunc func(*http.Request) (*http.Response, error) - -func (tf transportFunc) RoundTrip(req *http.Request) (*http.Response, error) { - return tf(req) -} - -// resolveTLSConfig attempts to resolve the TLS configuration from the -// RoundTripper. -func resolveTLSConfig(transport http.RoundTripper) *tls.Config { - switch tr := transport.(type) { - case *http.Transport: - return tr.TLSClientConfig - default: - return nil - } -} diff --git a/vendor/github.com/docker/docker/client/utils.go b/vendor/github.com/docker/docker/client/utils.go deleted file mode 100644 index 23d520ecb8..0000000000 --- a/vendor/github.com/docker/docker/client/utils.go +++ /dev/null @@ -1,33 +0,0 @@ -package client - -import ( - "github.com/docker/docker/api/types/filters" - "net/url" - "regexp" -) - -var headerRegexp = regexp.MustCompile(`\ADocker/.+\s\((.+)\)\z`) - -// getDockerOS returns the operating system based on the server header from the daemon. -func getDockerOS(serverHeader string) string { - var osType string - matches := headerRegexp.FindStringSubmatch(serverHeader) - if len(matches) > 0 { - osType = matches[1] - } - return osType -} - -// getFiltersQuery returns a url query with "filters" query term, based on the -// filters provided. -func getFiltersQuery(f filters.Args) (url.Values, error) { - query := url.Values{} - if f.Len() > 0 { - filterJSON, err := filters.ToParam(f) - if err != nil { - return query, err - } - query.Set("filters", filterJSON) - } - return query, nil -} diff --git a/vendor/github.com/docker/docker/client/version.go b/vendor/github.com/docker/docker/client/version.go deleted file mode 100644 index 933ceb4a49..0000000000 --- a/vendor/github.com/docker/docker/client/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// ServerVersion returns information of the docker client and server host. -func (cli *Client) ServerVersion(ctx context.Context) (types.Version, error) { - resp, err := cli.get(ctx, "/version", nil, nil) - if err != nil { - return types.Version{}, err - } - - var server types.Version - err = json.NewDecoder(resp.body).Decode(&server) - ensureReaderClosed(resp) - return server, err -} diff --git a/vendor/github.com/docker/docker/client/volume_create.go b/vendor/github.com/docker/docker/client/volume_create.go deleted file mode 100644 index 9620c87cbf..0000000000 --- a/vendor/github.com/docker/docker/client/volume_create.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "encoding/json" - - "github.com/docker/docker/api/types" - volumetypes "github.com/docker/docker/api/types/volume" - "golang.org/x/net/context" -) - -// VolumeCreate creates a volume in the docker host. -func (cli *Client) VolumeCreate(ctx context.Context, options volumetypes.VolumesCreateBody) (types.Volume, error) { - var volume types.Volume - resp, err := cli.post(ctx, "/volumes/create", nil, options, nil) - if err != nil { - return volume, err - } - err = json.NewDecoder(resp.body).Decode(&volume) - ensureReaderClosed(resp) - return volume, err -} diff --git a/vendor/github.com/docker/docker/client/volume_inspect.go b/vendor/github.com/docker/docker/client/volume_inspect.go deleted file mode 100644 index 3860e9b22c..0000000000 --- a/vendor/github.com/docker/docker/client/volume_inspect.go +++ /dev/null @@ -1,38 +0,0 @@ -package client - -import ( - "bytes" - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/docker/docker/api/types" - "golang.org/x/net/context" -) - -// VolumeInspect returns the information about a specific volume in the docker host. -func (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) { - volume, _, err := cli.VolumeInspectWithRaw(ctx, volumeID) - return volume, err -} - -// VolumeInspectWithRaw returns the information about a specific volume in the docker host and its raw representation -func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) { - var volume types.Volume - resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil) - if err != nil { - if resp.statusCode == http.StatusNotFound { - return volume, nil, volumeNotFoundError{volumeID} - } - return volume, nil, err - } - defer ensureReaderClosed(resp) - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return volume, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&volume) - return volume, body, err -} diff --git a/vendor/github.com/docker/docker/client/volume_list.go b/vendor/github.com/docker/docker/client/volume_list.go deleted file mode 100644 index 32247ce115..0000000000 --- a/vendor/github.com/docker/docker/client/volume_list.go +++ /dev/null @@ -1,32 +0,0 @@ -package client - -import ( - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/filters" - volumetypes "github.com/docker/docker/api/types/volume" - "golang.org/x/net/context" -) - -// VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumesListOKBody, error) { - var volumes volumetypes.VolumesListOKBody - query := url.Values{} - - if filter.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - if err != nil { - return volumes, err - } - query.Set("filters", filterJSON) - } - resp, err := cli.get(ctx, "/volumes", query, nil) - if err != nil { - return volumes, err - } - - err = json.NewDecoder(resp.body).Decode(&volumes) - ensureReaderClosed(resp) - return volumes, err -} diff --git a/vendor/github.com/docker/docker/client/volume_prune.go b/vendor/github.com/docker/docker/client/volume_prune.go deleted file mode 100644 index 2e7fea7747..0000000000 --- a/vendor/github.com/docker/docker/client/volume_prune.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "golang.org/x/net/context" -) - -// VolumesPrune requests the daemon to delete unused data -func (cli *Client) VolumesPrune(ctx context.Context, pruneFilters filters.Args) (types.VolumesPruneReport, error) { - var report types.VolumesPruneReport - - if err := cli.NewVersionError("1.25", "volume prune"); err != nil { - return report, err - } - - query, err := getFiltersQuery(pruneFilters) - if err != nil { - return report, err - } - - serverResp, err := cli.post(ctx, "/volumes/prune", query, nil, nil) - if err != nil { - return report, err - } - defer ensureReaderClosed(serverResp) - - if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil { - return report, fmt.Errorf("Error retrieving volume prune report: %v", err) - } - - return report, nil -} diff --git a/vendor/github.com/docker/docker/client/volume_remove.go b/vendor/github.com/docker/docker/client/volume_remove.go deleted file mode 100644 index 6c26575b49..0000000000 --- a/vendor/github.com/docker/docker/client/volume_remove.go +++ /dev/null @@ -1,21 +0,0 @@ -package client - -import ( - "net/url" - - "github.com/docker/docker/api/types/versions" - "golang.org/x/net/context" -) - -// VolumeRemove removes a volume from the docker host. -func (cli *Client) VolumeRemove(ctx context.Context, volumeID string, force bool) error { - query := url.Values{} - if versions.GreaterThanOrEqualTo(cli.version, "1.25") { - if force { - query.Set("force", "1") - } - } - resp, err := cli.delete(ctx, "/volumes/"+volumeID, query, nil) - ensureReaderClosed(resp) - return err -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go b/vendor/github.com/docker/docker/pkg/ioutils/buffer.go deleted file mode 100644 index 3d737b3e19..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/buffer.go +++ /dev/null @@ -1,51 +0,0 @@ -package ioutils - -import ( - "errors" - "io" -) - -var errBufferFull = errors.New("buffer is full") - -type fixedBuffer struct { - buf []byte - pos int - lastRead int -} - -func (b *fixedBuffer) Write(p []byte) (int, error) { - n := copy(b.buf[b.pos:cap(b.buf)], p) - b.pos += n - - if n < len(p) { - if b.pos == cap(b.buf) { - return n, errBufferFull - } - return n, io.ErrShortWrite - } - return n, nil -} - -func (b *fixedBuffer) Read(p []byte) (int, error) { - n := copy(p, b.buf[b.lastRead:b.pos]) - b.lastRead += n - return n, nil -} - -func (b *fixedBuffer) Len() int { - return b.pos - b.lastRead -} - -func (b *fixedBuffer) Cap() int { - return cap(b.buf) -} - -func (b *fixedBuffer) Reset() { - b.pos = 0 - b.lastRead = 0 - b.buf = b.buf[:0] -} - -func (b *fixedBuffer) String() string { - return string(b.buf[b.lastRead:b.pos]) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go b/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go deleted file mode 100644 index 72a04f3491..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ /dev/null @@ -1,186 +0,0 @@ -package ioutils - -import ( - "errors" - "io" - "sync" -) - -// maxCap is the highest capacity to use in byte slices that buffer data. -const maxCap = 1e6 - -// minCap is the lowest capacity to use in byte slices that buffer data -const minCap = 64 - -// blockThreshold is the minimum number of bytes in the buffer which will cause -// a write to BytesPipe to block when allocating a new slice. -const blockThreshold = 1e6 - -var ( - // ErrClosed is returned when Write is called on a closed BytesPipe. - ErrClosed = errors.New("write to closed BytesPipe") - - bufPools = make(map[int]*sync.Pool) - bufPoolsLock sync.Mutex -) - -// BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). -// All written data may be read at most once. Also, BytesPipe allocates -// and releases new byte slices to adjust to current needs, so the buffer -// won't be overgrown after peak loads. -type BytesPipe struct { - mu sync.Mutex - wait *sync.Cond - buf []*fixedBuffer - bufLen int - closeErr error // error to return from next Read. set to nil if not closed. -} - -// NewBytesPipe creates new BytesPipe, initialized by specified slice. -// If buf is nil, then it will be initialized with slice which cap is 64. -// buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). -func NewBytesPipe() *BytesPipe { - bp := &BytesPipe{} - bp.buf = append(bp.buf, getBuffer(minCap)) - bp.wait = sync.NewCond(&bp.mu) - return bp -} - -// Write writes p to BytesPipe. -// It can allocate new []byte slices in a process of writing. -func (bp *BytesPipe) Write(p []byte) (int, error) { - bp.mu.Lock() - - written := 0 -loop0: - for { - if bp.closeErr != nil { - bp.mu.Unlock() - return written, ErrClosed - } - - if len(bp.buf) == 0 { - bp.buf = append(bp.buf, getBuffer(64)) - } - // get the last buffer - b := bp.buf[len(bp.buf)-1] - - n, err := b.Write(p) - written += n - bp.bufLen += n - - // errBufferFull is an error we expect to get if the buffer is full - if err != nil && err != errBufferFull { - bp.wait.Broadcast() - bp.mu.Unlock() - return written, err - } - - // if there was enough room to write all then break - if len(p) == n { - break - } - - // more data: write to the next slice - p = p[n:] - - // make sure the buffer doesn't grow too big from this write - for bp.bufLen >= blockThreshold { - bp.wait.Wait() - if bp.closeErr != nil { - continue loop0 - } - } - - // add new byte slice to the buffers slice and continue writing - nextCap := b.Cap() * 2 - if nextCap > maxCap { - nextCap = maxCap - } - bp.buf = append(bp.buf, getBuffer(nextCap)) - } - bp.wait.Broadcast() - bp.mu.Unlock() - return written, nil -} - -// CloseWithError causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) CloseWithError(err error) error { - bp.mu.Lock() - if err != nil { - bp.closeErr = err - } else { - bp.closeErr = io.EOF - } - bp.wait.Broadcast() - bp.mu.Unlock() - return nil -} - -// Close causes further reads from a BytesPipe to return immediately. -func (bp *BytesPipe) Close() error { - return bp.CloseWithError(nil) -} - -// Read reads bytes from BytesPipe. -// Data could be read only once. -func (bp *BytesPipe) Read(p []byte) (n int, err error) { - bp.mu.Lock() - if bp.bufLen == 0 { - if bp.closeErr != nil { - bp.mu.Unlock() - return 0, bp.closeErr - } - bp.wait.Wait() - if bp.bufLen == 0 && bp.closeErr != nil { - err := bp.closeErr - bp.mu.Unlock() - return 0, err - } - } - - for bp.bufLen > 0 { - b := bp.buf[0] - read, _ := b.Read(p) // ignore error since fixedBuffer doesn't really return an error - n += read - bp.bufLen -= read - - if b.Len() == 0 { - // it's empty so return it to the pool and move to the next one - returnBuffer(b) - bp.buf[0] = nil - bp.buf = bp.buf[1:] - } - - if len(p) == read { - break - } - - p = p[read:] - } - - bp.wait.Broadcast() - bp.mu.Unlock() - return -} - -func returnBuffer(b *fixedBuffer) { - b.Reset() - bufPoolsLock.Lock() - pool := bufPools[b.Cap()] - bufPoolsLock.Unlock() - if pool != nil { - pool.Put(b) - } -} - -func getBuffer(size int) *fixedBuffer { - bufPoolsLock.Lock() - pool, ok := bufPools[size] - if !ok { - pool = &sync.Pool{New: func() interface{} { return &fixedBuffer{buf: make([]byte, 0, size)} }} - bufPools[size] = pool - } - bufPoolsLock.Unlock() - return pool.Get().(*fixedBuffer) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/fmt.go b/vendor/github.com/docker/docker/pkg/ioutils/fmt.go deleted file mode 100644 index 0b04b0ba3e..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/fmt.go +++ /dev/null @@ -1,22 +0,0 @@ -package ioutils - -import ( - "fmt" - "io" -) - -// FprintfIfNotEmpty prints the string value if it's not empty -func FprintfIfNotEmpty(w io.Writer, format, value string) (int, error) { - if value != "" { - return fmt.Fprintf(w, format, value) - } - return 0, nil -} - -// FprintfIfTrue prints the boolean value if it's true -func FprintfIfTrue(w io.Writer, format string, ok bool) (int, error) { - if ok { - return fmt.Fprintf(w, format, ok) - } - return 0, nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go b/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go deleted file mode 100644 index a56c462651..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go +++ /dev/null @@ -1,162 +0,0 @@ -package ioutils - -import ( - "io" - "io/ioutil" - "os" - "path/filepath" -) - -// NewAtomicFileWriter returns WriteCloser so that writing to it writes to a -// temporary file and closing it atomically changes the temporary file to -// destination path. Writing and closing concurrently is not allowed. -func NewAtomicFileWriter(filename string, perm os.FileMode) (io.WriteCloser, error) { - f, err := ioutil.TempFile(filepath.Dir(filename), ".tmp-"+filepath.Base(filename)) - if err != nil { - return nil, err - } - - abspath, err := filepath.Abs(filename) - if err != nil { - return nil, err - } - return &atomicFileWriter{ - f: f, - fn: abspath, - perm: perm, - }, nil -} - -// AtomicWriteFile atomically writes data to a file named by filename. -func AtomicWriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := NewAtomicFileWriter(filename, perm) - if err != nil { - return err - } - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - f.(*atomicFileWriter).writeErr = err - } - if err1 := f.Close(); err == nil { - err = err1 - } - return err -} - -type atomicFileWriter struct { - f *os.File - fn string - writeErr error - perm os.FileMode -} - -func (w *atomicFileWriter) Write(dt []byte) (int, error) { - n, err := w.f.Write(dt) - if err != nil { - w.writeErr = err - } - return n, err -} - -func (w *atomicFileWriter) Close() (retErr error) { - defer func() { - if retErr != nil || w.writeErr != nil { - os.Remove(w.f.Name()) - } - }() - if err := w.f.Sync(); err != nil { - w.f.Close() - return err - } - if err := w.f.Close(); err != nil { - return err - } - if err := os.Chmod(w.f.Name(), w.perm); err != nil { - return err - } - if w.writeErr == nil { - return os.Rename(w.f.Name(), w.fn) - } - return nil -} - -// AtomicWriteSet is used to atomically write a set -// of files and ensure they are visible at the same time. -// Must be committed to a new directory. -type AtomicWriteSet struct { - root string -} - -// NewAtomicWriteSet creates a new atomic write set to -// atomically create a set of files. The given directory -// is used as the base directory for storing files before -// commit. If no temporary directory is given the system -// default is used. -func NewAtomicWriteSet(tmpDir string) (*AtomicWriteSet, error) { - td, err := ioutil.TempDir(tmpDir, "write-set-") - if err != nil { - return nil, err - } - - return &AtomicWriteSet{ - root: td, - }, nil -} - -// WriteFile writes a file to the set, guaranteeing the file -// has been synced. -func (ws *AtomicWriteSet) WriteFile(filename string, data []byte, perm os.FileMode) error { - f, err := ws.FileWriter(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 -} - -type syncFileCloser struct { - *os.File -} - -func (w syncFileCloser) Close() error { - err := w.File.Sync() - if err1 := w.File.Close(); err == nil { - err = err1 - } - return err -} - -// FileWriter opens a file writer inside the set. The file -// should be synced and closed before calling commit. -func (ws *AtomicWriteSet) FileWriter(name string, flag int, perm os.FileMode) (io.WriteCloser, error) { - f, err := os.OpenFile(filepath.Join(ws.root, name), flag, perm) - if err != nil { - return nil, err - } - return syncFileCloser{f}, nil -} - -// Cancel cancels the set and removes all temporary data -// created in the set. -func (ws *AtomicWriteSet) Cancel() error { - return os.RemoveAll(ws.root) -} - -// Commit moves all created files to the target directory. The -// target directory must not exist and the parent of the target -// directory must exist. -func (ws *AtomicWriteSet) Commit(target string) error { - return os.Rename(ws.root, target) -} - -// String returns the location the set is writing to. -func (ws *AtomicWriteSet) String() string { - return ws.root -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/multireader.go b/vendor/github.com/docker/docker/pkg/ioutils/multireader.go deleted file mode 100644 index edb043ddc3..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/multireader.go +++ /dev/null @@ -1,224 +0,0 @@ -package ioutils - -import ( - "bytes" - "fmt" - "io" - "os" -) - -type pos struct { - idx int - offset int64 -} - -type multiReadSeeker struct { - readers []io.ReadSeeker - pos *pos - posIdx map[io.ReadSeeker]int -} - -func (r *multiReadSeeker) Seek(offset int64, whence int) (int64, error) { - var tmpOffset int64 - switch whence { - case os.SEEK_SET: - for i, rdr := range r.readers { - // get size of the current reader - s, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - - if offset > tmpOffset+s { - if i == len(r.readers)-1 { - rdrOffset := s + (offset - tmpOffset) - if _, err := rdr.Seek(rdrOffset, os.SEEK_SET); err != nil { - return -1, err - } - r.pos = &pos{i, rdrOffset} - return offset, nil - } - - tmpOffset += s - continue - } - - rdrOffset := offset - tmpOffset - idx := i - - rdr.Seek(rdrOffset, os.SEEK_SET) - // make sure all following readers are at 0 - for _, rdr := range r.readers[i+1:] { - rdr.Seek(0, os.SEEK_SET) - } - - if rdrOffset == s && i != len(r.readers)-1 { - idx++ - rdrOffset = 0 - } - r.pos = &pos{idx, rdrOffset} - return offset, nil - } - case os.SEEK_END: - for _, rdr := range r.readers { - s, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - tmpOffset += s - } - r.Seek(tmpOffset+offset, os.SEEK_SET) - return tmpOffset + offset, nil - case os.SEEK_CUR: - if r.pos == nil { - return r.Seek(offset, os.SEEK_SET) - } - // Just return the current offset - if offset == 0 { - return r.getCurOffset() - } - - curOffset, err := r.getCurOffset() - if err != nil { - return -1, err - } - rdr, rdrOffset, err := r.getReaderForOffset(curOffset + offset) - if err != nil { - return -1, err - } - - r.pos = &pos{r.posIdx[rdr], rdrOffset} - return curOffset + offset, nil - default: - return -1, fmt.Errorf("Invalid whence: %d", whence) - } - - return -1, fmt.Errorf("Error seeking for whence: %d, offset: %d", whence, offset) -} - -func (r *multiReadSeeker) getReaderForOffset(offset int64) (io.ReadSeeker, int64, error) { - - var offsetTo int64 - - for _, rdr := range r.readers { - size, err := getReadSeekerSize(rdr) - if err != nil { - return nil, -1, err - } - if offsetTo+size > offset { - return rdr, offset - offsetTo, nil - } - if rdr == r.readers[len(r.readers)-1] { - return rdr, offsetTo + offset, nil - } - offsetTo += size - } - - return nil, 0, nil -} - -func (r *multiReadSeeker) getCurOffset() (int64, error) { - var totalSize int64 - for _, rdr := range r.readers[:r.pos.idx+1] { - if r.posIdx[rdr] == r.pos.idx { - totalSize += r.pos.offset - break - } - - size, err := getReadSeekerSize(rdr) - if err != nil { - return -1, fmt.Errorf("error getting seeker size: %v", err) - } - totalSize += size - } - return totalSize, nil -} - -func (r *multiReadSeeker) getOffsetToReader(rdr io.ReadSeeker) (int64, error) { - var offset int64 - for _, r := range r.readers { - if r == rdr { - break - } - - size, err := getReadSeekerSize(rdr) - if err != nil { - return -1, err - } - offset += size - } - return offset, nil -} - -func (r *multiReadSeeker) Read(b []byte) (int, error) { - if r.pos == nil { - // make sure all readers are at 0 - r.Seek(0, os.SEEK_SET) - } - - bLen := int64(len(b)) - buf := bytes.NewBuffer(nil) - var rdr io.ReadSeeker - - for _, rdr = range r.readers[r.pos.idx:] { - readBytes, err := io.CopyN(buf, rdr, bLen) - if err != nil && err != io.EOF { - return -1, err - } - bLen -= readBytes - - if bLen == 0 { - break - } - } - - rdrPos, err := rdr.Seek(0, os.SEEK_CUR) - if err != nil { - return -1, err - } - r.pos = &pos{r.posIdx[rdr], rdrPos} - return buf.Read(b) -} - -func getReadSeekerSize(rdr io.ReadSeeker) (int64, error) { - // save the current position - pos, err := rdr.Seek(0, os.SEEK_CUR) - if err != nil { - return -1, err - } - - // get the size - size, err := rdr.Seek(0, os.SEEK_END) - if err != nil { - return -1, err - } - - // reset the position - if _, err := rdr.Seek(pos, os.SEEK_SET); err != nil { - return -1, err - } - return size, nil -} - -// MultiReadSeeker returns a ReadSeeker that's the logical concatenation of the provided -// input readseekers. After calling this method the initial position is set to the -// beginning of the first ReadSeeker. At the end of a ReadSeeker, Read always advances -// to the beginning of the next ReadSeeker and returns EOF at the end of the last ReadSeeker. -// Seek can be used over the sum of lengths of all readseekers. -// -// When a MultiReadSeeker is used, no Read and Seek operations should be made on -// its ReadSeeker components. Also, users should make no assumption on the state -// of individual readseekers while the MultiReadSeeker is used. -func MultiReadSeeker(readers ...io.ReadSeeker) io.ReadSeeker { - if len(readers) == 1 { - return readers[0] - } - idx := make(map[io.ReadSeeker]int) - for i, rdr := range readers { - idx[rdr] = i - } - return &multiReadSeeker{ - readers: readers, - posIdx: idx, - } -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/readers.go b/vendor/github.com/docker/docker/pkg/ioutils/readers.go deleted file mode 100644 index 63f3c07f46..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/readers.go +++ /dev/null @@ -1,154 +0,0 @@ -package ioutils - -import ( - "crypto/sha256" - "encoding/hex" - "io" - - "golang.org/x/net/context" -) - -type readCloserWrapper struct { - io.Reader - closer func() error -} - -func (r *readCloserWrapper) Close() error { - return r.closer() -} - -// NewReadCloserWrapper returns a new io.ReadCloser. -func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { - return &readCloserWrapper{ - Reader: r, - closer: closer, - } -} - -type readerErrWrapper struct { - reader io.Reader - closer func() -} - -func (r *readerErrWrapper) Read(p []byte) (int, error) { - n, err := r.reader.Read(p) - if err != nil { - r.closer() - } - return n, err -} - -// NewReaderErrWrapper returns a new io.Reader. -func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { - return &readerErrWrapper{ - reader: r, - closer: closer, - } -} - -// HashData returns the sha256 sum of src. -func HashData(src io.Reader) (string, error) { - h := sha256.New() - if _, err := io.Copy(h, src); err != nil { - return "", err - } - return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil -} - -// OnEOFReader wraps an io.ReadCloser and a function -// the function will run at the end of file or close the file. -type OnEOFReader struct { - Rc io.ReadCloser - Fn func() -} - -func (r *OnEOFReader) Read(p []byte) (n int, err error) { - n, err = r.Rc.Read(p) - if err == io.EOF { - r.runFunc() - } - return -} - -// Close closes the file and run the function. -func (r *OnEOFReader) Close() error { - err := r.Rc.Close() - r.runFunc() - return err -} - -func (r *OnEOFReader) runFunc() { - if fn := r.Fn; fn != nil { - fn() - r.Fn = nil - } -} - -// cancelReadCloser wraps an io.ReadCloser with a context for cancelling read -// operations. -type cancelReadCloser struct { - cancel func() - pR *io.PipeReader // Stream to read from - pW *io.PipeWriter -} - -// NewCancelReadCloser creates a wrapper that closes the ReadCloser when the -// context is cancelled. The returned io.ReadCloser must be closed when it is -// no longer needed. -func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { - pR, pW := io.Pipe() - - // Create a context used to signal when the pipe is closed - doneCtx, cancel := context.WithCancel(context.Background()) - - p := &cancelReadCloser{ - cancel: cancel, - pR: pR, - pW: pW, - } - - go func() { - _, err := io.Copy(pW, in) - select { - case <-ctx.Done(): - // If the context was closed, p.closeWithError - // was already called. Calling it again would - // change the error that Read returns. - default: - p.closeWithError(err) - } - in.Close() - }() - go func() { - for { - select { - case <-ctx.Done(): - p.closeWithError(ctx.Err()) - case <-doneCtx.Done(): - return - } - } - }() - - return p -} - -// Read wraps the Read method of the pipe that provides data from the wrapped -// ReadCloser. -func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { - return p.pR.Read(buf) -} - -// closeWithError closes the wrapper and its underlying reader. It will -// cause future calls to Read to return err. -func (p *cancelReadCloser) closeWithError(err error) { - p.pW.CloseWithError(err) - p.cancel() -} - -// Close closes the wrapper its underlying reader. It will cause -// future calls to Read to return io.EOF. -func (p *cancelReadCloser) Close() error { - p.closeWithError(io.EOF) - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go deleted file mode 100644 index 1539ad21b5..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package ioutils - -import "io/ioutil" - -// TempDir on Unix systems is equivalent to ioutil.TempDir. -func TempDir(dir, prefix string) (string, error) { - return ioutil.TempDir(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go deleted file mode 100644 index c258e5fdd8..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build windows - -package ioutils - -import ( - "io/ioutil" - - "github.com/docker/docker/pkg/longpath" -) - -// TempDir is the equivalent of ioutil.TempDir, except that the result is in Windows longpath format. -func TempDir(dir, prefix string) (string, error) { - tempDir, err := ioutil.TempDir(dir, prefix) - if err != nil { - return "", err - } - return longpath.AddPrefix(tempDir), nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go b/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go deleted file mode 100644 index 52a4901ade..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go +++ /dev/null @@ -1,92 +0,0 @@ -package ioutils - -import ( - "io" - "sync" -) - -// WriteFlusher wraps the Write and Flush operation ensuring that every write -// is a flush. In addition, the Close method can be called to intercept -// Read/Write calls if the targets lifecycle has already ended. -type WriteFlusher struct { - w io.Writer - flusher flusher - flushed chan struct{} - flushedOnce sync.Once - closed chan struct{} - closeLock sync.Mutex -} - -type flusher interface { - Flush() -} - -var errWriteFlusherClosed = io.EOF - -func (wf *WriteFlusher) Write(b []byte) (n int, err error) { - select { - case <-wf.closed: - return 0, errWriteFlusherClosed - default: - } - - n, err = wf.w.Write(b) - wf.Flush() // every write is a flush. - return n, err -} - -// Flush the stream immediately. -func (wf *WriteFlusher) Flush() { - select { - case <-wf.closed: - return - default: - } - - wf.flushedOnce.Do(func() { - close(wf.flushed) - }) - wf.flusher.Flush() -} - -// Flushed returns the state of flushed. -// If it's flushed, return true, or else it return false. -func (wf *WriteFlusher) Flushed() bool { - // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to - // be used to detect whether or a response code has been issued or not. - // Another hook should be used instead. - var flushed bool - select { - case <-wf.flushed: - flushed = true - default: - } - return flushed -} - -// Close closes the write flusher, disallowing any further writes to the -// target. After the flusher is closed, all calls to write or flush will -// result in an error. -func (wf *WriteFlusher) Close() error { - wf.closeLock.Lock() - defer wf.closeLock.Unlock() - - select { - case <-wf.closed: - return errWriteFlusherClosed - default: - close(wf.closed) - } - return nil -} - -// NewWriteFlusher returns a new WriteFlusher. -func NewWriteFlusher(w io.Writer) *WriteFlusher { - var fl flusher - if f, ok := w.(flusher); ok { - fl = f - } else { - fl = &NopFlusher{} - } - return &WriteFlusher{w: w, flusher: fl, closed: make(chan struct{}), flushed: make(chan struct{})} -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/writers.go b/vendor/github.com/docker/docker/pkg/ioutils/writers.go deleted file mode 100644 index ccc7f9c23e..0000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writers.go +++ /dev/null @@ -1,66 +0,0 @@ -package ioutils - -import "io" - -// NopWriter represents a type which write operation is nop. -type NopWriter struct{} - -func (*NopWriter) Write(buf []byte) (int, error) { - return len(buf), nil -} - -type nopWriteCloser struct { - io.Writer -} - -func (w *nopWriteCloser) Close() error { return nil } - -// NopWriteCloser returns a nopWriteCloser. -func NopWriteCloser(w io.Writer) io.WriteCloser { - return &nopWriteCloser{w} -} - -// NopFlusher represents a type which flush operation is nop. -type NopFlusher struct{} - -// Flush is a nop operation. -func (f *NopFlusher) Flush() {} - -type writeCloserWrapper struct { - io.Writer - closer func() error -} - -func (r *writeCloserWrapper) Close() error { - return r.closer() -} - -// NewWriteCloserWrapper returns a new io.WriteCloser. -func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { - return &writeCloserWrapper{ - Writer: r, - closer: closer, - } -} - -// WriteCounter wraps a concrete io.Writer and hold a count of the number -// of bytes written to the writer during a "session". -// This can be convenient when write return is masked -// (e.g., json.Encoder.Encode()) -type WriteCounter struct { - Count int64 - Writer io.Writer -} - -// NewWriteCounter returns a new WriteCounter. -func NewWriteCounter(w io.Writer) *WriteCounter { - return &WriteCounter{ - Writer: w, - } -} - -func (wc *WriteCounter) Write(p []byte) (count int, err error) { - count, err = wc.Writer.Write(p) - wc.Count += int64(count) - return -} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go deleted file mode 100644 index 4734c31119..0000000000 --- a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go +++ /dev/null @@ -1,42 +0,0 @@ -package jsonlog - -import ( - "encoding/json" - "fmt" - "time" -) - -// JSONLog represents a log message, typically a single entry from a given log stream. -// JSONLogs can be easily serialized to and from JSON and support custom formatting. -type JSONLog struct { - // Log is the log message - Log string `json:"log,omitempty"` - // Stream is the log source - Stream string `json:"stream,omitempty"` - // Created is the created timestamp of log - Created time.Time `json:"time"` - // Attrs is the list of extra attributes provided by the user - Attrs map[string]string `json:"attrs,omitempty"` -} - -// Format returns the log formatted according to format -// If format is nil, returns the log message -// If format is json, returns the log marshaled in json format -// By default, returns the log with the log time formatted according to format. -func (jl *JSONLog) Format(format string) (string, error) { - if format == "" { - return jl.Log, nil - } - if format == "json" { - m, err := json.Marshal(jl) - return string(m), err - } - return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil -} - -// Reset resets the log to nil. -func (jl *JSONLog) Reset() { - jl.Log = "" - jl.Stream = "" - jl.Created = time.Time{} -} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go deleted file mode 100644 index 83ce684a8e..0000000000 --- a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go +++ /dev/null @@ -1,178 +0,0 @@ -// This code was initially generated by ffjson -// This code was generated via the following steps: -// $ go get -u github.com/pquerna/ffjson -// $ make BIND_DIR=. shell -// $ ffjson pkg/jsonlog/jsonlog.go -// $ mv pkg/jsonglog/jsonlog_ffjson.go pkg/jsonlog/jsonlog_marshalling.go -// -// It has been modified to improve the performance of time marshalling to JSON -// and to clean it up. -// Should this code need to be regenerated when the JSONLog struct is changed, -// the relevant changes which have been made are: -// import ( -// "bytes" -//- -// "unicode/utf8" -// ) -// -// func (mj *JSONLog) MarshalJSON() ([]byte, error) { -//@@ -20,13 +16,13 @@ func (mj *JSONLog) MarshalJSON() ([]byte, error) { -// } -// return buf.Bytes(), nil -// } -//+ -// func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { -//- var err error -//- var obj []byte -//- var first bool = true -//- _ = obj -//- _ = err -//- _ = first -//+ var ( -//+ err error -//+ timestamp string -//+ first bool = true -//+ ) -// buf.WriteString(`{`) -// if len(mj.Log) != 0 { -// if first == true { -//@@ -52,11 +48,11 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { -// buf.WriteString(`,`) -// } -// buf.WriteString(`"time":`) -//- obj, err = mj.Created.MarshalJSON() -//+ timestamp, err = FastTimeMarshalJSON(mj.Created) -// if err != nil { -// return err -// } -//- buf.Write(obj) -//+ buf.WriteString(timestamp) -// buf.WriteString(`}`) -// return nil -// } -// @@ -81,9 +81,10 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { -// if len(mj.Log) != 0 { -// - if first == true { -// - first = false -// - } else { -// - buf.WriteString(`,`) -// - } -// + first = false -// buf.WriteString(`"log":`) -// ffjsonWriteJSONString(buf, mj.Log) -// } - -package jsonlog - -import ( - "bytes" - "unicode/utf8" -) - -// MarshalJSON marshals the JSONLog. -func (mj *JSONLog) MarshalJSON() ([]byte, error) { - var buf bytes.Buffer - buf.Grow(1024) - if err := mj.MarshalJSONBuf(&buf); err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// MarshalJSONBuf marshals the JSONLog and stores the result to a bytes.Buffer. -func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { - var ( - err error - timestamp string - first = true - ) - buf.WriteString(`{`) - if len(mj.Log) != 0 { - first = false - buf.WriteString(`"log":`) - ffjsonWriteJSONString(buf, mj.Log) - } - if len(mj.Stream) != 0 { - if first { - first = false - } else { - buf.WriteString(`,`) - } - buf.WriteString(`"stream":`) - ffjsonWriteJSONString(buf, mj.Stream) - } - if !first { - buf.WriteString(`,`) - } - buf.WriteString(`"time":`) - timestamp, err = FastTimeMarshalJSON(mj.Created) - if err != nil { - return err - } - buf.WriteString(timestamp) - buf.WriteString(`}`) - return nil -} - -func ffjsonWriteJSONString(buf *bytes.Buffer, s string) { - const hex = "0123456789abcdef" - - buf.WriteByte('"') - start := 0 - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { - i++ - continue - } - if start < i { - buf.WriteString(s[start:i]) - } - switch b { - case '\\', '"': - buf.WriteByte('\\') - buf.WriteByte(b) - case '\n': - buf.WriteByte('\\') - buf.WriteByte('n') - case '\r': - buf.WriteByte('\\') - buf.WriteByte('r') - default: - - buf.WriteString(`\u00`) - buf.WriteByte(hex[b>>4]) - buf.WriteByte(hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRuneInString(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - buf.WriteString(s[start:i]) - } - buf.WriteString(`\ufffd`) - i += size - start = i - continue - } - - if c == '\u2028' || c == '\u2029' { - if start < i { - buf.WriteString(s[start:i]) - } - buf.WriteString(`\u202`) - buf.WriteByte(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - buf.WriteString(s[start:]) - } - buf.WriteByte('"') -} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go b/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go deleted file mode 100644 index 0ba716f261..0000000000 --- a/vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go +++ /dev/null @@ -1,122 +0,0 @@ -package jsonlog - -import ( - "bytes" - "encoding/json" - "unicode/utf8" -) - -// JSONLogs is based on JSONLog. -// It allows marshalling JSONLog from Log as []byte -// and an already marshalled Created timestamp. -type JSONLogs struct { - Log []byte `json:"log,omitempty"` - Stream string `json:"stream,omitempty"` - Created string `json:"time"` - - // json-encoded bytes - RawAttrs json.RawMessage `json:"attrs,omitempty"` -} - -// MarshalJSONBuf is based on the same method from JSONLog -// It has been modified to take into account the necessary changes. -func (mj *JSONLogs) MarshalJSONBuf(buf *bytes.Buffer) error { - var first = true - - buf.WriteString(`{`) - if len(mj.Log) != 0 { - first = false - buf.WriteString(`"log":`) - ffjsonWriteJSONBytesAsString(buf, mj.Log) - } - if len(mj.Stream) != 0 { - if first { - first = false - } else { - buf.WriteString(`,`) - } - buf.WriteString(`"stream":`) - ffjsonWriteJSONString(buf, mj.Stream) - } - if len(mj.RawAttrs) > 0 { - if first { - first = false - } else { - buf.WriteString(`,`) - } - buf.WriteString(`"attrs":`) - buf.Write(mj.RawAttrs) - } - if !first { - buf.WriteString(`,`) - } - buf.WriteString(`"time":`) - buf.WriteString(mj.Created) - buf.WriteString(`}`) - return nil -} - -// This is based on ffjsonWriteJSONBytesAsString. It has been changed -// to accept a string passed as a slice of bytes. -func ffjsonWriteJSONBytesAsString(buf *bytes.Buffer, s []byte) { - const hex = "0123456789abcdef" - - buf.WriteByte('"') - start := 0 - for i := 0; i < len(s); { - if b := s[i]; b < utf8.RuneSelf { - if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' { - i++ - continue - } - if start < i { - buf.Write(s[start:i]) - } - switch b { - case '\\', '"': - buf.WriteByte('\\') - buf.WriteByte(b) - case '\n': - buf.WriteByte('\\') - buf.WriteByte('n') - case '\r': - buf.WriteByte('\\') - buf.WriteByte('r') - default: - - buf.WriteString(`\u00`) - buf.WriteByte(hex[b>>4]) - buf.WriteByte(hex[b&0xF]) - } - i++ - start = i - continue - } - c, size := utf8.DecodeRune(s[i:]) - if c == utf8.RuneError && size == 1 { - if start < i { - buf.Write(s[start:i]) - } - buf.WriteString(`\ufffd`) - i += size - start = i - continue - } - - if c == '\u2028' || c == '\u2029' { - if start < i { - buf.Write(s[start:i]) - } - buf.WriteString(`\u202`) - buf.WriteByte(hex[c&0xF]) - i += size - start = i - continue - } - i += size - } - if start < len(s) { - buf.Write(s[start:]) - } - buf.WriteByte('"') -} diff --git a/vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go b/vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go deleted file mode 100644 index 2117338149..0000000000 --- a/vendor/github.com/docker/docker/pkg/jsonlog/time_marshalling.go +++ /dev/null @@ -1,27 +0,0 @@ -// Package jsonlog provides helper functions to parse and print time (time.Time) as JSON. -package jsonlog - -import ( - "errors" - "time" -) - -const ( - // RFC3339NanoFixed is our own version of RFC339Nano because we want one - // that pads the nano seconds part with zeros to ensure - // the timestamps are aligned in the logs. - RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" - // JSONFormat is the format used by FastMarshalJSON - JSONFormat = `"` + time.RFC3339Nano + `"` -) - -// FastTimeMarshalJSON avoids one of the extra allocations that -// time.MarshalJSON is making. -func FastTimeMarshalJSON(t time.Time) (string, error) { - if y := t.Year(); y < 0 || y >= 10000 { - // RFC 3339 is clear that years are 4 digits exactly. - // See golang.org/issue/4556#c15 for more discussion. - return "", errors.New("time.MarshalJSON: year outside of range [0,9999]") - } - return t.Format(JSONFormat), nil -} diff --git a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go b/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go deleted file mode 100644 index 4fb2b62b11..0000000000 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ /dev/null @@ -1,296 +0,0 @@ -package jsonmessage - -import ( - "encoding/json" - "fmt" - "io" - "os" - "strings" - "time" - - "github.com/Nvveen/Gotty" - "github.com/docker/docker/pkg/jsonlog" - "github.com/docker/docker/pkg/term" - "github.com/docker/go-units" -) - -// JSONError wraps a concrete Code and Message, `Code` is -// is an integer error code, `Message` is the error message. -type JSONError struct { - Code int `json:"code,omitempty"` - Message string `json:"message,omitempty"` -} - -func (e *JSONError) Error() string { - return e.Message -} - -// JSONProgress describes a Progress. terminalFd is the fd of the current terminal, -// Start is the initial value for the operation. Current is the current status and -// value of the progress made towards Total. Total is the end value describing when -// we made 100% progress for an operation. -type JSONProgress struct { - terminalFd uintptr - Current int64 `json:"current,omitempty"` - Total int64 `json:"total,omitempty"` - Start int64 `json:"start,omitempty"` - // If true, don't show xB/yB - HideCounts bool `json:"hidecounts,omitempty"` -} - -func (p *JSONProgress) String() string { - var ( - width = 200 - pbBox string - numbersBox string - timeLeftBox string - ) - - ws, err := term.GetWinsize(p.terminalFd) - if err == nil { - width = int(ws.Width) - } - - if p.Current <= 0 && p.Total <= 0 { - return "" - } - current := units.HumanSize(float64(p.Current)) - if p.Total <= 0 { - return fmt.Sprintf("%8v", current) - } - total := units.HumanSize(float64(p.Total)) - percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 - if percentage > 50 { - percentage = 50 - } - if width > 110 { - // this number can't be negative gh#7136 - numSpaces := 0 - if 50-percentage > 0 { - numSpaces = 50 - percentage - } - pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) - } - - if !p.HideCounts { - numbersBox = fmt.Sprintf("%8v/%v", current, total) - - if p.Current > p.Total { - // remove total display if the reported current is wonky. - numbersBox = fmt.Sprintf("%8v", current) - } - } - - if p.Current > 0 && p.Start > 0 && percentage < 50 { - fromStart := time.Now().UTC().Sub(time.Unix(p.Start, 0)) - perEntry := fromStart / time.Duration(p.Current) - left := time.Duration(p.Total-p.Current) * perEntry - left = (left / time.Second) * time.Second - - if width > 50 { - timeLeftBox = " " + left.String() - } - } - return pbBox + numbersBox + timeLeftBox -} - -// JSONMessage defines a message struct. It describes -// the created time, where it from, status, ID of the -// message. It's used for docker events. -type JSONMessage struct { - Stream string `json:"stream,omitempty"` - Status string `json:"status,omitempty"` - Progress *JSONProgress `json:"progressDetail,omitempty"` - ProgressMessage string `json:"progress,omitempty"` //deprecated - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - Time int64 `json:"time,omitempty"` - TimeNano int64 `json:"timeNano,omitempty"` - Error *JSONError `json:"errorDetail,omitempty"` - ErrorMessage string `json:"error,omitempty"` //deprecated - // Aux contains out-of-band data, such as digests for push signing. - Aux *json.RawMessage `json:"aux,omitempty"` -} - -/* Satisfied by gotty.TermInfo as well as noTermInfo from below */ -type termInfo interface { - Parse(attr string, params ...interface{}) (string, error) -} - -type noTermInfo struct{} // canary used when no terminfo. - -func (ti *noTermInfo) Parse(attr string, params ...interface{}) (string, error) { - return "", fmt.Errorf("noTermInfo") -} - -func clearLine(out io.Writer, ti termInfo) { - // el2 (clear whole line) is not exposed by terminfo. - - // First clear line from beginning to cursor - if attr, err := ti.Parse("el1"); err == nil { - fmt.Fprintf(out, "%s", attr) - } else { - fmt.Fprintf(out, "\x1b[1K") - } - // Then clear line from cursor to end - if attr, err := ti.Parse("el"); err == nil { - fmt.Fprintf(out, "%s", attr) - } else { - fmt.Fprintf(out, "\x1b[K") - } -} - -func cursorUp(out io.Writer, ti termInfo, l int) { - if l == 0 { // Should never be the case, but be tolerant - return - } - if attr, err := ti.Parse("cuu", l); err == nil { - fmt.Fprintf(out, "%s", attr) - } else { - fmt.Fprintf(out, "\x1b[%dA", l) - } -} - -func cursorDown(out io.Writer, ti termInfo, l int) { - if l == 0 { // Should never be the case, but be tolerant - return - } - if attr, err := ti.Parse("cud", l); err == nil { - fmt.Fprintf(out, "%s", attr) - } else { - fmt.Fprintf(out, "\x1b[%dB", l) - } -} - -// Display displays the JSONMessage to `out`. `termInfo` is non-nil if `out` -// is a terminal. If this is the case, it will erase the entire current line -// when displaying the progressbar. -func (jm *JSONMessage) Display(out io.Writer, termInfo termInfo) error { - if jm.Error != nil { - if jm.Error.Code == 401 { - return fmt.Errorf("Authentication is required.") - } - return jm.Error - } - var endl string - if termInfo != nil && jm.Stream == "" && jm.Progress != nil { - clearLine(out, termInfo) - endl = "\r" - fmt.Fprintf(out, endl) - } else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal - return nil - } - if jm.TimeNano != 0 { - fmt.Fprintf(out, "%s ", time.Unix(0, jm.TimeNano).Format(jsonlog.RFC3339NanoFixed)) - } else if jm.Time != 0 { - fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(jsonlog.RFC3339NanoFixed)) - } - if jm.ID != "" { - fmt.Fprintf(out, "%s: ", jm.ID) - } - if jm.From != "" { - fmt.Fprintf(out, "(from %s) ", jm.From) - } - if jm.Progress != nil && termInfo != nil { - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl) - } else if jm.ProgressMessage != "" { //deprecated - fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl) - } else if jm.Stream != "" { - fmt.Fprintf(out, "%s%s", jm.Stream, endl) - } else { - fmt.Fprintf(out, "%s%s\n", jm.Status, endl) - } - return nil -} - -// DisplayJSONMessagesStream displays a json message stream from `in` to `out`, `isTerminal` -// describes if `out` is a terminal. If this is the case, it will print `\n` at the end of -// each line and move the cursor while displaying. -func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool, auxCallback func(*json.RawMessage)) error { - var ( - dec = json.NewDecoder(in) - ids = make(map[string]int) - ) - - var termInfo termInfo - - if isTerminal { - term := os.Getenv("TERM") - if term == "" { - term = "vt102" - } - - var err error - if termInfo, err = gotty.OpenTermInfo(term); err != nil { - termInfo = &noTermInfo{} - } - } - - for { - diff := 0 - var jm JSONMessage - if err := dec.Decode(&jm); err != nil { - if err == io.EOF { - break - } - return err - } - - if jm.Aux != nil { - if auxCallback != nil { - auxCallback(jm.Aux) - } - continue - } - - if jm.Progress != nil { - jm.Progress.terminalFd = terminalFd - } - if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") { - line, ok := ids[jm.ID] - if !ok { - // NOTE: This approach of using len(id) to - // figure out the number of lines of history - // only works as long as we clear the history - // when we output something that's not - // accounted for in the map, such as a line - // with no ID. - line = len(ids) - ids[jm.ID] = line - if termInfo != nil { - fmt.Fprintf(out, "\n") - } - } - diff = len(ids) - line - if termInfo != nil { - cursorUp(out, termInfo, diff) - } - } else { - // When outputting something that isn't progress - // output, clear the history of previous lines. We - // don't want progress entries from some previous - // operation to be updated (for example, pull -a - // with multiple tags). - ids = make(map[string]int) - } - err := jm.Display(out, termInfo) - if jm.ID != "" && termInfo != nil { - cursorDown(out, termInfo, diff) - } - if err != nil { - return err - } - } - return nil -} - -type stream interface { - io.Writer - FD() uintptr - IsTerminal() bool -} - -// DisplayJSONMessagesToStream prints json messages to the output stream -func DisplayJSONMessagesToStream(in io.Reader, stream stream, auxCallback func(*json.RawMessage)) error { - return DisplayJSONMessagesStream(in, stream, stream.FD(), stream.IsTerminal(), auxCallback) -} diff --git a/vendor/github.com/docker/docker/pkg/longpath/longpath.go b/vendor/github.com/docker/docker/pkg/longpath/longpath.go deleted file mode 100644 index 9b15bfff4c..0000000000 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,26 +0,0 @@ -// longpath introduces some constants and helper functions for handling long paths -// in Windows, which are expected to be prepended with `\\?\` and followed by either -// a drive letter, a UNC server\share, or a volume identifier. - -package longpath - -import ( - "strings" -) - -// Prefix is the longpath prefix for Windows file paths. -const Prefix = `\\?\` - -// AddPrefix will add the Windows long path prefix to the path provided if -// it does not already have it. -func AddPrefix(path string) string { - if !strings.HasPrefix(path, Prefix) { - if strings.HasPrefix(path, `\\`) { - // This is a UNC path, so we need to add 'UNC' to the path as well. - path = Prefix + `UNC` + path[1:] - } else { - path = Prefix + path - } - } - return path -} diff --git a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go b/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go deleted file mode 100644 index a018a203f3..0000000000 --- a/vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go +++ /dev/null @@ -1,190 +0,0 @@ -package stdcopy - -import ( - "bytes" - "encoding/binary" - "errors" - "fmt" - "io" - "sync" -) - -// StdType is the type of standard stream -// a writer can multiplex to. -type StdType byte - -const ( - // Stdin represents standard input stream type. - Stdin StdType = iota - // Stdout represents standard output stream type. - Stdout - // Stderr represents standard error steam type. - Stderr - // Systemerr represents errors originating from the system that make it - // into the the multiplexed stream. - Systemerr - - stdWriterPrefixLen = 8 - stdWriterFdIndex = 0 - stdWriterSizeIndex = 4 - - startingBufLen = 32*1024 + stdWriterPrefixLen + 1 -) - -var bufPool = &sync.Pool{New: func() interface{} { return bytes.NewBuffer(nil) }} - -// stdWriter is wrapper of io.Writer with extra customized info. -type stdWriter struct { - io.Writer - prefix byte -} - -// Write sends the buffer to the underneath writer. -// It inserts the prefix header before the buffer, -// so stdcopy.StdCopy knows where to multiplex the output. -// It makes stdWriter to implement io.Writer. -func (w *stdWriter) Write(p []byte) (n int, err error) { - if w == nil || w.Writer == nil { - return 0, errors.New("Writer not instantiated") - } - if p == nil { - return 0, nil - } - - header := [stdWriterPrefixLen]byte{stdWriterFdIndex: w.prefix} - binary.BigEndian.PutUint32(header[stdWriterSizeIndex:], uint32(len(p))) - buf := bufPool.Get().(*bytes.Buffer) - buf.Write(header[:]) - buf.Write(p) - - n, err = w.Writer.Write(buf.Bytes()) - n -= stdWriterPrefixLen - if n < 0 { - n = 0 - } - - buf.Reset() - bufPool.Put(buf) - return -} - -// NewStdWriter instantiates a new Writer. -// Everything written to it will be encapsulated using a custom format, -// and written to the underlying `w` stream. -// This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. -// `t` indicates the id of the stream to encapsulate. -// It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. -func NewStdWriter(w io.Writer, t StdType) io.Writer { - return &stdWriter{ - Writer: w, - prefix: byte(t), - } -} - -// StdCopy is a modified version of io.Copy. -// -// StdCopy will demultiplex `src`, assuming that it contains two streams, -// previously multiplexed together using a StdWriter instance. -// As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. -// -// StdCopy will read until it hits EOF on `src`. It will then return a nil error. -// In other words: if `err` is non nil, it indicates a real underlying error. -// -// `written` will hold the total number of bytes written to `dstout` and `dsterr`. -func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { - var ( - buf = make([]byte, startingBufLen) - bufLen = len(buf) - nr, nw int - er, ew error - out io.Writer - frameSize int - ) - - for { - // Make sure we have at least a full header - for nr < stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < stdWriterPrefixLen { - return written, nil - } - break - } - if er != nil { - return 0, er - } - } - - stream := StdType(buf[stdWriterFdIndex]) - // Check the first byte to know where to write - switch stream { - case Stdin: - fallthrough - case Stdout: - // Write on stdout - out = dstout - case Stderr: - // Write on stderr - out = dsterr - case Systemerr: - // If we're on Systemerr, we won't write anywhere. - // NB: if this code changes later, make sure you don't try to write - // to outstream if Systemerr is the stream - out = nil - default: - return 0, fmt.Errorf("Unrecognized input header: %d", buf[stdWriterFdIndex]) - } - - // Retrieve the size of the frame - frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) - - // Check if the buffer is big enough to read the frame. - // Extend it if necessary. - if frameSize+stdWriterPrefixLen > bufLen { - buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) - bufLen = len(buf) - } - - // While the amount of bytes read is less than the size of the frame + header, we keep reading - for nr < frameSize+stdWriterPrefixLen { - var nr2 int - nr2, er = src.Read(buf[nr:]) - nr += nr2 - if er == io.EOF { - if nr < frameSize+stdWriterPrefixLen { - return written, nil - } - break - } - if er != nil { - return 0, er - } - } - - // we might have an error from the source mixed up in our multiplexed - // stream. if we do, return it. - if stream == Systemerr { - return written, fmt.Errorf("error from daemon in stream: %s", string(buf[stdWriterPrefixLen:frameSize+stdWriterPrefixLen])) - } - - // Write the retrieved frame (without header) - nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) - if ew != nil { - return 0, ew - } - - // If the frame has not been fully written: error - if nw != frameSize { - return 0, io.ErrShortWrite - } - written += int64(nw) - - // Move the rest of the buffer to the beginning - copy(buf, buf[frameSize+stdWriterPrefixLen:]) - // Move the index - nr -= frameSize + stdWriterPrefixLen - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes.go b/vendor/github.com/docker/docker/pkg/system/chtimes.go deleted file mode 100644 index 7637f12e1a..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes.go +++ /dev/null @@ -1,52 +0,0 @@ -package system - -import ( - "os" - "syscall" - "time" - "unsafe" -) - -var ( - maxTime time.Time -) - -func init() { - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - maxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - maxTime = time.Unix(1<<31-1, 0) - } -} - -// Chtimes changes the access time and modified time of a file at the given path -func Chtimes(name string, atime time.Time, mtime time.Time) error { - unixMinTime := time.Unix(0, 0) - unixMaxTime := maxTime - - // If the modified time is prior to the Unix Epoch, or after the - // end of Unix Time, os.Chtimes has undefined behavior - // default to Unix Epoch in this case, just in case - - if atime.Before(unixMinTime) || atime.After(unixMaxTime) { - atime = unixMinTime - } - - if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { - mtime = unixMinTime - } - - if err := os.Chtimes(name, atime, mtime); err != nil { - return err - } - - // Take platform specific action for setting create time. - if err := setCTime(name, mtime); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go b/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go deleted file mode 100644 index 09d58bcbfd..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !windows - -package system - -import ( - "time" -) - -//setCTime will set the create time on a file. On Unix, the create -//time is updated as a side effect of setting the modified time, so -//no action is required. -func setCTime(path string, ctime time.Time) error { - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go b/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go deleted file mode 100644 index 2945868465..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build windows - -package system - -import ( - "syscall" - "time" -) - -//setCTime will set the create time on a file. On Windows, this requires -//calling SetFileTime and explicitly including the create time. -func setCTime(path string, ctime time.Time) error { - ctimespec := syscall.NsecToTimespec(ctime.UnixNano()) - pathp, e := syscall.UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := syscall.CreateFile(pathp, - syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil, - syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer syscall.Close(h) - c := syscall.NsecToFiletime(syscall.TimespecToNsec(ctimespec)) - return syscall.SetFileTime(h, &c, nil, nil) -} diff --git a/vendor/github.com/docker/docker/pkg/system/errors.go b/vendor/github.com/docker/docker/pkg/system/errors.go deleted file mode 100644 index 288318985e..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package system - -import ( - "errors" -) - -var ( - // ErrNotSupportedPlatform means the platform is not supported. - ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") -) diff --git a/vendor/github.com/docker/docker/pkg/system/events_windows.go b/vendor/github.com/docker/docker/pkg/system/events_windows.go deleted file mode 100644 index 3ec6d22151..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/events_windows.go +++ /dev/null @@ -1,85 +0,0 @@ -package system - -// This file implements syscalls for Win32 events which are not implemented -// in golang. - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var ( - procCreateEvent = modkernel32.NewProc("CreateEventW") - procOpenEvent = modkernel32.NewProc("OpenEventW") - procSetEvent = modkernel32.NewProc("SetEvent") - procResetEvent = modkernel32.NewProc("ResetEvent") - procPulseEvent = modkernel32.NewProc("PulseEvent") -) - -// CreateEvent implements win32 CreateEventW func in golang. It will create an event object. -func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) { - namep, _ := syscall.UTF16PtrFromString(name) - var _p1 uint32 - if manualReset { - _p1 = 1 - } - var _p2 uint32 - if initialState { - _p2 = 1 - } - r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) - use(unsafe.Pointer(namep)) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = e1 - } - return -} - -// OpenEvent implements win32 OpenEventW func in golang. It opens an event object. -func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) { - namep, _ := syscall.UTF16PtrFromString(name) - var _p1 uint32 - if inheritHandle { - _p1 = 1 - } - r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) - use(unsafe.Pointer(namep)) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - err = e1 - } - return -} - -// SetEvent implements win32 SetEvent func in golang. -func SetEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procSetEvent) -} - -// ResetEvent implements win32 ResetEvent func in golang. -func ResetEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procResetEvent) -} - -// PulseEvent implements win32 PulseEvent func in golang. -func PulseEvent(handle syscall.Handle) (err error) { - return setResetPulse(handle, procPulseEvent) -} - -func setResetPulse(handle syscall.Handle, proc *windows.LazyProc) (err error) { - r0, _, _ := proc.Call(uintptr(handle)) - if r0 != 0 { - err = syscall.Errno(r0) - } - return -} - -var temp unsafe.Pointer - -// use ensures a variable is kept alive without the GC freeing while still needed -func use(p unsafe.Pointer) { - temp = p -} diff --git a/vendor/github.com/docker/docker/pkg/system/exitcode.go b/vendor/github.com/docker/docker/pkg/system/exitcode.go deleted file mode 100644 index 60f0514b1d..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/exitcode.go +++ /dev/null @@ -1,33 +0,0 @@ -package system - -import ( - "fmt" - "os/exec" - "syscall" -) - -// GetExitCode returns the ExitStatus of the specified error if its type is -// exec.ExitError, returns 0 and an error otherwise. -func GetExitCode(err error) (int, error) { - exitCode := 0 - if exiterr, ok := err.(*exec.ExitError); ok { - if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { - return procExit.ExitStatus(), nil - } - } - return exitCode, fmt.Errorf("failed to get exit code") -} - -// ProcessExitCode process the specified error and returns the exit status code -// if the error was of type exec.ExitError, returns nothing otherwise. -func ProcessExitCode(err error) (exitCode int) { - if err != nil { - var exiterr error - if exitCode, exiterr = GetExitCode(err); exiterr != nil { - // TODO: Fix this so we check the error's text. - // we've failed to retrieve exit code, so we set it to 127 - exitCode = 127 - } - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys.go b/vendor/github.com/docker/docker/pkg/system/filesys.go deleted file mode 100644 index 7aa920de1a..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys.go +++ /dev/null @@ -1,68 +0,0 @@ -// +build !windows - -package system - -import ( - "io/ioutil" - "os" - "path/filepath" -) - -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// ACL'd for Builtin Administrators and Local System. -func MkdirAllWithACL(path string, perm os.FileMode) error { - return MkdirAll(path, perm) -} - -// MkdirAll creates a directory named path along with any necessary parents, -// with permission specified by attribute perm for all dir created. -func MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, perm) -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. -func IsAbs(path string) bool { - return filepath.IsAbs(path) -} - -// The functions below here are wrappers for the equivalents in the os and ioutils packages. -// They are passthrough on Unix platforms, and only relevant on Windows. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return os.Create(name) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return os.Open(name) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. It opens the named file with specified flag -// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, -// methods on the returned File can be used for I/O. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { - return os.OpenFile(name, flag, perm) -} - -// TempFileSequential 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 *os.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 TempFileSequential(dir, prefix string) (f *os.File, err error) { - return ioutil.TempFile(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/vendor/github.com/docker/docker/pkg/system/filesys_windows.go deleted file mode 100644 index 626d2ad886..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go +++ /dev/null @@ -1,291 +0,0 @@ -// +build windows - -package system - -import ( - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "sync" - "syscall" - "time" - "unsafe" - - winio "github.com/Microsoft/go-winio" -) - -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// ACL'd for Builtin Administrators and Local System. -func MkdirAllWithACL(path string, perm os.FileMode) error { - return mkdirall(path, true) -} - -// MkdirAll implementation that is volume path aware for Windows. -func MkdirAll(path string, _ os.FileMode) error { - return mkdirall(path, false) -} - -// mkdirall is a custom version of os.MkdirAll modified for use on Windows -// so that it is both volume path aware, and can create a directory with -// a DACL. -func mkdirall(path string, adminAndLocalSystem bool) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { - return nil - } - - // The rest of this method is largely copied from os.MkdirAll and should be kept - // as-is to ensure compatibility. - - // Fast path: if we can tell whether path is a directory or file, stop with success or error. - dir, err := os.Stat(path) - if err == nil { - if dir.IsDir() { - return nil - } - return &os.PathError{ - Op: "mkdir", - Path: path, - Err: syscall.ENOTDIR, - } - } - - // Slow path: make sure parent exists and then call Mkdir for path. - i := len(path) - for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. - i-- - } - - j := i - for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. - j-- - } - - if j > 1 { - // Create parent - err = mkdirall(path[0:j-1], false) - if err != nil { - return err - } - } - - // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. - if adminAndLocalSystem { - err = mkdirWithACL(path) - } else { - err = os.Mkdir(path, 0) - } - - if err != nil { - // Handle arguments like "foo/." by - // double-checking that directory doesn't exist. - dir, err1 := os.Lstat(path) - if err1 == nil && dir.IsDir() { - return nil - } - return err - } - return nil -} - -// mkdirWithACL creates a new directory. If there is an error, it will be of -// type *PathError. . -// -// This is a modified and combined version of os.Mkdir and syscall.Mkdir -// in golang to cater for creating a directory am ACL permitting full -// access, with inheritance, to any subfolder/file for Built-in Administrators -// and Local System. -func mkdirWithACL(name string) error { - sa := syscall.SecurityAttributes{Length: 0} - sddl := "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" - sd, err := winio.SddlToSecurityDescriptor(sddl) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0])) - - namep, err := syscall.UTF16PtrFromString(name) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - - e := syscall.CreateDirectory(namep, &sa) - if e != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: e} - } - return nil -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, -// golang filepath.IsAbs does not consider a path \windows\system32 as absolute -// as it doesn't start with a drive-letter/colon combination. However, in -// docker we need to verify things such as WORKDIR /windows/system32 in -// a Dockerfile (which gets translated to \windows\system32 when being processed -// by the daemon. This SHOULD be treated as absolute from a docker processing -// perspective. -func IsAbs(path string) bool { - if !filepath.IsAbs(path) { - if !strings.HasPrefix(path, string(os.PathSeparator)) { - return false - } - } - return true -} - -// The origin of the functions below here are the golang OS and syscall packages, -// slightly modified to only cope with files, not directories due to the -// specific use case. -// -// The alteration is to allow a file on Windows to be opened with -// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating -// the standby list, particularly when accessing large files such as layer.tar. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDONLY, 0) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { - if name == "" { - return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} - } - r, errf := syscallOpenFileSequential(name, flag, 0) - if errf == nil { - return r, nil - } - return nil, &os.PathError{Op: "open", Path: name, Err: errf} -} - -func syscallOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) { - r, e := syscallOpenSequential(name, flag|syscall.O_CLOEXEC, 0) - if e != nil { - return nil, e - } - return os.NewFile(uintptr(r), name), nil -} - -func makeInheritSa() *syscall.SecurityAttributes { - var sa syscall.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -func syscallOpenSequential(path string, mode int, _ uint32) (fd syscall.Handle, err error) { - if len(path) == 0 { - return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND - } - pathp, err := syscall.UTF16PtrFromString(path) - if err != nil { - return syscall.InvalidHandle, err - } - var access uint32 - switch mode & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) { - case syscall.O_RDONLY: - access = syscall.GENERIC_READ - case syscall.O_WRONLY: - access = syscall.GENERIC_WRITE - case syscall.O_RDWR: - access = syscall.GENERIC_READ | syscall.GENERIC_WRITE - } - if mode&syscall.O_CREAT != 0 { - access |= syscall.GENERIC_WRITE - } - if mode&syscall.O_APPEND != 0 { - access &^= syscall.GENERIC_WRITE - access |= syscall.FILE_APPEND_DATA - } - sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE) - var sa *syscall.SecurityAttributes - if mode&syscall.O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL): - createmode = syscall.CREATE_NEW - case mode&(syscall.O_CREAT|syscall.O_TRUNC) == (syscall.O_CREAT | syscall.O_TRUNC): - createmode = syscall.CREATE_ALWAYS - case mode&syscall.O_CREAT == syscall.O_CREAT: - createmode = syscall.OPEN_ALWAYS - case mode&syscall.O_TRUNC == syscall.O_TRUNC: - createmode = syscall.TRUNCATE_EXISTING - default: - createmode = syscall.OPEN_EXISTING - } - // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang. - //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx - const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN - h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) - return h, e -} - -// Helpers for TempFileSequential -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:] -} - -// TempFileSequential is a copy of ioutil.TempFile, modified to use sequential -// file access. Below is the original comment from golang: -// 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 *os.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 TempFileSequential(dir, prefix string) (f *os.File, err error) { - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+nextSuffix()) - f, err = OpenFileSequential(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 -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go b/vendor/github.com/docker/docker/pkg/system/lstat_unix.go deleted file mode 100644 index 62fda5bacf..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build !windows - -package system - -import "syscall" - -// Lstat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Lstat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Lstat(path, s); err != nil { - return nil, err - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go b/vendor/github.com/docker/docker/pkg/system/lstat_windows.go deleted file mode 100644 index e51df0dafe..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_windows.go +++ /dev/null @@ -1,14 +0,0 @@ -package system - -import "os" - -// Lstat calls os.Lstat to get a fileinfo interface back. -// This is then copied into our own locally defined structure. -func Lstat(path string) (*StatT, error) { - fi, err := os.Lstat(path) - if err != nil { - return nil, err - } - - return fromStatT(&fi) -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo.go b/vendor/github.com/docker/docker/pkg/system/meminfo.go deleted file mode 100644 index 3b6e947e67..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package system - -// MemInfo contains memory statistics of the host system. -type MemInfo struct { - // Total usable RAM (i.e. physical RAM minus a few reserved bits and the - // kernel binary code). - MemTotal int64 - - // Amount of free memory. - MemFree int64 - - // Total amount of swap space available. - SwapTotal int64 - - // Amount of swap space that is currently unused. - SwapFree int64 -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go deleted file mode 100644 index 385f1d5e73..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go +++ /dev/null @@ -1,65 +0,0 @@ -package system - -import ( - "bufio" - "io" - "os" - "strconv" - "strings" - - "github.com/docker/go-units" -) - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - file, err := os.Open("/proc/meminfo") - if err != nil { - return nil, err - } - defer file.Close() - return parseMemInfo(file) -} - -// parseMemInfo parses the /proc/meminfo file into -// a MemInfo object given an io.Reader to the file. -// Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*MemInfo, error) { - meminfo := &MemInfo{} - scanner := bufio.NewScanner(reader) - for scanner.Scan() { - // Expected format: ["MemTotal:", "1234", "kB"] - parts := strings.Fields(scanner.Text()) - - // Sanity checks: Skip malformed entries. - if len(parts) < 3 || parts[2] != "kB" { - continue - } - - // Convert to bytes. - size, err := strconv.Atoi(parts[1]) - if err != nil { - continue - } - bytes := int64(size) * units.KiB - - switch parts[0] { - case "MemTotal:": - meminfo.MemTotal = bytes - case "MemFree:": - meminfo.MemFree = bytes - case "SwapTotal:": - meminfo.SwapTotal = bytes - case "SwapFree:": - meminfo.SwapFree = bytes - } - - } - - // Handle errors that may have occurred during the reading of the file. - if err := scanner.Err(); err != nil { - return nil, err - } - - return meminfo, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_solaris.go b/vendor/github.com/docker/docker/pkg/system/meminfo_solaris.go deleted file mode 100644 index 925776e789..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_solaris.go +++ /dev/null @@ -1,129 +0,0 @@ -// +build solaris,cgo - -package system - -import ( - "fmt" - "unsafe" -) - -// #cgo CFLAGS: -std=c99 -// #cgo LDFLAGS: -lkstat -// #include -// #include -// #include -// #include -// #include -// #include -// struct swaptable *allocSwaptable(int num) { -// struct swaptable *st; -// struct swapent *swapent; -// st = (struct swaptable *)malloc(num * sizeof(swapent_t) + sizeof (int)); -// swapent = st->swt_ent; -// for (int i = 0; i < num; i++,swapent++) { -// swapent->ste_path = (char *)malloc(MAXPATHLEN * sizeof (char)); -// } -// st->swt_n = num; -// return st; -//} -// void freeSwaptable (struct swaptable *st) { -// struct swapent *swapent = st->swt_ent; -// for (int i = 0; i < st->swt_n; i++,swapent++) { -// free(swapent->ste_path); -// } -// free(st); -// } -// swapent_t getSwapEnt(swapent_t *ent, int i) { -// return ent[i]; -// } -// int64_t getPpKernel() { -// int64_t pp_kernel = 0; -// kstat_ctl_t *ksc; -// kstat_t *ks; -// kstat_named_t *knp; -// kid_t kid; -// -// if ((ksc = kstat_open()) == NULL) { -// return -1; -// } -// if ((ks = kstat_lookup(ksc, "unix", 0, "system_pages")) == NULL) { -// return -1; -// } -// if (((kid = kstat_read(ksc, ks, NULL)) == -1) || -// ((knp = kstat_data_lookup(ks, "pp_kernel")) == NULL)) { -// return -1; -// } -// switch (knp->data_type) { -// case KSTAT_DATA_UINT64: -// pp_kernel = knp->value.ui64; -// break; -// case KSTAT_DATA_UINT32: -// pp_kernel = knp->value.ui32; -// break; -// } -// pp_kernel *= sysconf(_SC_PAGESIZE); -// return (pp_kernel > 0 ? pp_kernel : -1); -// } -import "C" - -// Get the system memory info using sysconf same as prtconf -func getTotalMem() int64 { - pagesize := C.sysconf(C._SC_PAGESIZE) - npages := C.sysconf(C._SC_PHYS_PAGES) - return int64(pagesize * npages) -} - -func getFreeMem() int64 { - pagesize := C.sysconf(C._SC_PAGESIZE) - npages := C.sysconf(C._SC_AVPHYS_PAGES) - return int64(pagesize * npages) -} - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - - ppKernel := C.getPpKernel() - MemTotal := getTotalMem() - MemFree := getFreeMem() - SwapTotal, SwapFree, err := getSysSwap() - - if ppKernel < 0 || MemTotal < 0 || MemFree < 0 || SwapTotal < 0 || - SwapFree < 0 { - return nil, fmt.Errorf("error getting system memory info %v\n", err) - } - - meminfo := &MemInfo{} - // Total memory is total physical memory less than memory locked by kernel - meminfo.MemTotal = MemTotal - int64(ppKernel) - meminfo.MemFree = MemFree - meminfo.SwapTotal = SwapTotal - meminfo.SwapFree = SwapFree - - return meminfo, nil -} - -func getSysSwap() (int64, int64, error) { - var tSwap int64 - var fSwap int64 - var diskblksPerPage int64 - num, err := C.swapctl(C.SC_GETNSWP, nil) - if err != nil { - return -1, -1, err - } - st := C.allocSwaptable(num) - _, err = C.swapctl(C.SC_LIST, unsafe.Pointer(st)) - if err != nil { - C.freeSwaptable(st) - return -1, -1, err - } - - diskblksPerPage = int64(C.sysconf(C._SC_PAGESIZE) >> C.DEV_BSHIFT) - for i := 0; i < int(num); i++ { - swapent := C.getSwapEnt(&st.swt_ent[0], C.int(i)) - tSwap += int64(swapent.ste_pages) * diskblksPerPage - fSwap += int64(swapent.ste_free) * diskblksPerPage - } - C.freeSwaptable(st) - return tSwap, fSwap, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go deleted file mode 100644 index 3ce019dffd..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !linux,!windows,!solaris - -package system - -// ReadMemInfo is not supported on platforms other than linux and windows. -func ReadMemInfo() (*MemInfo, error) { - return nil, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go deleted file mode 100644 index 883944a4c5..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -package system - -import ( - "unsafe" - - "golang.org/x/sys/windows" -) - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - - procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") -) - -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx -type memorystatusex struct { - dwLength uint32 - dwMemoryLoad uint32 - ullTotalPhys uint64 - ullAvailPhys uint64 - ullTotalPageFile uint64 - ullAvailPageFile uint64 - ullTotalVirtual uint64 - ullAvailVirtual uint64 - ullAvailExtendedVirtual uint64 -} - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - msi := &memorystatusex{ - dwLength: 64, - } - r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) - if r1 == 0 { - return &MemInfo{}, nil - } - return &MemInfo{ - MemTotal: int64(msi.ullTotalPhys), - MemFree: int64(msi.ullAvailPhys), - SwapTotal: int64(msi.ullTotalPageFile), - SwapFree: int64(msi.ullAvailPageFile), - }, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod.go b/vendor/github.com/docker/docker/pkg/system/mknod.go deleted file mode 100644 index 73958182b4..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// Mknod creates a filesystem node (file, device special file or named pipe) named path -// with attributes specified by mode and dev. -func Mknod(path string, mode uint32, dev int) error { - return syscall.Mknod(path, mode, dev) -} - -// Mkdev is used to build the value of linux devices (in /dev/) which specifies major -// and minor number of the newly created device special file. -// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. -// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, -// then the top 12 bits of the minor. -func Mkdev(major int64, minor int64) uint32 { - return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff)) -} diff --git a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go b/vendor/github.com/docker/docker/pkg/system/mknod_windows.go deleted file mode 100644 index 2e863c0215..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod_windows.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build windows - -package system - -// Mknod is not implemented on Windows. -func Mknod(path string, mode uint32, dev int) error { - return ErrNotSupportedPlatform -} - -// Mkdev is not implemented on Windows. -func Mkdev(major int64, minor int64) uint32 { - panic("Mkdev not implemented on Windows.") -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_unix.go b/vendor/github.com/docker/docker/pkg/system/path_unix.go deleted file mode 100644 index c607c4db09..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !windows - -package system - -// DefaultPathEnv is unix style list of directories to search for -// executables. Each directory is separated from the next by a colon -// ':' character . -const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" - -// CheckSystemDriveAndRemoveDriveLetter verifies that a path, if it includes a drive letter, -// is the system drive. This is a no-op on Linux. -func CheckSystemDriveAndRemoveDriveLetter(path string) (string, error) { - return path, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/docker/docker/pkg/system/path_windows.go deleted file mode 100644 index cbfe2c1576..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_windows.go +++ /dev/null @@ -1,37 +0,0 @@ -// +build windows - -package system - -import ( - "fmt" - "path/filepath" - "strings" -) - -// DefaultPathEnv is deliberately empty on Windows as the default path will be set by -// the container. Docker has no context of what the default path should be. -const DefaultPathEnv = "" - -// CheckSystemDriveAndRemoveDriveLetter verifies and manipulates a Windows path. -// This is used, for example, when validating a user provided path in docker cp. -// If a drive letter is supplied, it must be the system drive. The drive letter -// is always removed. Also, it translates it to OS semantics (IOW / to \). We -// need the path in this syntax so that it can ultimately be contatenated with -// a Windows long-path which doesn't support drive-letters. Examples: -// C: --> Fail -// C:\ --> \ -// a --> a -// /a --> \a -// d:\ --> Fail -func CheckSystemDriveAndRemoveDriveLetter(path string) (string, error) { - if len(path) == 2 && string(path[1]) == ":" { - return "", fmt.Errorf("No relative path specified in %q", path) - } - if !filepath.IsAbs(path) || len(path) < 2 { - return filepath.FromSlash(path), nil - } - if string(path[1]) == ":" && !strings.EqualFold(string(path[0]), "c") { - return "", fmt.Errorf("The specified path is not on the system drive (C:)") - } - return filepath.FromSlash(path[2:]), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_unix.go b/vendor/github.com/docker/docker/pkg/system/process_unix.go deleted file mode 100644 index c99d796d13..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build linux freebsd solaris darwin - -package system - -import ( - "syscall" -) - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - err := syscall.Kill(pid, syscall.Signal(0)) - if err == nil || err == syscall.EPERM { - return true - } - - return false -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - syscall.Kill(pid, syscall.SIGKILL) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go b/vendor/github.com/docker/docker/pkg/system/stat_darwin.go deleted file mode 100644 index 715f05b938..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_darwin.go +++ /dev/null @@ -1,13 +0,0 @@ -package system - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go b/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go deleted file mode 100644 index 715f05b938..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package system - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_linux.go b/vendor/github.com/docker/docker/pkg/system/stat_linux.go deleted file mode 100644 index 66bf6e28ee..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_linux.go +++ /dev/null @@ -1,19 +0,0 @@ -package system - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} - -// FromStatT converts a syscall.Stat_t type to a system.Stat_t type -// This is exposed on Linux as pkg/archive/changes uses it. -func FromStatT(s *syscall.Stat_t) (*StatT, error) { - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go b/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go deleted file mode 100644 index b607dea946..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_openbsd.go +++ /dev/null @@ -1,13 +0,0 @@ -package system - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go deleted file mode 100644 index b607dea946..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_solaris.go +++ /dev/null @@ -1,13 +0,0 @@ -package system - -import "syscall" - -// fromStatT converts a syscall.Stat_t type to a system.Stat_t type -func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, - mode: uint32(s.Mode), - uid: s.Uid, - gid: s.Gid, - rdev: uint64(s.Rdev), - mtim: s.Mtim}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_unix.go b/vendor/github.com/docker/docker/pkg/system/stat_unix.go deleted file mode 100644 index 6208e74606..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_unix.go +++ /dev/null @@ -1,58 +0,0 @@ -// +build !windows - -package system - -import "syscall" - -// StatT type contains status of a file. It contains metadata -// like permission, owner, group, size, etc about a file. -type StatT struct { - mode uint32 - uid uint32 - gid uint32 - rdev uint64 - size int64 - mtim syscall.Timespec -} - -// Mode returns file's permission mode. -func (s StatT) Mode() uint32 { - return s.mode -} - -// UID returns file's user id of owner. -func (s StatT) UID() uint32 { - return s.uid -} - -// GID returns file's group id of owner. -func (s StatT) GID() uint32 { - return s.gid -} - -// Rdev returns file's device ID (if it's special file). -func (s StatT) Rdev() uint64 { - return s.rdev -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() syscall.Timespec { - return s.mtim -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - s := &syscall.Stat_t{} - if err := syscall.Stat(path, s); err != nil { - return nil, err - } - return fromStatT(s) -} diff --git a/vendor/github.com/docker/docker/pkg/system/stat_windows.go b/vendor/github.com/docker/docker/pkg/system/stat_windows.go deleted file mode 100644 index 6c63972682..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_windows.go +++ /dev/null @@ -1,49 +0,0 @@ -package system - -import ( - "os" - "time" -) - -// StatT type contains status of a file. It contains metadata -// like permission, size, etc about a file. -type StatT struct { - mode os.FileMode - size int64 - mtim time.Time -} - -// Size returns file's size. -func (s StatT) Size() int64 { - return s.size -} - -// Mode returns file's permission mode. -func (s StatT) Mode() os.FileMode { - return os.FileMode(s.mode) -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() time.Time { - return time.Time(s.mtim) -} - -// Stat takes a path to a file and returns -// a system.StatT type pertaining to that file. -// -// Throws an error if the file does not exist -func Stat(path string) (*StatT, error) { - fi, err := os.Stat(path) - if err != nil { - return nil, err - } - return fromStatT(&fi) -} - -// fromStatT converts a os.FileInfo type to a system.StatT type -func fromStatT(fi *os.FileInfo) (*StatT, error) { - return &StatT{ - size: (*fi).Size(), - mode: (*fi).Mode(), - mtim: (*fi).ModTime()}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go b/vendor/github.com/docker/docker/pkg/system/syscall_unix.go deleted file mode 100644 index 3ae9128468..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build linux freebsd - -package system - -import "syscall" - -// Unmount is a platform-specific helper function to call -// the unmount syscall. -func Unmount(dest string) error { - return syscall.Unmount(dest, 0) -} - -// CommandLineToArgv should not be used on Unix. -// It simply returns commandLine in the only element in the returned array. -func CommandLineToArgv(commandLine string) ([]string, error) { - return []string{commandLine}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go b/vendor/github.com/docker/docker/pkg/system/syscall_windows.go deleted file mode 100644 index 1f311874f4..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go +++ /dev/null @@ -1,105 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" - - "github.com/Sirupsen/logrus" -) - -var ( - ntuserApiset = syscall.NewLazyDLL("ext-ms-win-ntuser-window-l1-1-0") - procGetVersionExW = modkernel32.NewProc("GetVersionExW") -) - -// OSVersion is a wrapper for Windows version information -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx -type OSVersion struct { - Version uint32 - MajorVersion uint8 - MinorVersion uint8 - Build uint16 -} - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx -type osVersionInfoEx struct { - OSVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformID uint32 - CSDVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - Reserve byte -} - -// GetOSVersion gets the operating system version on Windows. Note that -// docker.exe must be manifested to get the correct version information. -func GetOSVersion() OSVersion { - var err error - osv := OSVersion{} - osv.Version, err = syscall.GetVersion() - if err != nil { - // GetVersion never fails. - panic(err) - } - osv.MajorVersion = uint8(osv.Version & 0xFF) - osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) - osv.Build = uint16(osv.Version >> 16) - return osv -} - -// IsWindowsClient returns true if the SKU is client -// @engine maintainers - this function should not be removed or modified as it -// is used to enforce licensing restrictions on Windows. -func IsWindowsClient() bool { - osviex := &osVersionInfoEx{OSVersionInfoSize: 284} - r1, _, err := procGetVersionExW.Call(uintptr(unsafe.Pointer(osviex))) - if r1 == 0 { - logrus.Warnf("GetVersionExW failed - assuming server SKU: %v", err) - return false - } - const verNTWorkstation = 0x00000001 - return osviex.ProductType == verNTWorkstation -} - -// Unmount is a platform-specific helper function to call -// the unmount syscall. Not supported on Windows -func Unmount(dest string) error { - return nil -} - -// CommandLineToArgv wraps the Windows syscall to turn a commandline into an argument array. -func CommandLineToArgv(commandLine string) ([]string, error) { - var argc int32 - - argsPtr, err := syscall.UTF16PtrFromString(commandLine) - if err != nil { - return nil, err - } - - argv, err := syscall.CommandLineToArgv(argsPtr, &argc) - if err != nil { - return nil, err - } - defer syscall.LocalFree(syscall.Handle(uintptr(unsafe.Pointer(argv)))) - - newArgs := make([]string, argc) - for i, v := range (*argv)[:argc] { - newArgs[i] = string(syscall.UTF16ToString((*v)[:])) - } - - return newArgs, nil -} - -// HasWin32KSupport determines whether containers that depend on win32k can -// run on this machine. Win32k is the driver used to implement windowing. -func HasWin32KSupport() bool { - // For now, check for ntuser API support on the host. In the future, a host - // may support win32k in containers even if the host does not support ntuser - // APIs. - return ntuserApiset.Load() == nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask.go b/vendor/github.com/docker/docker/pkg/system/umask.go deleted file mode 100644 index 3d0146b01a..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/umask.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !windows - -package system - -import ( - "syscall" -) - -// Umask sets current process's file mode creation mask to newmask -// and returns oldmask. -func Umask(newmask int) (oldmask int, err error) { - return syscall.Umask(newmask), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask_windows.go b/vendor/github.com/docker/docker/pkg/system/umask_windows.go deleted file mode 100644 index 13f1de1769..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/umask_windows.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build windows - -package system - -// Umask is not supported on the windows platform. -func Umask(newmask int) (oldmask int, err error) { - // should not be called on cli code path - return 0, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go b/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go deleted file mode 100644 index e2eac3b553..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go +++ /dev/null @@ -1,22 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - var _path *byte - _path, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - - if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_linux.go b/vendor/github.com/docker/docker/pkg/system/utimes_linux.go deleted file mode 100644 index fc8a1aba95..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_linux.go +++ /dev/null @@ -1,26 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// LUtimesNano is used to change access and modification time of the specified path. -// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. -func LUtimesNano(path string, ts []syscall.Timespec) error { - // These are not currently available in syscall - atFdCwd := -100 - atSymLinkNoFollow := 0x100 - - var _path *byte - _path, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - - if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(atSymLinkNoFollow), 0, 0); err != 0 && err != syscall.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go b/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go deleted file mode 100644 index 139714544d..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !linux,!freebsd - -package system - -import "syscall" - -// LUtimesNano is only supported on linux and freebsd. -func LUtimesNano(path string, ts []syscall.Timespec) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go b/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go deleted file mode 100644 index d2e2c05799..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go +++ /dev/null @@ -1,63 +0,0 @@ -package system - -import ( - "syscall" - "unsafe" -) - -// Lgetxattr retrieves the value of the extended attribute identified by attr -// and associated with the given path in the file system. -// It will returns a nil slice and nil error if the xattr is not set. -func Lgetxattr(path string, attr string) ([]byte, error) { - pathBytes, err := syscall.BytePtrFromString(path) - if err != nil { - return nil, err - } - attrBytes, err := syscall.BytePtrFromString(attr) - if err != nil { - return nil, err - } - - dest := make([]byte, 128) - destBytes := unsafe.Pointer(&dest[0]) - sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) - if errno == syscall.ENODATA { - return nil, nil - } - if errno == syscall.ERANGE { - dest = make([]byte, sz) - destBytes := unsafe.Pointer(&dest[0]) - sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) - } - if errno != 0 { - return nil, errno - } - - return dest[:sz], nil -} - -var _zero uintptr - -// Lsetxattr sets the value of the extended attribute identified by attr -// and associated with the given path in the file system. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - pathBytes, err := syscall.BytePtrFromString(path) - if err != nil { - return err - } - attrBytes, err := syscall.BytePtrFromString(attr) - if err != nil { - return err - } - var dataBytes unsafe.Pointer - if len(data) > 0 { - dataBytes = unsafe.Pointer(&data[0]) - } else { - dataBytes = unsafe.Pointer(&_zero) - } - _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0) - if errno != 0 { - return errno - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go deleted file mode 100644 index 0114f2227c..0000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !linux - -package system - -// Lgetxattr is not supported on platforms other than linux. -func Lgetxattr(path string, attr string) ([]byte, error) { - return nil, ErrNotSupportedPlatform -} - -// Lsetxattr is not supported on platforms other than linux. -func Lsetxattr(path string, attr string, data []byte, flags int) error { - return ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/term/ascii.go b/vendor/github.com/docker/docker/pkg/term/ascii.go deleted file mode 100644 index f5262bccf5..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/ascii.go +++ /dev/null @@ -1,66 +0,0 @@ -package term - -import ( - "fmt" - "strings" -) - -// ASCII list the possible supported ASCII key sequence -var ASCII = []string{ - "ctrl-@", - "ctrl-a", - "ctrl-b", - "ctrl-c", - "ctrl-d", - "ctrl-e", - "ctrl-f", - "ctrl-g", - "ctrl-h", - "ctrl-i", - "ctrl-j", - "ctrl-k", - "ctrl-l", - "ctrl-m", - "ctrl-n", - "ctrl-o", - "ctrl-p", - "ctrl-q", - "ctrl-r", - "ctrl-s", - "ctrl-t", - "ctrl-u", - "ctrl-v", - "ctrl-w", - "ctrl-x", - "ctrl-y", - "ctrl-z", - "ctrl-[", - "ctrl-\\", - "ctrl-]", - "ctrl-^", - "ctrl-_", -} - -// ToBytes converts a string representing a suite of key-sequence to the corresponding ASCII code. -func ToBytes(keys string) ([]byte, error) { - codes := []byte{} -next: - for _, key := range strings.Split(keys, ",") { - if len(key) != 1 { - for code, ctrl := range ASCII { - if ctrl == key { - codes = append(codes, byte(code)) - continue next - } - } - if key == "DEL" { - codes = append(codes, 127) - } else { - return nil, fmt.Errorf("Unknown character: '%s'", key) - } - } else { - codes = append(codes, byte(key[0])) - } - } - return codes, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go b/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go deleted file mode 100644 index 59dac5ba8e..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go +++ /dev/null @@ -1,50 +0,0 @@ -// +build linux,cgo - -package term - -import ( - "syscall" - "unsafe" -) - -// #include -import "C" - -// Termios is the Unix API for terminal I/O. -// It is passthrough for syscall.Termios in order to make it portable with -// other platforms where it is not available or handled differently. -type Termios syscall.Termios - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if err := tcget(fd, &oldState.termios); err != 0 { - return nil, err - } - - newState := oldState.termios - - C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) - if err := tcset(fd, &newState); err != 0 { - return nil, err - } - return &oldState, nil -} - -func tcget(fd uintptr, p *Termios) syscall.Errno { - ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) - if ret != 0 { - return err.(syscall.Errno) - } - return 0 -} - -func tcset(fd uintptr, p *Termios) syscall.Errno { - ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) - if ret != 0 { - return err.(syscall.Errno) - } - return 0 -} diff --git a/vendor/github.com/docker/docker/pkg/term/tc_other.go b/vendor/github.com/docker/docker/pkg/term/tc_other.go deleted file mode 100644 index 750d7c3f60..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/tc_other.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows -// +build !linux !cgo -// +build !solaris !cgo - -package term - -import ( - "syscall" - "unsafe" -) - -func tcget(fd uintptr, p *Termios) syscall.Errno { - _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(p))) - return err -} - -func tcset(fd uintptr, p *Termios) syscall.Errno { - _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(p))) - return err -} diff --git a/vendor/github.com/docker/docker/pkg/term/tc_solaris_cgo.go b/vendor/github.com/docker/docker/pkg/term/tc_solaris_cgo.go deleted file mode 100644 index c9139d0ca8..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/tc_solaris_cgo.go +++ /dev/null @@ -1,63 +0,0 @@ -// +build solaris,cgo - -package term - -import ( - "syscall" - "unsafe" -) - -// #include -import "C" - -// Termios is the Unix API for terminal I/O. -// It is passthrough for syscall.Termios in order to make it portable with -// other platforms where it is not available or handled differently. -type Termios syscall.Termios - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if err := tcget(fd, &oldState.termios); err != 0 { - return nil, err - } - - newState := oldState.termios - - newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON | syscall.IXANY) - newState.Oflag &^= syscall.OPOST - newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) - newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) - newState.Cflag |= syscall.CS8 - - /* - VMIN is the minimum number of characters that needs to be read in non-canonical mode for it to be returned - Since VMIN is overloaded with another element in canonical mode when we switch modes it defaults to 4. It - needs to be explicitly set to 1. - */ - newState.Cc[C.VMIN] = 1 - newState.Cc[C.VTIME] = 0 - - if err := tcset(fd, &newState); err != 0 { - return nil, err - } - return &oldState, nil -} - -func tcget(fd uintptr, p *Termios) syscall.Errno { - ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) - if ret != 0 { - return err.(syscall.Errno) - } - return 0 -} - -func tcset(fd uintptr, p *Termios) syscall.Errno { - ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) - if ret != 0 { - return err.(syscall.Errno) - } - return 0 -} diff --git a/vendor/github.com/docker/docker/pkg/term/term.go b/vendor/github.com/docker/docker/pkg/term/term.go deleted file mode 100644 index 816f8d7524..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/term.go +++ /dev/null @@ -1,123 +0,0 @@ -// +build !windows - -// Package term provides structures and helper functions to work with -// terminal (state, sizes). -package term - -import ( - "errors" - "fmt" - "io" - "os" - "os/signal" - "syscall" -) - -var ( - // ErrInvalidState is returned if the state of the terminal is invalid. - ErrInvalidState = errors.New("Invalid terminal state") -) - -// State represents the state of the terminal. -type State struct { - termios Termios -} - -// Winsize represents the size of the terminal window. -type Winsize struct { - Height uint16 - Width uint16 - x uint16 - y uint16 -} - -// StdStreams returns the standard streams (stdin, stdout, stderr). -func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { - return os.Stdin, os.Stdout, os.Stderr -} - -// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. -func GetFdInfo(in interface{}) (uintptr, bool) { - var inFd uintptr - var isTerminalIn bool - if file, ok := in.(*os.File); ok { - inFd = file.Fd() - isTerminalIn = IsTerminal(inFd) - } - return inFd, isTerminalIn -} - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(fd uintptr) bool { - var termios Termios - return tcget(fd, &termios) == 0 -} - -// RestoreTerminal restores the terminal connected to the given file descriptor -// to a previous state. -func RestoreTerminal(fd uintptr, state *State) error { - if state == nil { - return ErrInvalidState - } - if err := tcset(fd, &state.termios); err != 0 { - return err - } - return nil -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - var oldState State - if err := tcget(fd, &oldState.termios); err != 0 { - return nil, err - } - - return &oldState, nil -} - -// DisableEcho applies the specified state to the terminal connected to the file -// descriptor, with echo disabled. -func DisableEcho(fd uintptr, state *State) error { - newState := state.termios - newState.Lflag &^= syscall.ECHO - - if err := tcset(fd, &newState); err != 0 { - return err - } - handleInterrupt(fd, state) - return nil -} - -// SetRawTerminal puts the terminal connected to the given file descriptor into -// raw mode and returns the previous state. On UNIX, this puts both the input -// and output into raw mode. On Windows, it only puts the input into raw mode. -func SetRawTerminal(fd uintptr) (*State, error) { - oldState, err := MakeRaw(fd) - if err != nil { - return nil, err - } - handleInterrupt(fd, oldState) - return oldState, err -} - -// SetRawTerminalOutput puts the output of terminal connected to the given file -// descriptor into raw mode. On UNIX, this does nothing and returns nil for the -// state. On Windows, it disables LF -> CRLF translation. -func SetRawTerminalOutput(fd uintptr) (*State, error) { - return nil, nil -} - -func handleInterrupt(fd uintptr, state *State) { - sigchan := make(chan os.Signal, 1) - signal.Notify(sigchan, os.Interrupt) - go func() { - for range sigchan { - // quit cleanly and the new terminal item is on a new line - fmt.Println() - signal.Stop(sigchan) - close(sigchan) - RestoreTerminal(fd, state) - os.Exit(1) - } - }() -} diff --git a/vendor/github.com/docker/docker/pkg/term/term_solaris.go b/vendor/github.com/docker/docker/pkg/term/term_solaris.go deleted file mode 100644 index 112debbec5..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/term_solaris.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build solaris - -package term - -import ( - "syscall" - "unsafe" -) - -/* -#include -#include -#include - -// Small wrapper to get rid of variadic args of ioctl() -int my_ioctl(int fd, int cmd, struct winsize *ws) { - return ioctl(fd, cmd, ws); -} -*/ -import "C" - -// GetWinsize returns the window size based on the specified file descriptor. -func GetWinsize(fd uintptr) (*Winsize, error) { - ws := &Winsize{} - ret, err := C.my_ioctl(C.int(fd), C.int(syscall.TIOCGWINSZ), (*C.struct_winsize)(unsafe.Pointer(ws))) - // Skip retval = 0 - if ret == 0 { - return ws, nil - } - return ws, err -} - -// SetWinsize tries to set the specified window size for the specified file descriptor. -func SetWinsize(fd uintptr, ws *Winsize) error { - ret, err := C.my_ioctl(C.int(fd), C.int(syscall.TIOCSWINSZ), (*C.struct_winsize)(unsafe.Pointer(ws))) - // Skip retval = 0 - if ret == 0 { - return nil - } - return err -} diff --git a/vendor/github.com/docker/docker/pkg/term/term_unix.go b/vendor/github.com/docker/docker/pkg/term/term_unix.go deleted file mode 100644 index ddf87a0e58..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/term_unix.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build !solaris,!windows - -package term - -import ( - "syscall" - "unsafe" -) - -// GetWinsize returns the window size based on the specified file descriptor. -func GetWinsize(fd uintptr) (*Winsize, error) { - ws := &Winsize{} - _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws))) - // Skipp errno = 0 - if err == 0 { - return ws, nil - } - return ws, err -} - -// SetWinsize tries to set the specified window size for the specified file descriptor. -func SetWinsize(fd uintptr, ws *Winsize) error { - _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws))) - // Skipp errno = 0 - if err == 0 { - return nil - } - return err -} diff --git a/vendor/github.com/docker/docker/pkg/term/term_windows.go b/vendor/github.com/docker/docker/pkg/term/term_windows.go deleted file mode 100644 index 62e9a9e692..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/term_windows.go +++ /dev/null @@ -1,233 +0,0 @@ -// +build windows - -package term - -import ( - "io" - "os" - "os/signal" - "syscall" - - "github.com/Azure/go-ansiterm/winterm" - "github.com/docker/docker/pkg/term/windows" -) - -// State holds the console mode for the terminal. -type State struct { - mode uint32 -} - -// Winsize is used for window size. -type Winsize struct { - Height uint16 - Width uint16 -} - -const ( - // https://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx - enableVirtualTerminalInput = 0x0200 - enableVirtualTerminalProcessing = 0x0004 - disableNewlineAutoReturn = 0x0008 -) - -// vtInputSupported is true if enableVirtualTerminalInput is supported by the console -var vtInputSupported bool - -// StdStreams returns the standard streams (stdin, stdout, stderr). -func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { - // Turn on VT handling on all std handles, if possible. This might - // fail, in which case we will fall back to terminal emulation. - var emulateStdin, emulateStdout, emulateStderr bool - fd := os.Stdin.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate that enableVirtualTerminalInput is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|enableVirtualTerminalInput); err != nil { - emulateStdin = true - } else { - vtInputSupported = true - } - // Unconditionally set the console mode back even on failure because SetConsoleMode - // remembers invalid bits on input handles. - winterm.SetConsoleMode(fd, mode) - } - - fd = os.Stdout.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate disableNewlineAutoReturn is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|enableVirtualTerminalProcessing|disableNewlineAutoReturn); err != nil { - emulateStdout = true - } else { - winterm.SetConsoleMode(fd, mode|enableVirtualTerminalProcessing) - } - } - - fd = os.Stderr.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate disableNewlineAutoReturn is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|enableVirtualTerminalProcessing|disableNewlineAutoReturn); err != nil { - emulateStderr = true - } else { - winterm.SetConsoleMode(fd, mode|enableVirtualTerminalProcessing) - } - } - - if os.Getenv("ConEmuANSI") == "ON" || os.Getenv("ConsoleZVersion") != "" { - // The ConEmu and ConsoleZ terminals emulate ANSI on output streams well. - emulateStdin = true - emulateStdout = false - emulateStderr = false - } - - if emulateStdin { - stdIn = windows.NewAnsiReader(syscall.STD_INPUT_HANDLE) - } else { - stdIn = os.Stdin - } - - if emulateStdout { - stdOut = windows.NewAnsiWriter(syscall.STD_OUTPUT_HANDLE) - } else { - stdOut = os.Stdout - } - - if emulateStderr { - stdErr = windows.NewAnsiWriter(syscall.STD_ERROR_HANDLE) - } else { - stdErr = os.Stderr - } - - return -} - -// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. -func GetFdInfo(in interface{}) (uintptr, bool) { - return windows.GetHandleInfo(in) -} - -// GetWinsize returns the window size based on the specified file descriptor. -func GetWinsize(fd uintptr) (*Winsize, error) { - info, err := winterm.GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil, err - } - - winsize := &Winsize{ - Width: uint16(info.Window.Right - info.Window.Left + 1), - Height: uint16(info.Window.Bottom - info.Window.Top + 1), - } - - return winsize, nil -} - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(fd uintptr) bool { - return windows.IsConsole(fd) -} - -// RestoreTerminal restores the terminal connected to the given file descriptor -// to a previous state. -func RestoreTerminal(fd uintptr, state *State) error { - return winterm.SetConsoleMode(fd, state.mode) -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - mode, e := winterm.GetConsoleMode(fd) - if e != nil { - return nil, e - } - - return &State{mode: mode}, nil -} - -// DisableEcho disables echo for the terminal connected to the given file descriptor. -// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx -func DisableEcho(fd uintptr, state *State) error { - mode := state.mode - mode &^= winterm.ENABLE_ECHO_INPUT - mode |= winterm.ENABLE_PROCESSED_INPUT | winterm.ENABLE_LINE_INPUT - err := winterm.SetConsoleMode(fd, mode) - if err != nil { - return err - } - - // Register an interrupt handler to catch and restore prior state - restoreAtInterrupt(fd, state) - return nil -} - -// SetRawTerminal puts the terminal connected to the given file descriptor into -// raw mode and returns the previous state. On UNIX, this puts both the input -// and output into raw mode. On Windows, it only puts the input into raw mode. -func SetRawTerminal(fd uintptr) (*State, error) { - state, err := MakeRaw(fd) - if err != nil { - return nil, err - } - - // Register an interrupt handler to catch and restore prior state - restoreAtInterrupt(fd, state) - return state, err -} - -// SetRawTerminalOutput puts the output of terminal connected to the given file -// descriptor into raw mode. On UNIX, this does nothing and returns nil for the -// state. On Windows, it disables LF -> CRLF translation. -func SetRawTerminalOutput(fd uintptr) (*State, error) { - state, err := SaveState(fd) - if err != nil { - return nil, err - } - - // Ignore failures, since disableNewlineAutoReturn might not be supported on this - // version of Windows. - winterm.SetConsoleMode(fd, state.mode|disableNewlineAutoReturn) - return state, err -} - -// MakeRaw puts the terminal (Windows Console) connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be restored. -func MakeRaw(fd uintptr) (*State, error) { - state, err := SaveState(fd) - if err != nil { - return nil, err - } - - mode := state.mode - - // See - // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx - // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx - - // Disable these modes - mode &^= winterm.ENABLE_ECHO_INPUT - mode &^= winterm.ENABLE_LINE_INPUT - mode &^= winterm.ENABLE_MOUSE_INPUT - mode &^= winterm.ENABLE_WINDOW_INPUT - mode &^= winterm.ENABLE_PROCESSED_INPUT - - // Enable these modes - mode |= winterm.ENABLE_EXTENDED_FLAGS - mode |= winterm.ENABLE_INSERT_MODE - mode |= winterm.ENABLE_QUICK_EDIT_MODE - if vtInputSupported { - mode |= enableVirtualTerminalInput - } - - err = winterm.SetConsoleMode(fd, mode) - if err != nil { - return nil, err - } - return state, nil -} - -func restoreAtInterrupt(fd uintptr, state *State) { - sigchan := make(chan os.Signal, 1) - signal.Notify(sigchan, os.Interrupt) - - go func() { - _ = <-sigchan - RestoreTerminal(fd, state) - os.Exit(0) - }() -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_darwin.go b/vendor/github.com/docker/docker/pkg/term/termios_darwin.go deleted file mode 100644 index 480db900ac..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_darwin.go +++ /dev/null @@ -1,69 +0,0 @@ -package term - -import ( - "syscall" - "unsafe" -) - -const ( - getTermios = syscall.TIOCGETA - setTermios = syscall.TIOCSETA -) - -// Termios magic numbers, passthrough to the ones defined in syscall. -const ( - IGNBRK = syscall.IGNBRK - PARMRK = syscall.PARMRK - INLCR = syscall.INLCR - IGNCR = syscall.IGNCR - ECHONL = syscall.ECHONL - CSIZE = syscall.CSIZE - ICRNL = syscall.ICRNL - ISTRIP = syscall.ISTRIP - PARENB = syscall.PARENB - ECHO = syscall.ECHO - ICANON = syscall.ICANON - ISIG = syscall.ISIG - IXON = syscall.IXON - BRKINT = syscall.BRKINT - INPCK = syscall.INPCK - OPOST = syscall.OPOST - CS8 = syscall.CS8 - IEXTEN = syscall.IEXTEN -) - -// Termios is the Unix API for terminal I/O. -type Termios struct { - Iflag uint64 - Oflag uint64 - Cflag uint64 - Lflag uint64 - Cc [20]byte - Ispeed uint64 - Ospeed uint64 -} - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { - return nil, err - } - - newState := oldState.termios - newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) - newState.Oflag &^= OPOST - newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) - newState.Cflag &^= (CSIZE | PARENB) - newState.Cflag |= CS8 - newState.Cc[syscall.VMIN] = 1 - newState.Cc[syscall.VTIME] = 0 - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { - return nil, err - } - - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go b/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go deleted file mode 100644 index ed843ad69c..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_freebsd.go +++ /dev/null @@ -1,69 +0,0 @@ -package term - -import ( - "syscall" - "unsafe" -) - -const ( - getTermios = syscall.TIOCGETA - setTermios = syscall.TIOCSETA -) - -// Termios magic numbers, passthrough to the ones defined in syscall. -const ( - IGNBRK = syscall.IGNBRK - PARMRK = syscall.PARMRK - INLCR = syscall.INLCR - IGNCR = syscall.IGNCR - ECHONL = syscall.ECHONL - CSIZE = syscall.CSIZE - ICRNL = syscall.ICRNL - ISTRIP = syscall.ISTRIP - PARENB = syscall.PARENB - ECHO = syscall.ECHO - ICANON = syscall.ICANON - ISIG = syscall.ISIG - IXON = syscall.IXON - BRKINT = syscall.BRKINT - INPCK = syscall.INPCK - OPOST = syscall.OPOST - CS8 = syscall.CS8 - IEXTEN = syscall.IEXTEN -) - -// Termios is the Unix API for terminal I/O. -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]byte - Ispeed uint32 - Ospeed uint32 -} - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { - return nil, err - } - - newState := oldState.termios - newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) - newState.Oflag &^= OPOST - newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) - newState.Cflag &^= (CSIZE | PARENB) - newState.Cflag |= CS8 - newState.Cc[syscall.VMIN] = 1 - newState.Cc[syscall.VTIME] = 0 - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { - return nil, err - } - - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_linux.go b/vendor/github.com/docker/docker/pkg/term/termios_linux.go deleted file mode 100644 index 22921b6aef..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_linux.go +++ /dev/null @@ -1,47 +0,0 @@ -// +build !cgo - -package term - -import ( - "syscall" - "unsafe" -) - -const ( - getTermios = syscall.TCGETS - setTermios = syscall.TCSETS -) - -// Termios is the Unix API for terminal I/O. -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]byte - Ispeed uint32 - Ospeed uint32 -} - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { - return nil, err - } - - newState := oldState.termios - - newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON) - newState.Oflag &^= syscall.OPOST - newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) - newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) - newState.Cflag |= syscall.CS8 - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { - return nil, err - } - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go b/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go deleted file mode 100644 index ed843ad69c..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_openbsd.go +++ /dev/null @@ -1,69 +0,0 @@ -package term - -import ( - "syscall" - "unsafe" -) - -const ( - getTermios = syscall.TIOCGETA - setTermios = syscall.TIOCSETA -) - -// Termios magic numbers, passthrough to the ones defined in syscall. -const ( - IGNBRK = syscall.IGNBRK - PARMRK = syscall.PARMRK - INLCR = syscall.INLCR - IGNCR = syscall.IGNCR - ECHONL = syscall.ECHONL - CSIZE = syscall.CSIZE - ICRNL = syscall.ICRNL - ISTRIP = syscall.ISTRIP - PARENB = syscall.PARENB - ECHO = syscall.ECHO - ICANON = syscall.ICANON - ISIG = syscall.ISIG - IXON = syscall.IXON - BRKINT = syscall.BRKINT - INPCK = syscall.INPCK - OPOST = syscall.OPOST - CS8 = syscall.CS8 - IEXTEN = syscall.IEXTEN -) - -// Termios is the Unix API for terminal I/O. -type Termios struct { - Iflag uint32 - Oflag uint32 - Cflag uint32 - Lflag uint32 - Cc [20]byte - Ispeed uint32 - Ospeed uint32 -} - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { - return nil, err - } - - newState := oldState.termios - newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) - newState.Oflag &^= OPOST - newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) - newState.Cflag &^= (CSIZE | PARENB) - newState.Cflag |= CS8 - newState.Cc[syscall.VMIN] = 1 - newState.Cc[syscall.VTIME] = 0 - - if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { - return nil, err - } - - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go deleted file mode 100644 index cb0b88356d..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go +++ /dev/null @@ -1,263 +0,0 @@ -// +build windows - -package windows - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "strings" - "unsafe" - - ansiterm "github.com/Azure/go-ansiterm" - "github.com/Azure/go-ansiterm/winterm" -) - -const ( - escapeSequence = ansiterm.KEY_ESC_CSI -) - -// ansiReader wraps a standard input file (e.g., os.Stdin) providing ANSI sequence translation. -type ansiReader struct { - file *os.File - fd uintptr - buffer []byte - cbBuffer int - command []byte -} - -// NewAnsiReader returns an io.ReadCloser that provides VT100 terminal emulation on top of a -// Windows console input handle. -func NewAnsiReader(nFile int) io.ReadCloser { - initLogger() - file, fd := winterm.GetStdFile(nFile) - return &ansiReader{ - file: file, - fd: fd, - command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), - buffer: make([]byte, 0), - } -} - -// Close closes the wrapped file. -func (ar *ansiReader) Close() (err error) { - return ar.file.Close() -} - -// Fd returns the file descriptor of the wrapped file. -func (ar *ansiReader) Fd() uintptr { - return ar.fd -} - -// Read reads up to len(p) bytes of translated input events into p. -func (ar *ansiReader) Read(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - - // Previously read bytes exist, read as much as we can and return - if len(ar.buffer) > 0 { - logger.Debugf("Reading previously cached bytes") - - originalLength := len(ar.buffer) - copiedLength := copy(p, ar.buffer) - - if copiedLength == originalLength { - ar.buffer = make([]byte, 0, len(p)) - } else { - ar.buffer = ar.buffer[copiedLength:] - } - - logger.Debugf("Read from cache p[%d]: % x", copiedLength, p) - return copiedLength, nil - } - - // Read and translate key events - events, err := readInputEvents(ar.fd, len(p)) - if err != nil { - return 0, err - } else if len(events) == 0 { - logger.Debug("No input events detected") - return 0, nil - } - - keyBytes := translateKeyEvents(events, []byte(escapeSequence)) - - // Save excess bytes and right-size keyBytes - if len(keyBytes) > len(p) { - logger.Debugf("Received %d keyBytes, only room for %d bytes", len(keyBytes), len(p)) - ar.buffer = keyBytes[len(p):] - keyBytes = keyBytes[:len(p)] - } else if len(keyBytes) == 0 { - logger.Debug("No key bytes returned from the translator") - return 0, nil - } - - copiedLength := copy(p, keyBytes) - if copiedLength != len(keyBytes) { - return 0, errors.New("unexpected copy length encountered") - } - - logger.Debugf("Read p[%d]: % x", copiedLength, p) - logger.Debugf("Read keyBytes[%d]: % x", copiedLength, keyBytes) - return copiedLength, nil -} - -// readInputEvents polls until at least one event is available. -func readInputEvents(fd uintptr, maxBytes int) ([]winterm.INPUT_RECORD, error) { - // Determine the maximum number of records to retrieve - // -- Cast around the type system to obtain the size of a single INPUT_RECORD. - // unsafe.Sizeof requires an expression vs. a type-reference; the casting - // tricks the type system into believing it has such an expression. - recordSize := int(unsafe.Sizeof(*((*winterm.INPUT_RECORD)(unsafe.Pointer(&maxBytes))))) - countRecords := maxBytes / recordSize - if countRecords > ansiterm.MAX_INPUT_EVENTS { - countRecords = ansiterm.MAX_INPUT_EVENTS - } else if countRecords == 0 { - countRecords = 1 - } - logger.Debugf("[windows] readInputEvents: Reading %v records (buffer size %v, record size %v)", countRecords, maxBytes, recordSize) - - // Wait for and read input events - events := make([]winterm.INPUT_RECORD, countRecords) - nEvents := uint32(0) - eventsExist, err := winterm.WaitForSingleObject(fd, winterm.WAIT_INFINITE) - if err != nil { - return nil, err - } - - if eventsExist { - err = winterm.ReadConsoleInput(fd, events, &nEvents) - if err != nil { - return nil, err - } - } - - // Return a slice restricted to the number of returned records - logger.Debugf("[windows] readInputEvents: Read %v events", nEvents) - return events[:nEvents], nil -} - -// KeyEvent Translation Helpers - -var arrowKeyMapPrefix = map[uint16]string{ - winterm.VK_UP: "%s%sA", - winterm.VK_DOWN: "%s%sB", - winterm.VK_RIGHT: "%s%sC", - winterm.VK_LEFT: "%s%sD", -} - -var keyMapPrefix = map[uint16]string{ - winterm.VK_UP: "\x1B[%sA", - winterm.VK_DOWN: "\x1B[%sB", - winterm.VK_RIGHT: "\x1B[%sC", - winterm.VK_LEFT: "\x1B[%sD", - winterm.VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 - winterm.VK_END: "\x1B[4%s~", // showkey shows ^[[4 - winterm.VK_INSERT: "\x1B[2%s~", - winterm.VK_DELETE: "\x1B[3%s~", - winterm.VK_PRIOR: "\x1B[5%s~", - winterm.VK_NEXT: "\x1B[6%s~", - winterm.VK_F1: "", - winterm.VK_F2: "", - winterm.VK_F3: "\x1B[13%s~", - winterm.VK_F4: "\x1B[14%s~", - winterm.VK_F5: "\x1B[15%s~", - winterm.VK_F6: "\x1B[17%s~", - winterm.VK_F7: "\x1B[18%s~", - winterm.VK_F8: "\x1B[19%s~", - winterm.VK_F9: "\x1B[20%s~", - winterm.VK_F10: "\x1B[21%s~", - winterm.VK_F11: "\x1B[23%s~", - winterm.VK_F12: "\x1B[24%s~", -} - -// translateKeyEvents converts the input events into the appropriate ANSI string. -func translateKeyEvents(events []winterm.INPUT_RECORD, escapeSequence []byte) []byte { - var buffer bytes.Buffer - for _, event := range events { - if event.EventType == winterm.KEY_EVENT && event.KeyEvent.KeyDown != 0 { - buffer.WriteString(keyToString(&event.KeyEvent, escapeSequence)) - } - } - - return buffer.Bytes() -} - -// keyToString maps the given input event record to the corresponding string. -func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) string { - if keyEvent.UnicodeChar == 0 { - return formatVirtualKey(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) - } - - _, alt, control := getControlKeys(keyEvent.ControlKeyState) - if control { - // TODO(azlinux): Implement following control sequences - // -D Signals the end of input from the keyboard; also exits current shell. - // -H Deletes the first character to the left of the cursor. Also called the ERASE key. - // -Q Restarts printing after it has been stopped with -s. - // -S Suspends printing on the screen (does not stop the program). - // -U Deletes all characters on the current line. Also called the KILL key. - // -E Quits current command and creates a core - - } - - // +Key generates ESC N Key - if !control && alt { - return ansiterm.KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) - } - - return string(keyEvent.UnicodeChar) -} - -// formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string. -func formatVirtualKey(key uint16, controlState uint32, escapeSequence []byte) string { - shift, alt, control := getControlKeys(controlState) - modifier := getControlKeysModifier(shift, alt, control) - - if format, ok := arrowKeyMapPrefix[key]; ok { - return fmt.Sprintf(format, escapeSequence, modifier) - } - - if format, ok := keyMapPrefix[key]; ok { - return fmt.Sprintf(format, modifier) - } - - return "" -} - -// getControlKeys extracts the shift, alt, and ctrl key states. -func getControlKeys(controlState uint32) (shift, alt, control bool) { - shift = 0 != (controlState & winterm.SHIFT_PRESSED) - alt = 0 != (controlState & (winterm.LEFT_ALT_PRESSED | winterm.RIGHT_ALT_PRESSED)) - control = 0 != (controlState & (winterm.LEFT_CTRL_PRESSED | winterm.RIGHT_CTRL_PRESSED)) - return shift, alt, control -} - -// getControlKeysModifier returns the ANSI modifier for the given combination of control keys. -func getControlKeysModifier(shift, alt, control bool) string { - if shift && alt && control { - return ansiterm.KEY_CONTROL_PARAM_8 - } - if alt && control { - return ansiterm.KEY_CONTROL_PARAM_7 - } - if shift && control { - return ansiterm.KEY_CONTROL_PARAM_6 - } - if control { - return ansiterm.KEY_CONTROL_PARAM_5 - } - if shift && alt { - return ansiterm.KEY_CONTROL_PARAM_4 - } - if alt { - return ansiterm.KEY_CONTROL_PARAM_3 - } - if shift { - return ansiterm.KEY_CONTROL_PARAM_2 - } - return "" -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go deleted file mode 100644 index a3ce5697d9..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build windows - -package windows - -import ( - "io" - "os" - - ansiterm "github.com/Azure/go-ansiterm" - "github.com/Azure/go-ansiterm/winterm" -) - -// ansiWriter wraps a standard output file (e.g., os.Stdout) providing ANSI sequence translation. -type ansiWriter struct { - file *os.File - fd uintptr - infoReset *winterm.CONSOLE_SCREEN_BUFFER_INFO - command []byte - escapeSequence []byte - inAnsiSequence bool - parser *ansiterm.AnsiParser -} - -// NewAnsiWriter returns an io.Writer that provides VT100 terminal emulation on top of a -// Windows console output handle. -func NewAnsiWriter(nFile int) io.Writer { - initLogger() - file, fd := winterm.GetStdFile(nFile) - info, err := winterm.GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil - } - - parser := ansiterm.CreateParser("Ground", winterm.CreateWinEventHandler(fd, file)) - logger.Infof("newAnsiWriter: parser %p", parser) - - aw := &ansiWriter{ - file: file, - fd: fd, - infoReset: info, - command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), - escapeSequence: []byte(ansiterm.KEY_ESC_CSI), - parser: parser, - } - - logger.Infof("newAnsiWriter: aw.parser %p", aw.parser) - logger.Infof("newAnsiWriter: %v", aw) - return aw -} - -func (aw *ansiWriter) Fd() uintptr { - return aw.fd -} - -// Write writes len(p) bytes from p to the underlying data stream. -func (aw *ansiWriter) Write(p []byte) (total int, err error) { - if len(p) == 0 { - return 0, nil - } - - logger.Infof("Write: % x", p) - logger.Infof("Write: %s", string(p)) - return aw.parser.Parse(p) -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/console.go b/vendor/github.com/docker/docker/pkg/term/windows/console.go deleted file mode 100644 index ca5c3b2e53..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/console.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build windows - -package windows - -import ( - "os" - - "github.com/Azure/go-ansiterm/winterm" -) - -// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. -func GetHandleInfo(in interface{}) (uintptr, bool) { - switch t := in.(type) { - case *ansiReader: - return t.Fd(), true - case *ansiWriter: - return t.Fd(), true - } - - var inFd uintptr - var isTerminal bool - - if file, ok := in.(*os.File); ok { - inFd = file.Fd() - isTerminal = IsConsole(inFd) - } - return inFd, isTerminal -} - -// IsConsole returns true if the given file descriptor is a Windows Console. -// The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. -func IsConsole(fd uintptr) bool { - _, e := winterm.GetConsoleMode(fd) - return e == nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/windows.go b/vendor/github.com/docker/docker/pkg/term/windows/windows.go deleted file mode 100644 index ce4cb5990e..0000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/windows.go +++ /dev/null @@ -1,33 +0,0 @@ -// These files implement ANSI-aware input and output streams for use by the Docker Windows client. -// When asked for the set of standard streams (e.g., stdin, stdout, stderr), the code will create -// and return pseudo-streams that convert ANSI sequences to / from Windows Console API calls. - -package windows - -import ( - "io/ioutil" - "os" - "sync" - - ansiterm "github.com/Azure/go-ansiterm" - "github.com/Sirupsen/logrus" -) - -var logger *logrus.Logger -var initOnce sync.Once - -func initLogger() { - initOnce.Do(func() { - logFile := ioutil.Discard - - if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { - logFile, _ = os.Create("ansiReaderWriter.log") - } - - logger = &logrus.Logger{ - Out: logFile, - Formatter: new(logrus.TextFormatter), - Level: logrus.DebugLevel, - } - }) -} diff --git a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone.go b/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone.go deleted file mode 100644 index e4dec3a5d1..0000000000 --- a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build go1.8 - -package tlsconfig - -import "crypto/tls" - -// Clone returns a clone of tls.Config. This function is provided for -// compatibility for go1.7 that doesn't include this method in stdlib. -func Clone(c *tls.Config) *tls.Config { - return c.Clone() -} diff --git a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go16.go b/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go16.go deleted file mode 100644 index 0b816650ec..0000000000 --- a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go16.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build go1.6,!go1.7 - -package tlsconfig - -import "crypto/tls" - -// Clone returns a clone of tls.Config. This function is provided for -// compatibility for go1.6 that doesn't include this method in stdlib. -func Clone(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - } -} diff --git a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go17.go b/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go17.go deleted file mode 100644 index 0d5b448fec..0000000000 --- a/vendor/github.com/docker/docker/pkg/tlsconfig/tlsconfig_clone_go17.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.7,!go1.8 - -package tlsconfig - -import "crypto/tls" - -// Clone returns a clone of tls.Config. This function is provided for -// compatibility for go1.7 that doesn't include this method in stdlib. -func Clone(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/vendor/github.com/docker/go-connections/LICENSE b/vendor/github.com/docker/go-connections/LICENSE deleted file mode 100644 index b55b37bc31..0000000000 --- a/vendor/github.com/docker/go-connections/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/docker/go-connections/nat/nat.go b/vendor/github.com/docker/go-connections/nat/nat.go deleted file mode 100644 index 4d5f5ae63a..0000000000 --- a/vendor/github.com/docker/go-connections/nat/nat.go +++ /dev/null @@ -1,242 +0,0 @@ -// Package nat is a convenience package for manipulation of strings describing network ports. -package nat - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -const ( - // portSpecTemplate is the expected format for port specifications - portSpecTemplate = "ip:hostPort:containerPort" -) - -// PortBinding represents a binding between a Host IP address and a Host Port -type PortBinding struct { - // HostIP is the host IP Address - HostIP string `json:"HostIp"` - // HostPort is the host port number - HostPort string -} - -// PortMap is a collection of PortBinding indexed by Port -type PortMap map[Port][]PortBinding - -// PortSet is a collection of structs indexed by Port -type PortSet map[Port]struct{} - -// Port is a string containing port number and protocol in the format "80/tcp" -type Port string - -// NewPort creates a new instance of a Port given a protocol and port number or port range -func NewPort(proto, port string) (Port, error) { - // Check for parsing issues on "port" now so we can avoid having - // to check it later on. - - portStartInt, portEndInt, err := ParsePortRangeToInt(port) - if err != nil { - return "", err - } - - if portStartInt == portEndInt { - return Port(fmt.Sprintf("%d/%s", portStartInt, proto)), nil - } - return Port(fmt.Sprintf("%d-%d/%s", portStartInt, portEndInt, proto)), nil -} - -// ParsePort parses the port number string and returns an int -func ParsePort(rawPort string) (int, error) { - if len(rawPort) == 0 { - return 0, nil - } - port, err := strconv.ParseUint(rawPort, 10, 16) - if err != nil { - return 0, err - } - return int(port), nil -} - -// ParsePortRangeToInt parses the port range string and returns start/end ints -func ParsePortRangeToInt(rawPort string) (int, int, error) { - if len(rawPort) == 0 { - return 0, 0, nil - } - start, end, err := ParsePortRange(rawPort) - if err != nil { - return 0, 0, err - } - return int(start), int(end), nil -} - -// Proto returns the protocol of a Port -func (p Port) Proto() string { - proto, _ := SplitProtoPort(string(p)) - return proto -} - -// Port returns the port number of a Port -func (p Port) Port() string { - _, port := SplitProtoPort(string(p)) - return port -} - -// Int returns the port number of a Port as an int -func (p Port) Int() int { - portStr := p.Port() - // We don't need to check for an error because we're going to - // assume that any error would have been found, and reported, in NewPort() - port, _ := ParsePort(portStr) - return port -} - -// Range returns the start/end port numbers of a Port range as ints -func (p Port) Range() (int, int, error) { - return ParsePortRangeToInt(p.Port()) -} - -// SplitProtoPort splits a port in the format of proto/port -func SplitProtoPort(rawPort string) (string, string) { - parts := strings.Split(rawPort, "/") - l := len(parts) - if len(rawPort) == 0 || l == 0 || len(parts[0]) == 0 { - return "", "" - } - if l == 1 { - return "tcp", rawPort - } - if len(parts[1]) == 0 { - return "tcp", parts[0] - } - return parts[1], parts[0] -} - -func validateProto(proto string) bool { - for _, availableProto := range []string{"tcp", "udp"} { - if availableProto == proto { - return true - } - } - return false -} - -// ParsePortSpecs receives port specs in the format of ip:public:private/proto and parses -// these in to the internal types -func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, error) { - var ( - exposedPorts = make(map[Port]struct{}, len(ports)) - bindings = make(map[Port][]PortBinding) - ) - for _, rawPort := range ports { - portMappings, err := ParsePortSpec(rawPort) - if err != nil { - return nil, nil, err - } - - for _, portMapping := range portMappings { - port := portMapping.Port - if _, exists := exposedPorts[port]; !exists { - exposedPorts[port] = struct{}{} - } - bslice, exists := bindings[port] - if !exists { - bslice = []PortBinding{} - } - bindings[port] = append(bslice, portMapping.Binding) - } - } - return exposedPorts, bindings, nil -} - -// PortMapping is a data object mapping a Port to a PortBinding -type PortMapping struct { - Port Port - Binding PortBinding -} - -func splitParts(rawport string) (string, string, string) { - parts := strings.Split(rawport, ":") - n := len(parts) - containerport := parts[n-1] - - switch n { - case 1: - return "", "", containerport - case 2: - return "", parts[0], containerport - case 3: - return parts[0], parts[1], containerport - default: - return strings.Join(parts[:n-2], ":"), parts[n-2], containerport - } -} - -// ParsePortSpec parses a port specification string into a slice of PortMappings -func ParsePortSpec(rawPort string) ([]PortMapping, error) { - var proto string - rawIP, hostPort, containerPort := splitParts(rawPort) - proto, containerPort = SplitProtoPort(containerPort) - - // Strip [] from IPV6 addresses - ip, _, err := net.SplitHostPort(rawIP + ":") - if err != nil { - return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) - } - if ip != "" && net.ParseIP(ip) == nil { - return nil, fmt.Errorf("Invalid ip address: %s", ip) - } - if containerPort == "" { - return nil, fmt.Errorf("No port specified: %s", rawPort) - } - - startPort, endPort, err := ParsePortRange(containerPort) - if err != nil { - return nil, fmt.Errorf("Invalid containerPort: %s", containerPort) - } - - var startHostPort, endHostPort uint64 = 0, 0 - if len(hostPort) > 0 { - startHostPort, endHostPort, err = ParsePortRange(hostPort) - if err != nil { - return nil, fmt.Errorf("Invalid hostPort: %s", hostPort) - } - } - - if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { - // Allow host port range iff containerPort is not a range. - // In this case, use the host port range as the dynamic - // host port range to allocate into. - if endPort != startPort { - return nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) - } - } - - if !validateProto(strings.ToLower(proto)) { - return nil, fmt.Errorf("Invalid proto: %s", proto) - } - - ports := []PortMapping{} - for i := uint64(0); i <= (endPort - startPort); i++ { - containerPort = strconv.FormatUint(startPort+i, 10) - if len(hostPort) > 0 { - hostPort = strconv.FormatUint(startHostPort+i, 10) - } - // Set hostPort to a range only if there is a single container port - // and a dynamic host port. - if startPort == endPort && startHostPort != endHostPort { - hostPort = fmt.Sprintf("%s-%s", hostPort, strconv.FormatUint(endHostPort, 10)) - } - port, err := NewPort(strings.ToLower(proto), containerPort) - if err != nil { - return nil, err - } - - binding := PortBinding{ - HostIP: ip, - HostPort: hostPort, - } - ports = append(ports, PortMapping{Port: port, Binding: binding}) - } - return ports, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/parse.go b/vendor/github.com/docker/go-connections/nat/parse.go deleted file mode 100644 index 892adf8c66..0000000000 --- a/vendor/github.com/docker/go-connections/nat/parse.go +++ /dev/null @@ -1,57 +0,0 @@ -package nat - -import ( - "fmt" - "strconv" - "strings" -) - -// PartParser parses and validates the specified string (data) using the specified template -// e.g. ip:public:private -> 192.168.0.1:80:8000 -// DEPRECATED: do not use, this function may be removed in a future version -func PartParser(template, data string) (map[string]string, error) { - // ip:public:private - var ( - templateParts = strings.Split(template, ":") - parts = strings.Split(data, ":") - out = make(map[string]string, len(templateParts)) - ) - if len(parts) != len(templateParts) { - return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template) - } - - for i, t := range templateParts { - value := "" - if len(parts) > i { - value = parts[i] - } - out[t] = value - } - return out, nil -} - -// ParsePortRange parses and validates the specified string as a port-range (8000-9000) -func ParsePortRange(ports string) (uint64, uint64, error) { - if ports == "" { - return 0, 0, fmt.Errorf("Empty string specified for ports.") - } - if !strings.Contains(ports, "-") { - start, err := strconv.ParseUint(ports, 10, 16) - end := start - return start, end, err - } - - parts := strings.Split(ports, "-") - start, err := strconv.ParseUint(parts[0], 10, 16) - if err != nil { - return 0, 0, err - } - end, err := strconv.ParseUint(parts[1], 10, 16) - if err != nil { - return 0, 0, err - } - if end < start { - return 0, 0, fmt.Errorf("Invalid range specified for the Port: %s", ports) - } - return start, end, nil -} diff --git a/vendor/github.com/docker/go-connections/nat/sort.go b/vendor/github.com/docker/go-connections/nat/sort.go deleted file mode 100644 index ce950171e3..0000000000 --- a/vendor/github.com/docker/go-connections/nat/sort.go +++ /dev/null @@ -1,96 +0,0 @@ -package nat - -import ( - "sort" - "strings" -) - -type portSorter struct { - ports []Port - by func(i, j Port) bool -} - -func (s *portSorter) Len() int { - return len(s.ports) -} - -func (s *portSorter) Swap(i, j int) { - s.ports[i], s.ports[j] = s.ports[j], s.ports[i] -} - -func (s *portSorter) Less(i, j int) bool { - ip := s.ports[i] - jp := s.ports[j] - - return s.by(ip, jp) -} - -// Sort sorts a list of ports using the provided predicate -// This function should compare `i` and `j`, returning true if `i` is -// considered to be less than `j` -func Sort(ports []Port, predicate func(i, j Port) bool) { - s := &portSorter{ports, predicate} - sort.Sort(s) -} - -type portMapEntry struct { - port Port - binding PortBinding -} - -type portMapSorter []portMapEntry - -func (s portMapSorter) Len() int { return len(s) } -func (s portMapSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// sort the port so that the order is: -// 1. port with larger specified bindings -// 2. larger port -// 3. port with tcp protocol -func (s portMapSorter) Less(i, j int) bool { - pi, pj := s[i].port, s[j].port - hpi, hpj := toInt(s[i].binding.HostPort), toInt(s[j].binding.HostPort) - return hpi > hpj || pi.Int() > pj.Int() || (pi.Int() == pj.Int() && strings.ToLower(pi.Proto()) == "tcp") -} - -// SortPortMap sorts the list of ports and their respected mapping. The ports -// will explicit HostPort will be placed first. -func SortPortMap(ports []Port, bindings PortMap) { - s := portMapSorter{} - for _, p := range ports { - if binding, ok := bindings[p]; ok { - for _, b := range binding { - s = append(s, portMapEntry{port: p, binding: b}) - } - bindings[p] = []PortBinding{} - } else { - s = append(s, portMapEntry{port: p}) - } - } - - sort.Sort(s) - var ( - i int - pm = make(map[Port]struct{}) - ) - // reorder ports - for _, entry := range s { - if _, ok := pm[entry.port]; !ok { - ports[i] = entry.port - pm[entry.port] = struct{}{} - i++ - } - // reorder bindings for this port - if _, ok := bindings[entry.port]; ok { - bindings[entry.port] = append(bindings[entry.port], entry.binding) - } - } -} - -func toInt(s string) uint64 { - i, _, err := ParsePortRange(s) - if err != nil { - i = 0 - } - return i -} diff --git a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go b/vendor/github.com/docker/go-connections/sockets/inmem_socket.go deleted file mode 100644 index 99846ffddb..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/inmem_socket.go +++ /dev/null @@ -1,81 +0,0 @@ -package sockets - -import ( - "errors" - "net" - "sync" -) - -var errClosed = errors.New("use of closed network connection") - -// InmemSocket implements net.Listener using in-memory only connections. -type InmemSocket struct { - chConn chan net.Conn - chClose chan struct{} - addr string - mu sync.Mutex -} - -// dummyAddr is used to satisfy net.Addr for the in-mem socket -// it is just stored as a string and returns the string for all calls -type dummyAddr string - -// NewInmemSocket creates an in-memory only net.Listener -// The addr argument can be any string, but is used to satisfy the `Addr()` part -// of the net.Listener interface -func NewInmemSocket(addr string, bufSize int) *InmemSocket { - return &InmemSocket{ - chConn: make(chan net.Conn, bufSize), - chClose: make(chan struct{}), - addr: addr, - } -} - -// Addr returns the socket's addr string to satisfy net.Listener -func (s *InmemSocket) Addr() net.Addr { - return dummyAddr(s.addr) -} - -// Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn. -func (s *InmemSocket) Accept() (net.Conn, error) { - select { - case conn := <-s.chConn: - return conn, nil - case <-s.chClose: - return nil, errClosed - } -} - -// Close closes the listener. It will be unavailable for use once closed. -func (s *InmemSocket) Close() error { - s.mu.Lock() - defer s.mu.Unlock() - select { - case <-s.chClose: - default: - close(s.chClose) - } - return nil -} - -// Dial is used to establish a connection with the in-mem server -func (s *InmemSocket) Dial(network, addr string) (net.Conn, error) { - srvConn, clientConn := net.Pipe() - select { - case s.chConn <- srvConn: - case <-s.chClose: - return nil, errClosed - } - - return clientConn, nil -} - -// Network returns the addr string, satisfies net.Addr -func (a dummyAddr) Network() string { - return string(a) -} - -// String returns the string form -func (a dummyAddr) String() string { - return string(a) -} diff --git a/vendor/github.com/docker/go-connections/sockets/proxy.go b/vendor/github.com/docker/go-connections/sockets/proxy.go deleted file mode 100644 index 98e9a1dc61..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/proxy.go +++ /dev/null @@ -1,51 +0,0 @@ -package sockets - -import ( - "net" - "net/url" - "os" - "strings" - - "golang.org/x/net/proxy" -) - -// GetProxyEnv allows access to the uppercase and the lowercase forms of -// proxy-related variables. See the Go specification for details on these -// variables. https://golang.org/pkg/net/http/ -func GetProxyEnv(key string) string { - proxyValue := os.Getenv(strings.ToUpper(key)) - if proxyValue == "" { - return os.Getenv(strings.ToLower(key)) - } - return proxyValue -} - -// DialerFromEnvironment takes in a "direct" *net.Dialer and returns a -// proxy.Dialer which will route the connections through the proxy using the -// given dialer. -func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) { - allProxy := GetProxyEnv("all_proxy") - if len(allProxy) == 0 { - return direct, nil - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return direct, err - } - - proxyFromURL, err := proxy.FromURL(proxyURL, direct) - if err != nil { - return direct, err - } - - noProxy := GetProxyEnv("no_proxy") - if len(noProxy) == 0 { - return proxyFromURL, nil - } - - perHost := proxy.NewPerHost(proxyFromURL, direct) - perHost.AddFromString(noProxy) - - return perHost, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets.go b/vendor/github.com/docker/go-connections/sockets/sockets.go deleted file mode 100644 index a1d7beb4d8..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "errors" - "net" - "net/http" - "time" -) - -// Why 32? See https://github.com/docker/docker/pull/8035. -const defaultTimeout = 32 * time.Second - -// ErrProtocolNotAvailable is returned when a given transport protocol is not provided by the operating system. -var ErrProtocolNotAvailable = errors.New("protocol not available") - -// ConfigureTransport configures the specified Transport according to the -// specified proto and addr. -// If the proto is unix (using a unix socket to communicate) or npipe the -// compression is disabled. -func ConfigureTransport(tr *http.Transport, proto, addr string) error { - switch proto { - case "unix": - return configureUnixTransport(tr, proto, addr) - case "npipe": - return configureNpipeTransport(tr, proto, addr) - default: - tr.Proxy = http.ProxyFromEnvironment - dialer, err := DialerFromEnvironment(&net.Dialer{ - Timeout: defaultTimeout, - }) - if err != nil { - return err - } - tr.Dial = dialer.Dial - } - return nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go b/vendor/github.com/docker/go-connections/sockets/sockets_unix.go deleted file mode 100644 index 386cf0dbbd..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build !windows - -package sockets - -import ( - "fmt" - "net" - "net/http" - "syscall" - "time" -) - -const maxUnixSocketPathSize = len(syscall.RawSockaddrUnix{}.Path) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - if len(addr) > maxUnixSocketPathSize { - return fmt.Errorf("Unix socket path %q is too long", addr) - } - // No need for compression in local communications. - tr.DisableCompression = true - tr.Dial = func(_, _ string) (net.Conn, error) { - return net.DialTimeout(proto, addr, defaultTimeout) - } - return nil -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -// DialPipe connects to a Windows named pipe. -// This is not supported on other OSes. -func DialPipe(_ string, _ time.Duration) (net.Conn, error) { - return nil, syscall.EAFNOSUPPORT -} diff --git a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go b/vendor/github.com/docker/go-connections/sockets/sockets_windows.go deleted file mode 100644 index 5c21644e1f..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -package sockets - -import ( - "net" - "net/http" - "time" - - "github.com/Microsoft/go-winio" -) - -func configureUnixTransport(tr *http.Transport, proto, addr string) error { - return ErrProtocolNotAvailable -} - -func configureNpipeTransport(tr *http.Transport, proto, addr string) error { - // No need for compression in local communications. - tr.DisableCompression = true - tr.Dial = func(_, _ string) (net.Conn, error) { - return DialPipe(addr, defaultTimeout) - } - return nil -} - -// DialPipe connects to a Windows named pipe. -func DialPipe(addr string, timeout time.Duration) (net.Conn, error) { - return winio.DialPipe(addr, &timeout) -} diff --git a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go b/vendor/github.com/docker/go-connections/sockets/tcp_socket.go deleted file mode 100644 index 53cbb6c79e..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/tcp_socket.go +++ /dev/null @@ -1,22 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "crypto/tls" - "net" -) - -// NewTCPSocket creates a TCP socket listener with the specified address and -// the specified tls configuration. If TLSConfig is set, will encapsulate the -// TCP listener inside a TLS one. -func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) { - l, err := net.Listen("tcp", addr) - if err != nil { - return nil, err - } - if tlsConfig != nil { - tlsConfig.NextProtos = []string{"http/1.1"} - l = tls.NewListener(l, tlsConfig) - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/sockets/unix_socket.go b/vendor/github.com/docker/go-connections/sockets/unix_socket.go deleted file mode 100644 index a8b5dbb6fd..0000000000 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package sockets - -import ( - "net" - "os" - "syscall" -) - -// NewUnixSocket creates a unix socket with the specified path and group. -func NewUnixSocket(path string, gid int) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - mask := syscall.Umask(0777) - defer syscall.Umask(mask) - - l, err := net.Listen("unix", path) - if err != nil { - return nil, err - } - if err := os.Chown(path, 0, gid); err != nil { - l.Close() - return nil, err - } - if err := os.Chmod(path, 0660); err != nil { - l.Close() - return nil, err - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go deleted file mode 100644 index 1d5fa4c76d..0000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build go1.7 - -package tlsconfig - -import ( - "crypto/x509" - "runtime" - - "github.com/Sirupsen/logrus" -) - -// SystemCertPool returns a copy of the system cert pool, -// returns an error if failed to load or empty pool on windows. -func SystemCertPool() (*x509.CertPool, error) { - certpool, err := x509.SystemCertPool() - if err != nil && runtime.GOOS == "windows" { - logrus.Infof("Unable to use system certificate pool: %v", err) - return x509.NewCertPool(), nil - } - return certpool, err -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go deleted file mode 100644 index 262c95e8cd..0000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !go1.7 - -package tlsconfig - -import ( - "crypto/x509" - - "github.com/Sirupsen/logrus" -) - -// SystemCertPool returns an new empty cert pool, -// accessing system cert pool is supported in go 1.7 -func SystemCertPool() (*x509.CertPool, error) { - logrus.Warn("Unable to use system certificate pool: requires building with go 1.7 or later") - return x509.NewCertPool(), nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config.go b/vendor/github.com/docker/go-connections/tlsconfig/config.go deleted file mode 100644 index ad4b112ab3..0000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config.go +++ /dev/null @@ -1,246 +0,0 @@ -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -// As a reminder from https://golang.org/pkg/crypto/tls/#Config: -// A Config structure is used to configure a TLS client or server. After one has been passed to a TLS function it must not be modified. -// A Config may be reused; the tls package will also not modify it. -package tlsconfig - -import ( - "crypto/tls" - "crypto/x509" - "encoding/pem" - "fmt" - "io/ioutil" - "os" - - "github.com/Sirupsen/logrus" - "github.com/pkg/errors" -) - -// Options represents the information needed to create client and server TLS configurations. -type Options struct { - CAFile string - - // If either CertFile or KeyFile is empty, Client() will not load them - // preventing the client from authenticating to the server. - // However, Server() requires them and will error out if they are empty. - CertFile string - KeyFile string - - // client-only option - InsecureSkipVerify bool - // server-only option - ClientAuth tls.ClientAuthType - // If ExclusiveRootPools is set, then if a CA file is provided, the root pool used for TLS - // creds will include exclusively the roots in that CA file. If no CA file is provided, - // the system pool will be used. - ExclusiveRootPools bool - MinVersion uint16 - // If Passphrase is set, it will be used to decrypt a TLS private key - // if the key is encrypted - Passphrase string -} - -// Extra (server-side) accepted CBC cipher suites - will phase out in the future -var acceptedCBCCiphers = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, - tls.TLS_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_RSA_WITH_AES_128_CBC_SHA, -} - -// DefaultServerAcceptedCiphers should be uses by code which already has a crypto/tls -// options struct but wants to use a commonly accepted set of TLS cipher suites, with -// known weak algorithms removed. -var DefaultServerAcceptedCiphers = append(clientCipherSuites, acceptedCBCCiphers...) - -// allTLSVersions lists all the TLS versions and is used by the code that validates -// a uint16 value as a TLS version. -var allTLSVersions = map[uint16]struct{}{ - tls.VersionSSL30: {}, - tls.VersionTLS10: {}, - tls.VersionTLS11: {}, - tls.VersionTLS12: {}, -} - -// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration. -func ServerDefault() *tls.Config { - return &tls.Config{ - // Avoid fallback to SSL protocols < TLS1.0 - MinVersion: tls.VersionTLS10, - PreferServerCipherSuites: true, - CipherSuites: DefaultServerAcceptedCiphers, - } -} - -// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration. -func ClientDefault() *tls.Config { - return &tls.Config{ - // Prefer TLS1.2 as the client minimum - MinVersion: tls.VersionTLS12, - CipherSuites: clientCipherSuites, - } -} - -// certPool returns an X.509 certificate pool from `caFile`, the certificate file. -func certPool(caFile string, exclusivePool bool) (*x509.CertPool, error) { - // If we should verify the server, we need to load a trusted ca - var ( - certPool *x509.CertPool - err error - ) - if exclusivePool { - certPool = x509.NewCertPool() - } else { - certPool, err = SystemCertPool() - if err != nil { - return nil, fmt.Errorf("failed to read system certificates: %v", err) - } - } - pem, err := ioutil.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) - } - if !certPool.AppendCertsFromPEM(pem) { - return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) - } - logrus.Debugf("Trusting %d certs", len(certPool.Subjects())) - return certPool, nil -} - -// isValidMinVersion checks that the input value is a valid tls minimum version -func isValidMinVersion(version uint16) bool { - _, ok := allTLSVersions[version] - return ok -} - -// adjustMinVersion sets the MinVersion on `config`, the input configuration. -// It assumes the current MinVersion on the `config` is the lowest allowed. -func adjustMinVersion(options Options, config *tls.Config) error { - if options.MinVersion > 0 { - if !isValidMinVersion(options.MinVersion) { - return fmt.Errorf("Invalid minimum TLS version: %x", options.MinVersion) - } - if options.MinVersion < config.MinVersion { - return fmt.Errorf("Requested minimum TLS version is too low. Should be at-least: %x", config.MinVersion) - } - config.MinVersion = options.MinVersion - } - - return nil -} - -// IsErrEncryptedKey returns true if the 'err' is an error of incorrect -// password when tryin to decrypt a TLS private key -func IsErrEncryptedKey(err error) bool { - return errors.Cause(err) == x509.IncorrectPasswordError -} - -// getPrivateKey returns the private key in 'keyBytes', in PEM-encoded format. -// If the private key is encrypted, 'passphrase' is used to decrypted the -// private key. -func getPrivateKey(keyBytes []byte, passphrase string) ([]byte, error) { - // this section makes some small changes to code from notary/tuf/utils/x509.go - pemBlock, _ := pem.Decode(keyBytes) - if pemBlock == nil { - return nil, fmt.Errorf("no valid private key found") - } - - var err error - if x509.IsEncryptedPEMBlock(pemBlock) { - keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) - if err != nil { - return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") - } - keyBytes = pem.EncodeToMemory(&pem.Block{Type: pemBlock.Type, Bytes: keyBytes}) - } - - return keyBytes, nil -} - -// getCert returns a Certificate from the CertFile and KeyFile in 'options', -// if the key is encrypted, the Passphrase in 'options' will be used to -// decrypt it. -func getCert(options Options) ([]tls.Certificate, error) { - if options.CertFile == "" && options.KeyFile == "" { - return nil, nil - } - - errMessage := "Could not load X509 key pair" - - cert, err := ioutil.ReadFile(options.CertFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err := ioutil.ReadFile(options.KeyFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - return []tls.Certificate{tlsCert}, nil -} - -// Client returns a TLS configuration meant to be used by a client. -func Client(options Options) (*tls.Config, error) { - tlsConfig := ClientDefault() - tlsConfig.InsecureSkipVerify = options.InsecureSkipVerify - if !options.InsecureSkipVerify && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.RootCAs = CAs - } - - tlsCerts, err := getCert(options) - if err != nil { - return nil, err - } - tlsConfig.Certificates = tlsCerts - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} - -// Server returns a TLS configuration meant to be used by a server. -func Server(options Options) (*tls.Config, error) { - tlsConfig := ServerDefault() - tlsConfig.ClientAuth = options.ClientAuth - tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) - if err != nil { - if os.IsNotExist(err) { - return nil, fmt.Errorf("Could not load X509 key pair (cert: %q, key: %q): %v", options.CertFile, options.KeyFile, err) - } - return nil, fmt.Errorf("Error reading X509 key pair (cert: %q, key: %q): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) - } - tlsConfig.Certificates = []tls.Certificate{tlsCert} - if options.ClientAuth >= tls.VerifyClientCertIfGiven && options.CAFile != "" { - CAs, err := certPool(options.CAFile, options.ExclusiveRootPools) - if err != nil { - return nil, err - } - tlsConfig.ClientCAs = CAs - } - - if err := adjustMinVersion(options, tlsConfig); err != nil { - return nil, err - } - - return tlsConfig, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go deleted file mode 100644 index 6b4c6a7c0d..0000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build go1.5 - -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -package tlsconfig - -import ( - "crypto/tls" -) - -// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) -var clientCipherSuites = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go deleted file mode 100644 index ee22df47cb..0000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !go1.5 - -// Package tlsconfig provides primitives to retrieve secure-enough TLS configurations for both clients and servers. -// -package tlsconfig - -import ( - "crypto/tls" -) - -// Client TLS cipher suites (dropping CBC ciphers for client preferred suite set) -var clientCipherSuites = []uint16{ - tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} diff --git a/vendor/github.com/docker/go-units/CONTRIBUTING.md b/vendor/github.com/docker/go-units/CONTRIBUTING.md deleted file mode 100644 index 9ea86d784e..0000000000 --- a/vendor/github.com/docker/go-units/CONTRIBUTING.md +++ /dev/null @@ -1,67 +0,0 @@ -# Contributing to go-units - -Want to hack on go-units? Awesome! Here are instructions to get you started. - -go-units is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read Docker's -[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), -[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), -[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and -[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -660 York Street, Suite 102, -San Francisco, CA 94110 USA - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/docker/go-units/LICENSE b/vendor/github.com/docker/go-units/LICENSE deleted file mode 100644 index b55b37bc31..0000000000 --- a/vendor/github.com/docker/go-units/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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. - - END OF TERMS AND CONDITIONS - - Copyright 2015 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/docker/go-units/MAINTAINERS b/vendor/github.com/docker/go-units/MAINTAINERS deleted file mode 100644 index 477be8b214..0000000000 --- a/vendor/github.com/docker/go-units/MAINTAINERS +++ /dev/null @@ -1,27 +0,0 @@ -# go-connections maintainers file -# -# This file describes who runs the docker/go-connections project and how. -# This is a living document - if you see something out of date or missing, speak up! -# -# It is structured to be consumable by both humans and programs. -# To extract its contents programmatically, use any TOML-compliant parser. -# -# This file is compiled into the MAINTAINERS file in docker/opensource. -# -[Org] - [Org."Core maintainers"] - people = [ - "calavera", - ] - -[people] - -# A reference list of all people associated with the project. -# All other sections should refer to people by their canonical key -# in the people section. - - # ADD YOURSELF HERE IN ALPHABETICAL ORDER - [people.calavera] - Name = "David Calavera" - Email = "david.calavera@gmail.com" - GitHub = "calavera" diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md deleted file mode 100644 index 4f70a4e134..0000000000 --- a/vendor/github.com/docker/go-units/README.md +++ /dev/null @@ -1,16 +0,0 @@ -[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) - -# Introduction - -go-units is a library to transform human friendly measurements into machine friendly values. - -## Usage - -See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. - -## Copyright and license - -Copyright © 2015 Docker, Inc. - -go-units is licensed under the Apache License, Version 2.0. -See [LICENSE](LICENSE) for the full text of the license. diff --git a/vendor/github.com/docker/go-units/circle.yml b/vendor/github.com/docker/go-units/circle.yml deleted file mode 100644 index 9043b35478..0000000000 --- a/vendor/github.com/docker/go-units/circle.yml +++ /dev/null @@ -1,11 +0,0 @@ -dependencies: - post: - # install golint - - go get github.com/golang/lint/golint - -test: - pre: - # run analysis before tests - - go vet ./... - - test -z "$(golint ./... | tee /dev/stderr)" - - test -z "$(gofmt -s -l . | tee /dev/stderr)" diff --git a/vendor/github.com/docker/go-units/duration.go b/vendor/github.com/docker/go-units/duration.go deleted file mode 100644 index ba02af26dc..0000000000 --- a/vendor/github.com/docker/go-units/duration.go +++ /dev/null @@ -1,35 +0,0 @@ -// Package units provides helper function to parse and print size and time units -// in human-readable format. -package units - -import ( - "fmt" - "time" -) - -// HumanDuration returns a human-readable approximation of a duration -// (eg. "About a minute", "4 hours ago", etc.). -func HumanDuration(d time.Duration) string { - if seconds := int(d.Seconds()); seconds < 1 { - return "Less than a second" - } else if seconds == 1 { - return "1 second" - } else if seconds < 60 { - return fmt.Sprintf("%d seconds", seconds) - } else if minutes := int(d.Minutes()); minutes == 1 { - return "About a minute" - } else if minutes < 46 { - return fmt.Sprintf("%d minutes", minutes) - } else if hours := int(d.Hours() + 0.5); hours == 1 { - return "About an hour" - } else if hours < 48 { - return fmt.Sprintf("%d hours", hours) - } else if hours < 24*7*2 { - return fmt.Sprintf("%d days", hours/24) - } else if hours < 24*30*2 { - return fmt.Sprintf("%d weeks", hours/24/7) - } else if hours < 24*365*2 { - return fmt.Sprintf("%d months", hours/24/30) - } - return fmt.Sprintf("%d years", int(d.Hours())/24/365) -} diff --git a/vendor/github.com/docker/go-units/size.go b/vendor/github.com/docker/go-units/size.go deleted file mode 100644 index 44616c2718..0000000000 --- a/vendor/github.com/docker/go-units/size.go +++ /dev/null @@ -1,108 +0,0 @@ -package units - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -// See: http://en.wikipedia.org/wiki/Binary_prefix -const ( - // Decimal - - KB = 1000 - MB = 1000 * KB - GB = 1000 * MB - TB = 1000 * GB - PB = 1000 * TB - - // Binary - - KiB = 1024 - MiB = 1024 * KiB - GiB = 1024 * MiB - TiB = 1024 * GiB - PiB = 1024 * TiB -) - -type unitMap map[string]int64 - -var ( - decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB} - binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB} - sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[bB]?$`) -) - -var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} -var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"} - -func getSizeAndUnit(size float64, base float64, _map []string) (float64, string) { - i := 0 - unitsLimit := len(_map) - 1 - for size >= base && i < unitsLimit { - size = size / base - i++ - } - return size, _map[i] -} - -// CustomSize returns a human-readable approximation of a size -// using custom format. -func CustomSize(format string, size float64, base float64, _map []string) string { - size, unit := getSizeAndUnit(size, base, _map) - return fmt.Sprintf(format, size, unit) -} - -// HumanSizeWithPrecision allows the size to be in any precision, -// instead of 4 digit precision used in units.HumanSize. -func HumanSizeWithPrecision(size float64, precision int) string { - size, unit := getSizeAndUnit(size, 1000.0, decimapAbbrs) - return fmt.Sprintf("%.*g%s", precision, size, unit) -} - -// HumanSize returns a human-readable approximation of a size -// capped at 4 valid numbers (eg. "2.746 MB", "796 KB"). -func HumanSize(size float64) string { - return HumanSizeWithPrecision(size, 4) -} - -// BytesSize returns a human-readable size in bytes, kibibytes, -// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB"). -func BytesSize(size float64) string { - return CustomSize("%.4g%s", size, 1024.0, binaryAbbrs) -} - -// FromHumanSize returns an integer from a human-readable specification of a -// size using SI standard (eg. "44kB", "17MB"). -func FromHumanSize(size string) (int64, error) { - return parseSize(size, decimalMap) -} - -// RAMInBytes parses a human-readable string representing an amount of RAM -// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and -// returns the number of bytes, or -1 if the string is unparseable. -// Units are case-insensitive, and the 'b' suffix is optional. -func RAMInBytes(size string) (int64, error) { - return parseSize(size, binaryMap) -} - -// Parses the human-readable size string into the amount it represents. -func parseSize(sizeStr string, uMap unitMap) (int64, error) { - matches := sizeRegex.FindStringSubmatch(sizeStr) - if len(matches) != 4 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - size, err := strconv.ParseFloat(matches[1], 64) - if err != nil { - return -1, err - } - - unitPrefix := strings.ToLower(matches[3]) - if mul, ok := uMap[unitPrefix]; ok { - size *= float64(mul) - } - - return int64(size), nil -} diff --git a/vendor/github.com/docker/go-units/ulimit.go b/vendor/github.com/docker/go-units/ulimit.go deleted file mode 100644 index 5ac7fd825f..0000000000 --- a/vendor/github.com/docker/go-units/ulimit.go +++ /dev/null @@ -1,118 +0,0 @@ -package units - -import ( - "fmt" - "strconv" - "strings" -) - -// Ulimit is a human friendly version of Rlimit. -type Ulimit struct { - Name string - Hard int64 - Soft int64 -} - -// Rlimit specifies the resource limits, such as max open files. -type Rlimit struct { - Type int `json:"type,omitempty"` - Hard uint64 `json:"hard,omitempty"` - Soft uint64 `json:"soft,omitempty"` -} - -const ( - // magic numbers for making the syscall - // some of these are defined in the syscall package, but not all. - // Also since Windows client doesn't get access to the syscall package, need to - // define these here - rlimitAs = 9 - rlimitCore = 4 - rlimitCPU = 0 - rlimitData = 2 - rlimitFsize = 1 - rlimitLocks = 10 - rlimitMemlock = 8 - rlimitMsgqueue = 12 - rlimitNice = 13 - rlimitNofile = 7 - rlimitNproc = 6 - rlimitRss = 5 - rlimitRtprio = 14 - rlimitRttime = 15 - rlimitSigpending = 11 - rlimitStack = 3 -) - -var ulimitNameMapping = map[string]int{ - //"as": rlimitAs, // Disabled since this doesn't seem usable with the way Docker inits a container. - "core": rlimitCore, - "cpu": rlimitCPU, - "data": rlimitData, - "fsize": rlimitFsize, - "locks": rlimitLocks, - "memlock": rlimitMemlock, - "msgqueue": rlimitMsgqueue, - "nice": rlimitNice, - "nofile": rlimitNofile, - "nproc": rlimitNproc, - "rss": rlimitRss, - "rtprio": rlimitRtprio, - "rttime": rlimitRttime, - "sigpending": rlimitSigpending, - "stack": rlimitStack, -} - -// ParseUlimit parses and returns a Ulimit from the specified string. -func ParseUlimit(val string) (*Ulimit, error) { - parts := strings.SplitN(val, "=", 2) - if len(parts) != 2 { - return nil, fmt.Errorf("invalid ulimit argument: %s", val) - } - - if _, exists := ulimitNameMapping[parts[0]]; !exists { - return nil, fmt.Errorf("invalid ulimit type: %s", parts[0]) - } - - var ( - soft int64 - hard = &soft // default to soft in case no hard was set - temp int64 - err error - ) - switch limitVals := strings.Split(parts[1], ":"); len(limitVals) { - case 2: - temp, err = strconv.ParseInt(limitVals[1], 10, 64) - if err != nil { - return nil, err - } - hard = &temp - fallthrough - case 1: - soft, err = strconv.ParseInt(limitVals[0], 10, 64) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) - } - - if soft > *hard { - return nil, fmt.Errorf("ulimit soft limit must be less than or equal to hard limit: %d > %d", soft, *hard) - } - - return &Ulimit{Name: parts[0], Soft: soft, Hard: *hard}, nil -} - -// GetRlimit returns the RLimit corresponding to Ulimit. -func (u *Ulimit) GetRlimit() (*Rlimit, error) { - t, exists := ulimitNameMapping[u.Name] - if !exists { - return nil, fmt.Errorf("invalid ulimit name %s", u.Name) - } - - return &Rlimit{Type: t, Soft: uint64(u.Soft), Hard: uint64(u.Hard)}, nil -} - -func (u *Ulimit) String() string { - return fmt.Sprintf("%s=%d:%d", u.Name, u.Soft, u.Hard) -} diff --git a/vendor/github.com/docker/libtrust/CONTRIBUTING.md b/vendor/github.com/docker/libtrust/CONTRIBUTING.md deleted file mode 100644 index 05be0f8ab3..0000000000 --- a/vendor/github.com/docker/libtrust/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contributing to libtrust - -Want to hack on libtrust? Awesome! Here are instructions to get you -started. - -libtrust is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read -[Docker's contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md). - -Happy hacking! diff --git a/vendor/github.com/docker/libtrust/LICENSE b/vendor/github.com/docker/libtrust/LICENSE deleted file mode 100644 index 27448585ad..0000000000 --- a/vendor/github.com/docker/libtrust/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - Copyright 2014 Docker, Inc. - - 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. diff --git a/vendor/github.com/docker/libtrust/MAINTAINERS b/vendor/github.com/docker/libtrust/MAINTAINERS deleted file mode 100644 index 9768175feb..0000000000 --- a/vendor/github.com/docker/libtrust/MAINTAINERS +++ /dev/null @@ -1,3 +0,0 @@ -Solomon Hykes -Josh Hawn (github: jlhawn) -Derek McGowan (github: dmcgowan) diff --git a/vendor/github.com/docker/libtrust/README.md b/vendor/github.com/docker/libtrust/README.md deleted file mode 100644 index dcffb31ae4..0000000000 --- a/vendor/github.com/docker/libtrust/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# libtrust - -> **WARNING** this library is no longer actively developed, and will be integrated -> in the [docker/distribution][https://www.github.com/docker/distribution] -> repository in future. - -Libtrust is library for managing authentication and authorization using public key cryptography. - -Authentication is handled using the identity attached to the public key. -Libtrust provides multiple methods to prove possession of the private key associated with an identity. - - TLS x509 certificates - - Signature verification - - Key Challenge - -Authorization and access control is managed through a distributed trust graph. -Trust servers are used as the authorities of the trust graph and allow caching portions of the graph for faster access. - -## Copyright and license - -Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license. -Docs released under Creative commons. - diff --git a/vendor/github.com/docker/libtrust/certificates.go b/vendor/github.com/docker/libtrust/certificates.go deleted file mode 100644 index 3dcca33cb1..0000000000 --- a/vendor/github.com/docker/libtrust/certificates.go +++ /dev/null @@ -1,175 +0,0 @@ -package libtrust - -import ( - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "fmt" - "io/ioutil" - "math/big" - "net" - "time" -) - -type certTemplateInfo struct { - commonName string - domains []string - ipAddresses []net.IP - isCA bool - clientAuth bool - serverAuth bool -} - -func generateCertTemplate(info *certTemplateInfo) *x509.Certificate { - // Generate a certificate template which is valid from the past week to - // 10 years from now. The usage of the certificate depends on the - // specified fields in the given certTempInfo object. - var ( - keyUsage x509.KeyUsage - extKeyUsage []x509.ExtKeyUsage - ) - - if info.isCA { - keyUsage = x509.KeyUsageCertSign - } - - if info.clientAuth { - extKeyUsage = append(extKeyUsage, x509.ExtKeyUsageClientAuth) - } - - if info.serverAuth { - extKeyUsage = append(extKeyUsage, x509.ExtKeyUsageServerAuth) - } - - return &x509.Certificate{ - SerialNumber: big.NewInt(0), - Subject: pkix.Name{ - CommonName: info.commonName, - }, - NotBefore: time.Now().Add(-time.Hour * 24 * 7), - NotAfter: time.Now().Add(time.Hour * 24 * 365 * 10), - DNSNames: info.domains, - IPAddresses: info.ipAddresses, - IsCA: info.isCA, - KeyUsage: keyUsage, - ExtKeyUsage: extKeyUsage, - BasicConstraintsValid: info.isCA, - } -} - -func generateCert(pub PublicKey, priv PrivateKey, subInfo, issInfo *certTemplateInfo) (cert *x509.Certificate, err error) { - pubCertTemplate := generateCertTemplate(subInfo) - privCertTemplate := generateCertTemplate(issInfo) - - certDER, err := x509.CreateCertificate( - rand.Reader, pubCertTemplate, privCertTemplate, - pub.CryptoPublicKey(), priv.CryptoPrivateKey(), - ) - if err != nil { - return nil, fmt.Errorf("failed to create certificate: %s", err) - } - - cert, err = x509.ParseCertificate(certDER) - if err != nil { - return nil, fmt.Errorf("failed to parse certificate: %s", err) - } - - return -} - -// GenerateSelfSignedServerCert creates a self-signed certificate for the -// given key which is to be used for TLS servers with the given domains and -// IP addresses. -func GenerateSelfSignedServerCert(key PrivateKey, domains []string, ipAddresses []net.IP) (*x509.Certificate, error) { - info := &certTemplateInfo{ - commonName: key.KeyID(), - domains: domains, - ipAddresses: ipAddresses, - serverAuth: true, - } - - return generateCert(key.PublicKey(), key, info, info) -} - -// GenerateSelfSignedClientCert creates a self-signed certificate for the -// given key which is to be used for TLS clients. -func GenerateSelfSignedClientCert(key PrivateKey) (*x509.Certificate, error) { - info := &certTemplateInfo{ - commonName: key.KeyID(), - clientAuth: true, - } - - return generateCert(key.PublicKey(), key, info, info) -} - -// GenerateCACert creates a certificate which can be used as a trusted -// certificate authority. -func GenerateCACert(signer PrivateKey, trustedKey PublicKey) (*x509.Certificate, error) { - subjectInfo := &certTemplateInfo{ - commonName: trustedKey.KeyID(), - isCA: true, - } - issuerInfo := &certTemplateInfo{ - commonName: signer.KeyID(), - } - - return generateCert(trustedKey, signer, subjectInfo, issuerInfo) -} - -// GenerateCACertPool creates a certificate authority pool to be used for a -// TLS configuration. Any self-signed certificates issued by the specified -// trusted keys will be verified during a TLS handshake -func GenerateCACertPool(signer PrivateKey, trustedKeys []PublicKey) (*x509.CertPool, error) { - certPool := x509.NewCertPool() - - for _, trustedKey := range trustedKeys { - cert, err := GenerateCACert(signer, trustedKey) - if err != nil { - return nil, fmt.Errorf("failed to generate CA certificate: %s", err) - } - - certPool.AddCert(cert) - } - - return certPool, nil -} - -// LoadCertificateBundle loads certificates from the given file. The file should be pem encoded -// containing one or more certificates. The expected pem type is "CERTIFICATE". -func LoadCertificateBundle(filename string) ([]*x509.Certificate, error) { - b, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - certificates := []*x509.Certificate{} - var block *pem.Block - block, b = pem.Decode(b) - for ; block != nil; block, b = pem.Decode(b) { - if block.Type == "CERTIFICATE" { - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - return nil, err - } - certificates = append(certificates, cert) - } else { - return nil, fmt.Errorf("invalid pem block type: %s", block.Type) - } - } - - return certificates, nil -} - -// LoadCertificatePool loads a CA pool from the given file. The file should be pem encoded -// containing one or more certificates. The expected pem type is "CERTIFICATE". -func LoadCertificatePool(filename string) (*x509.CertPool, error) { - certs, err := LoadCertificateBundle(filename) - if err != nil { - return nil, err - } - pool := x509.NewCertPool() - for _, cert := range certs { - pool.AddCert(cert) - } - return pool, nil -} diff --git a/vendor/github.com/docker/libtrust/doc.go b/vendor/github.com/docker/libtrust/doc.go deleted file mode 100644 index ec5d2159c1..0000000000 --- a/vendor/github.com/docker/libtrust/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* -Package libtrust provides an interface for managing authentication and -authorization using public key cryptography. Authentication is handled -using the identity attached to the public key and verified through TLS -x509 certificates, a key challenge, or signature. Authorization and -access control is managed through a trust graph distributed between -both remote trust servers and locally cached and managed data. -*/ -package libtrust diff --git a/vendor/github.com/docker/libtrust/ec_key.go b/vendor/github.com/docker/libtrust/ec_key.go deleted file mode 100644 index 00bbe4b3ca..0000000000 --- a/vendor/github.com/docker/libtrust/ec_key.go +++ /dev/null @@ -1,428 +0,0 @@ -package libtrust - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "io" - "math/big" -) - -/* - * EC DSA PUBLIC KEY - */ - -// ecPublicKey implements a libtrust.PublicKey using elliptic curve digital -// signature algorithms. -type ecPublicKey struct { - *ecdsa.PublicKey - curveName string - signatureAlgorithm *signatureAlgorithm - extended map[string]interface{} -} - -func fromECPublicKey(cryptoPublicKey *ecdsa.PublicKey) (*ecPublicKey, error) { - curve := cryptoPublicKey.Curve - - switch { - case curve == elliptic.P256(): - return &ecPublicKey{cryptoPublicKey, "P-256", es256, map[string]interface{}{}}, nil - case curve == elliptic.P384(): - return &ecPublicKey{cryptoPublicKey, "P-384", es384, map[string]interface{}{}}, nil - case curve == elliptic.P521(): - return &ecPublicKey{cryptoPublicKey, "P-521", es512, map[string]interface{}{}}, nil - default: - return nil, errors.New("unsupported elliptic curve") - } -} - -// KeyType returns the key type for elliptic curve keys, i.e., "EC". -func (k *ecPublicKey) KeyType() string { - return "EC" -} - -// CurveName returns the elliptic curve identifier. -// Possible values are "P-256", "P-384", and "P-521". -func (k *ecPublicKey) CurveName() string { - return k.curveName -} - -// KeyID returns a distinct identifier which is unique to this Public Key. -func (k *ecPublicKey) KeyID() string { - return keyIDFromCryptoKey(k) -} - -func (k *ecPublicKey) String() string { - return fmt.Sprintf("EC Public Key <%s>", k.KeyID()) -} - -// Verify verifyies the signature of the data in the io.Reader using this -// PublicKey. The alg parameter should identify the digital signature -// algorithm which was used to produce the signature and should be supported -// by this public key. Returns a nil error if the signature is valid. -func (k *ecPublicKey) Verify(data io.Reader, alg string, signature []byte) error { - // For EC keys there is only one supported signature algorithm depending - // on the curve parameters. - if k.signatureAlgorithm.HeaderParam() != alg { - return fmt.Errorf("unable to verify signature: EC Public Key with curve %q does not support signature algorithm %q", k.curveName, alg) - } - - // signature is the concatenation of (r, s), base64Url encoded. - sigLength := len(signature) - expectedOctetLength := 2 * ((k.Params().BitSize + 7) >> 3) - if sigLength != expectedOctetLength { - return fmt.Errorf("signature length is %d octets long, should be %d", sigLength, expectedOctetLength) - } - - rBytes, sBytes := signature[:sigLength/2], signature[sigLength/2:] - r := new(big.Int).SetBytes(rBytes) - s := new(big.Int).SetBytes(sBytes) - - hasher := k.signatureAlgorithm.HashID().New() - _, err := io.Copy(hasher, data) - if err != nil { - return fmt.Errorf("error reading data to sign: %s", err) - } - hash := hasher.Sum(nil) - - if !ecdsa.Verify(k.PublicKey, hash, r, s) { - return errors.New("invalid signature") - } - - return nil -} - -// CryptoPublicKey returns the internal object which can be used as a -// crypto.PublicKey for use with other standard library operations. The type -// is either *rsa.PublicKey or *ecdsa.PublicKey -func (k *ecPublicKey) CryptoPublicKey() crypto.PublicKey { - return k.PublicKey -} - -func (k *ecPublicKey) toMap() map[string]interface{} { - jwk := make(map[string]interface{}) - for k, v := range k.extended { - jwk[k] = v - } - jwk["kty"] = k.KeyType() - jwk["kid"] = k.KeyID() - jwk["crv"] = k.CurveName() - - xBytes := k.X.Bytes() - yBytes := k.Y.Bytes() - octetLength := (k.Params().BitSize + 7) >> 3 - // MUST include leading zeros in the output so that x, y are each - // *octetLength* bytes long. - xBuf := make([]byte, octetLength-len(xBytes), octetLength) - yBuf := make([]byte, octetLength-len(yBytes), octetLength) - xBuf = append(xBuf, xBytes...) - yBuf = append(yBuf, yBytes...) - - jwk["x"] = joseBase64UrlEncode(xBuf) - jwk["y"] = joseBase64UrlEncode(yBuf) - - return jwk -} - -// MarshalJSON serializes this Public Key using the JWK JSON serialization format for -// elliptic curve keys. -func (k *ecPublicKey) MarshalJSON() (data []byte, err error) { - return json.Marshal(k.toMap()) -} - -// PEMBlock serializes this Public Key to DER-encoded PKIX format. -func (k *ecPublicKey) PEMBlock() (*pem.Block, error) { - derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey) - if err != nil { - return nil, fmt.Errorf("unable to serialize EC PublicKey to DER-encoded PKIX format: %s", err) - } - k.extended["kid"] = k.KeyID() // For display purposes. - return createPemBlock("PUBLIC KEY", derBytes, k.extended) -} - -func (k *ecPublicKey) AddExtendedField(field string, value interface{}) { - k.extended[field] = value -} - -func (k *ecPublicKey) GetExtendedField(field string) interface{} { - v, ok := k.extended[field] - if !ok { - return nil - } - return v -} - -func ecPublicKeyFromMap(jwk map[string]interface{}) (*ecPublicKey, error) { - // JWK key type (kty) has already been determined to be "EC". - // Need to extract 'crv', 'x', 'y', and 'kid' and check for - // consistency. - - // Get the curve identifier value. - crv, err := stringFromMap(jwk, "crv") - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key curve identifier: %s", err) - } - - var ( - curve elliptic.Curve - sigAlg *signatureAlgorithm - ) - - switch { - case crv == "P-256": - curve = elliptic.P256() - sigAlg = es256 - case crv == "P-384": - curve = elliptic.P384() - sigAlg = es384 - case crv == "P-521": - curve = elliptic.P521() - sigAlg = es512 - default: - return nil, fmt.Errorf("JWK EC Public Key curve identifier not supported: %q\n", crv) - } - - // Get the X and Y coordinates for the public key point. - xB64Url, err := stringFromMap(jwk, "x") - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key x-coordinate: %s", err) - } - x, err := parseECCoordinate(xB64Url, curve) - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key x-coordinate: %s", err) - } - - yB64Url, err := stringFromMap(jwk, "y") - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key y-coordinate: %s", err) - } - y, err := parseECCoordinate(yB64Url, curve) - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key y-coordinate: %s", err) - } - - key := &ecPublicKey{ - PublicKey: &ecdsa.PublicKey{Curve: curve, X: x, Y: y}, - curveName: crv, signatureAlgorithm: sigAlg, - } - - // Key ID is optional too, but if it exists, it should match the key. - _, ok := jwk["kid"] - if ok { - kid, err := stringFromMap(jwk, "kid") - if err != nil { - return nil, fmt.Errorf("JWK EC Public Key ID: %s", err) - } - if kid != key.KeyID() { - return nil, fmt.Errorf("JWK EC Public Key ID does not match: %s", kid) - } - } - - key.extended = jwk - - return key, nil -} - -/* - * EC DSA PRIVATE KEY - */ - -// ecPrivateKey implements a JWK Private Key using elliptic curve digital signature -// algorithms. -type ecPrivateKey struct { - ecPublicKey - *ecdsa.PrivateKey -} - -func fromECPrivateKey(cryptoPrivateKey *ecdsa.PrivateKey) (*ecPrivateKey, error) { - publicKey, err := fromECPublicKey(&cryptoPrivateKey.PublicKey) - if err != nil { - return nil, err - } - - return &ecPrivateKey{*publicKey, cryptoPrivateKey}, nil -} - -// PublicKey returns the Public Key data associated with this Private Key. -func (k *ecPrivateKey) PublicKey() PublicKey { - return &k.ecPublicKey -} - -func (k *ecPrivateKey) String() string { - return fmt.Sprintf("EC Private Key <%s>", k.KeyID()) -} - -// Sign signs the data read from the io.Reader using a signature algorithm supported -// by the elliptic curve private key. If the specified hashing algorithm is -// supported by this key, that hash function is used to generate the signature -// otherwise the the default hashing algorithm for this key is used. Returns -// the signature and the name of the JWK signature algorithm used, e.g., -// "ES256", "ES384", "ES512". -func (k *ecPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) { - // Generate a signature of the data using the internal alg. - // The given hashId is only a suggestion, and since EC keys only support - // on signature/hash algorithm given the curve name, we disregard it for - // the elliptic curve JWK signature implementation. - hasher := k.signatureAlgorithm.HashID().New() - _, err = io.Copy(hasher, data) - if err != nil { - return nil, "", fmt.Errorf("error reading data to sign: %s", err) - } - hash := hasher.Sum(nil) - - r, s, err := ecdsa.Sign(rand.Reader, k.PrivateKey, hash) - if err != nil { - return nil, "", fmt.Errorf("error producing signature: %s", err) - } - rBytes, sBytes := r.Bytes(), s.Bytes() - octetLength := (k.ecPublicKey.Params().BitSize + 7) >> 3 - // MUST include leading zeros in the output - rBuf := make([]byte, octetLength-len(rBytes), octetLength) - sBuf := make([]byte, octetLength-len(sBytes), octetLength) - - rBuf = append(rBuf, rBytes...) - sBuf = append(sBuf, sBytes...) - - signature = append(rBuf, sBuf...) - alg = k.signatureAlgorithm.HeaderParam() - - return -} - -// CryptoPrivateKey returns the internal object which can be used as a -// crypto.PublicKey for use with other standard library operations. The type -// is either *rsa.PublicKey or *ecdsa.PublicKey -func (k *ecPrivateKey) CryptoPrivateKey() crypto.PrivateKey { - return k.PrivateKey -} - -func (k *ecPrivateKey) toMap() map[string]interface{} { - jwk := k.ecPublicKey.toMap() - - dBytes := k.D.Bytes() - // The length of this octet string MUST be ceiling(log-base-2(n)/8) - // octets (where n is the order of the curve). This is because the private - // key d must be in the interval [1, n-1] so the bitlength of d should be - // no larger than the bitlength of n-1. The easiest way to find the octet - // length is to take bitlength(n-1), add 7 to force a carry, and shift this - // bit sequence right by 3, which is essentially dividing by 8 and adding - // 1 if there is any remainder. Thus, the private key value d should be - // output to (bitlength(n-1)+7)>>3 octets. - n := k.ecPublicKey.Params().N - octetLength := (new(big.Int).Sub(n, big.NewInt(1)).BitLen() + 7) >> 3 - // Create a buffer with the necessary zero-padding. - dBuf := make([]byte, octetLength-len(dBytes), octetLength) - dBuf = append(dBuf, dBytes...) - - jwk["d"] = joseBase64UrlEncode(dBuf) - - return jwk -} - -// MarshalJSON serializes this Private Key using the JWK JSON serialization format for -// elliptic curve keys. -func (k *ecPrivateKey) MarshalJSON() (data []byte, err error) { - return json.Marshal(k.toMap()) -} - -// PEMBlock serializes this Private Key to DER-encoded PKIX format. -func (k *ecPrivateKey) PEMBlock() (*pem.Block, error) { - derBytes, err := x509.MarshalECPrivateKey(k.PrivateKey) - if err != nil { - return nil, fmt.Errorf("unable to serialize EC PrivateKey to DER-encoded PKIX format: %s", err) - } - k.extended["keyID"] = k.KeyID() // For display purposes. - return createPemBlock("EC PRIVATE KEY", derBytes, k.extended) -} - -func ecPrivateKeyFromMap(jwk map[string]interface{}) (*ecPrivateKey, error) { - dB64Url, err := stringFromMap(jwk, "d") - if err != nil { - return nil, fmt.Errorf("JWK EC Private Key: %s", err) - } - - // JWK key type (kty) has already been determined to be "EC". - // Need to extract the public key information, then extract the private - // key value 'd'. - publicKey, err := ecPublicKeyFromMap(jwk) - if err != nil { - return nil, err - } - - d, err := parseECPrivateParam(dB64Url, publicKey.Curve) - if err != nil { - return nil, fmt.Errorf("JWK EC Private Key d-param: %s", err) - } - - key := &ecPrivateKey{ - ecPublicKey: *publicKey, - PrivateKey: &ecdsa.PrivateKey{ - PublicKey: *publicKey.PublicKey, - D: d, - }, - } - - return key, nil -} - -/* - * Key Generation Functions. - */ - -func generateECPrivateKey(curve elliptic.Curve) (k *ecPrivateKey, err error) { - k = new(ecPrivateKey) - k.PrivateKey, err = ecdsa.GenerateKey(curve, rand.Reader) - if err != nil { - return nil, err - } - - k.ecPublicKey.PublicKey = &k.PrivateKey.PublicKey - k.extended = make(map[string]interface{}) - - return -} - -// GenerateECP256PrivateKey generates a key pair using elliptic curve P-256. -func GenerateECP256PrivateKey() (PrivateKey, error) { - k, err := generateECPrivateKey(elliptic.P256()) - if err != nil { - return nil, fmt.Errorf("error generating EC P-256 key: %s", err) - } - - k.curveName = "P-256" - k.signatureAlgorithm = es256 - - return k, nil -} - -// GenerateECP384PrivateKey generates a key pair using elliptic curve P-384. -func GenerateECP384PrivateKey() (PrivateKey, error) { - k, err := generateECPrivateKey(elliptic.P384()) - if err != nil { - return nil, fmt.Errorf("error generating EC P-384 key: %s", err) - } - - k.curveName = "P-384" - k.signatureAlgorithm = es384 - - return k, nil -} - -// GenerateECP521PrivateKey generates aß key pair using elliptic curve P-521. -func GenerateECP521PrivateKey() (PrivateKey, error) { - k, err := generateECPrivateKey(elliptic.P521()) - if err != nil { - return nil, fmt.Errorf("error generating EC P-521 key: %s", err) - } - - k.curveName = "P-521" - k.signatureAlgorithm = es512 - - return k, nil -} diff --git a/vendor/github.com/docker/libtrust/filter.go b/vendor/github.com/docker/libtrust/filter.go deleted file mode 100644 index 5b2b4fca6f..0000000000 --- a/vendor/github.com/docker/libtrust/filter.go +++ /dev/null @@ -1,50 +0,0 @@ -package libtrust - -import ( - "path/filepath" -) - -// FilterByHosts filters the list of PublicKeys to only those which contain a -// 'hosts' pattern which matches the given host. If *includeEmpty* is true, -// then keys which do not specify any hosts are also returned. -func FilterByHosts(keys []PublicKey, host string, includeEmpty bool) ([]PublicKey, error) { - filtered := make([]PublicKey, 0, len(keys)) - - for _, pubKey := range keys { - var hosts []string - switch v := pubKey.GetExtendedField("hosts").(type) { - case []string: - hosts = v - case []interface{}: - for _, value := range v { - h, ok := value.(string) - if !ok { - continue - } - hosts = append(hosts, h) - } - } - - if len(hosts) == 0 { - if includeEmpty { - filtered = append(filtered, pubKey) - } - continue - } - - // Check if any hosts match pattern - for _, hostPattern := range hosts { - match, err := filepath.Match(hostPattern, host) - if err != nil { - return nil, err - } - - if match { - filtered = append(filtered, pubKey) - continue - } - } - } - - return filtered, nil -} diff --git a/vendor/github.com/docker/libtrust/hash.go b/vendor/github.com/docker/libtrust/hash.go deleted file mode 100644 index a2df787dd9..0000000000 --- a/vendor/github.com/docker/libtrust/hash.go +++ /dev/null @@ -1,56 +0,0 @@ -package libtrust - -import ( - "crypto" - _ "crypto/sha256" // Registrer SHA224 and SHA256 - _ "crypto/sha512" // Registrer SHA384 and SHA512 - "fmt" -) - -type signatureAlgorithm struct { - algHeaderParam string - hashID crypto.Hash -} - -func (h *signatureAlgorithm) HeaderParam() string { - return h.algHeaderParam -} - -func (h *signatureAlgorithm) HashID() crypto.Hash { - return h.hashID -} - -var ( - rs256 = &signatureAlgorithm{"RS256", crypto.SHA256} - rs384 = &signatureAlgorithm{"RS384", crypto.SHA384} - rs512 = &signatureAlgorithm{"RS512", crypto.SHA512} - es256 = &signatureAlgorithm{"ES256", crypto.SHA256} - es384 = &signatureAlgorithm{"ES384", crypto.SHA384} - es512 = &signatureAlgorithm{"ES512", crypto.SHA512} -) - -func rsaSignatureAlgorithmByName(alg string) (*signatureAlgorithm, error) { - switch { - case alg == "RS256": - return rs256, nil - case alg == "RS384": - return rs384, nil - case alg == "RS512": - return rs512, nil - default: - return nil, fmt.Errorf("RSA Digital Signature Algorithm %q not supported", alg) - } -} - -func rsaPKCS1v15SignatureAlgorithmForHashID(hashID crypto.Hash) *signatureAlgorithm { - switch { - case hashID == crypto.SHA512: - return rs512 - case hashID == crypto.SHA384: - return rs384 - case hashID == crypto.SHA256: - fallthrough - default: - return rs256 - } -} diff --git a/vendor/github.com/docker/libtrust/jsonsign.go b/vendor/github.com/docker/libtrust/jsonsign.go deleted file mode 100644 index cb2ca9a769..0000000000 --- a/vendor/github.com/docker/libtrust/jsonsign.go +++ /dev/null @@ -1,657 +0,0 @@ -package libtrust - -import ( - "bytes" - "crypto" - "crypto/x509" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "sort" - "time" - "unicode" -) - -var ( - // ErrInvalidSignContent is used when the content to be signed is invalid. - ErrInvalidSignContent = errors.New("invalid sign content") - - // ErrInvalidJSONContent is used when invalid json is encountered. - ErrInvalidJSONContent = errors.New("invalid json content") - - // ErrMissingSignatureKey is used when the specified signature key - // does not exist in the JSON content. - ErrMissingSignatureKey = errors.New("missing signature key") -) - -type jsHeader struct { - JWK PublicKey `json:"jwk,omitempty"` - Algorithm string `json:"alg"` - Chain []string `json:"x5c,omitempty"` -} - -type jsSignature struct { - Header jsHeader `json:"header"` - Signature string `json:"signature"` - Protected string `json:"protected,omitempty"` -} - -type jsSignaturesSorted []jsSignature - -func (jsbkid jsSignaturesSorted) Swap(i, j int) { jsbkid[i], jsbkid[j] = jsbkid[j], jsbkid[i] } -func (jsbkid jsSignaturesSorted) Len() int { return len(jsbkid) } - -func (jsbkid jsSignaturesSorted) Less(i, j int) bool { - ki, kj := jsbkid[i].Header.JWK.KeyID(), jsbkid[j].Header.JWK.KeyID() - si, sj := jsbkid[i].Signature, jsbkid[j].Signature - - if ki == kj { - return si < sj - } - - return ki < kj -} - -type signKey struct { - PrivateKey - Chain []*x509.Certificate -} - -// JSONSignature represents a signature of a json object. -type JSONSignature struct { - payload string - signatures []jsSignature - indent string - formatLength int - formatTail []byte -} - -func newJSONSignature() *JSONSignature { - return &JSONSignature{ - signatures: make([]jsSignature, 0, 1), - } -} - -// Payload returns the encoded payload of the signature. This -// payload should not be signed directly -func (js *JSONSignature) Payload() ([]byte, error) { - return joseBase64UrlDecode(js.payload) -} - -func (js *JSONSignature) protectedHeader() (string, error) { - protected := map[string]interface{}{ - "formatLength": js.formatLength, - "formatTail": joseBase64UrlEncode(js.formatTail), - "time": time.Now().UTC().Format(time.RFC3339), - } - protectedBytes, err := json.Marshal(protected) - if err != nil { - return "", err - } - - return joseBase64UrlEncode(protectedBytes), nil -} - -func (js *JSONSignature) signBytes(protectedHeader string) ([]byte, error) { - buf := make([]byte, len(js.payload)+len(protectedHeader)+1) - copy(buf, protectedHeader) - buf[len(protectedHeader)] = '.' - copy(buf[len(protectedHeader)+1:], js.payload) - return buf, nil -} - -// Sign adds a signature using the given private key. -func (js *JSONSignature) Sign(key PrivateKey) error { - protected, err := js.protectedHeader() - if err != nil { - return err - } - signBytes, err := js.signBytes(protected) - if err != nil { - return err - } - sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256) - if err != nil { - return err - } - - js.signatures = append(js.signatures, jsSignature{ - Header: jsHeader{ - JWK: key.PublicKey(), - Algorithm: algorithm, - }, - Signature: joseBase64UrlEncode(sigBytes), - Protected: protected, - }) - - return nil -} - -// SignWithChain adds a signature using the given private key -// and setting the x509 chain. The public key of the first element -// in the chain must be the public key corresponding with the sign key. -func (js *JSONSignature) SignWithChain(key PrivateKey, chain []*x509.Certificate) error { - // Ensure key.Chain[0] is public key for key - //key.Chain.PublicKey - //key.PublicKey().CryptoPublicKey() - - // Verify chain - protected, err := js.protectedHeader() - if err != nil { - return err - } - signBytes, err := js.signBytes(protected) - if err != nil { - return err - } - sigBytes, algorithm, err := key.Sign(bytes.NewReader(signBytes), crypto.SHA256) - if err != nil { - return err - } - - header := jsHeader{ - Chain: make([]string, len(chain)), - Algorithm: algorithm, - } - - for i, cert := range chain { - header.Chain[i] = base64.StdEncoding.EncodeToString(cert.Raw) - } - - js.signatures = append(js.signatures, jsSignature{ - Header: header, - Signature: joseBase64UrlEncode(sigBytes), - Protected: protected, - }) - - return nil -} - -// Verify verifies all the signatures and returns the list of -// public keys used to sign. Any x509 chains are not checked. -func (js *JSONSignature) Verify() ([]PublicKey, error) { - keys := make([]PublicKey, len(js.signatures)) - for i, signature := range js.signatures { - signBytes, err := js.signBytes(signature.Protected) - if err != nil { - return nil, err - } - var publicKey PublicKey - if len(signature.Header.Chain) > 0 { - certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0]) - if err != nil { - return nil, err - } - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, err - } - publicKey, err = FromCryptoPublicKey(cert.PublicKey) - if err != nil { - return nil, err - } - } else if signature.Header.JWK != nil { - publicKey = signature.Header.JWK - } else { - return nil, errors.New("missing public key") - } - - sigBytes, err := joseBase64UrlDecode(signature.Signature) - if err != nil { - return nil, err - } - - err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes) - if err != nil { - return nil, err - } - - keys[i] = publicKey - } - return keys, nil -} - -// VerifyChains verifies all the signatures and the chains associated -// with each signature and returns the list of verified chains. -// Signatures without an x509 chain are not checked. -func (js *JSONSignature) VerifyChains(ca *x509.CertPool) ([][]*x509.Certificate, error) { - chains := make([][]*x509.Certificate, 0, len(js.signatures)) - for _, signature := range js.signatures { - signBytes, err := js.signBytes(signature.Protected) - if err != nil { - return nil, err - } - var publicKey PublicKey - if len(signature.Header.Chain) > 0 { - certBytes, err := base64.StdEncoding.DecodeString(signature.Header.Chain[0]) - if err != nil { - return nil, err - } - cert, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, err - } - publicKey, err = FromCryptoPublicKey(cert.PublicKey) - if err != nil { - return nil, err - } - intermediates := x509.NewCertPool() - if len(signature.Header.Chain) > 1 { - intermediateChain := signature.Header.Chain[1:] - for i := range intermediateChain { - certBytes, err := base64.StdEncoding.DecodeString(intermediateChain[i]) - if err != nil { - return nil, err - } - intermediate, err := x509.ParseCertificate(certBytes) - if err != nil { - return nil, err - } - intermediates.AddCert(intermediate) - } - } - - verifyOptions := x509.VerifyOptions{ - Intermediates: intermediates, - Roots: ca, - } - - verifiedChains, err := cert.Verify(verifyOptions) - if err != nil { - return nil, err - } - chains = append(chains, verifiedChains...) - - sigBytes, err := joseBase64UrlDecode(signature.Signature) - if err != nil { - return nil, err - } - - err = publicKey.Verify(bytes.NewReader(signBytes), signature.Header.Algorithm, sigBytes) - if err != nil { - return nil, err - } - } - - } - return chains, nil -} - -// JWS returns JSON serialized JWS according to -// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-7.2 -func (js *JSONSignature) JWS() ([]byte, error) { - if len(js.signatures) == 0 { - return nil, errors.New("missing signature") - } - - sort.Sort(jsSignaturesSorted(js.signatures)) - - jsonMap := map[string]interface{}{ - "payload": js.payload, - "signatures": js.signatures, - } - - return json.MarshalIndent(jsonMap, "", " ") -} - -func notSpace(r rune) bool { - return !unicode.IsSpace(r) -} - -func detectJSONIndent(jsonContent []byte) (indent string) { - if len(jsonContent) > 2 && jsonContent[0] == '{' && jsonContent[1] == '\n' { - quoteIndex := bytes.IndexRune(jsonContent[1:], '"') - if quoteIndex > 0 { - indent = string(jsonContent[2 : quoteIndex+1]) - } - } - return -} - -type jsParsedHeader struct { - JWK json.RawMessage `json:"jwk"` - Algorithm string `json:"alg"` - Chain []string `json:"x5c"` -} - -type jsParsedSignature struct { - Header jsParsedHeader `json:"header"` - Signature string `json:"signature"` - Protected string `json:"protected"` -} - -// ParseJWS parses a JWS serialized JSON object into a Json Signature. -func ParseJWS(content []byte) (*JSONSignature, error) { - type jsParsed struct { - Payload string `json:"payload"` - Signatures []jsParsedSignature `json:"signatures"` - } - parsed := &jsParsed{} - err := json.Unmarshal(content, parsed) - if err != nil { - return nil, err - } - if len(parsed.Signatures) == 0 { - return nil, errors.New("missing signatures") - } - payload, err := joseBase64UrlDecode(parsed.Payload) - if err != nil { - return nil, err - } - - js, err := NewJSONSignature(payload) - if err != nil { - return nil, err - } - js.signatures = make([]jsSignature, len(parsed.Signatures)) - for i, signature := range parsed.Signatures { - header := jsHeader{ - Algorithm: signature.Header.Algorithm, - } - if signature.Header.Chain != nil { - header.Chain = signature.Header.Chain - } - if signature.Header.JWK != nil { - publicKey, err := UnmarshalPublicKeyJWK([]byte(signature.Header.JWK)) - if err != nil { - return nil, err - } - header.JWK = publicKey - } - js.signatures[i] = jsSignature{ - Header: header, - Signature: signature.Signature, - Protected: signature.Protected, - } - } - - return js, nil -} - -// NewJSONSignature returns a new unsigned JWS from a json byte array. -// JSONSignature will need to be signed before serializing or storing. -// Optionally, one or more signatures can be provided as byte buffers, -// containing serialized JWS signatures, to assemble a fully signed JWS -// package. It is the callers responsibility to ensure uniqueness of the -// provided signatures. -func NewJSONSignature(content []byte, signatures ...[]byte) (*JSONSignature, error) { - var dataMap map[string]interface{} - err := json.Unmarshal(content, &dataMap) - if err != nil { - return nil, err - } - - js := newJSONSignature() - js.indent = detectJSONIndent(content) - - js.payload = joseBase64UrlEncode(content) - - // Find trailing } and whitespace, put in protected header - closeIndex := bytes.LastIndexFunc(content, notSpace) - if content[closeIndex] != '}' { - return nil, ErrInvalidJSONContent - } - lastRuneIndex := bytes.LastIndexFunc(content[:closeIndex], notSpace) - if content[lastRuneIndex] == ',' { - return nil, ErrInvalidJSONContent - } - js.formatLength = lastRuneIndex + 1 - js.formatTail = content[js.formatLength:] - - if len(signatures) > 0 { - for _, signature := range signatures { - var parsedJSig jsParsedSignature - - if err := json.Unmarshal(signature, &parsedJSig); err != nil { - return nil, err - } - - // TODO(stevvooe): A lot of the code below is repeated in - // ParseJWS. It will require more refactoring to fix that. - jsig := jsSignature{ - Header: jsHeader{ - Algorithm: parsedJSig.Header.Algorithm, - }, - Signature: parsedJSig.Signature, - Protected: parsedJSig.Protected, - } - - if parsedJSig.Header.Chain != nil { - jsig.Header.Chain = parsedJSig.Header.Chain - } - - if parsedJSig.Header.JWK != nil { - publicKey, err := UnmarshalPublicKeyJWK([]byte(parsedJSig.Header.JWK)) - if err != nil { - return nil, err - } - jsig.Header.JWK = publicKey - } - - js.signatures = append(js.signatures, jsig) - } - } - - return js, nil -} - -// NewJSONSignatureFromMap returns a new unsigned JSONSignature from a map or -// struct. JWS will need to be signed before serializing or storing. -func NewJSONSignatureFromMap(content interface{}) (*JSONSignature, error) { - switch content.(type) { - case map[string]interface{}: - case struct{}: - default: - return nil, errors.New("invalid data type") - } - - js := newJSONSignature() - js.indent = " " - - payload, err := json.MarshalIndent(content, "", js.indent) - if err != nil { - return nil, err - } - js.payload = joseBase64UrlEncode(payload) - - // Remove '\n}' from formatted section, put in protected header - js.formatLength = len(payload) - 2 - js.formatTail = payload[js.formatLength:] - - return js, nil -} - -func readIntFromMap(key string, m map[string]interface{}) (int, bool) { - value, ok := m[key] - if !ok { - return 0, false - } - switch v := value.(type) { - case int: - return v, true - case float64: - return int(v), true - default: - return 0, false - } -} - -func readStringFromMap(key string, m map[string]interface{}) (v string, ok bool) { - value, ok := m[key] - if !ok { - return "", false - } - v, ok = value.(string) - return -} - -// ParsePrettySignature parses a formatted signature into a -// JSON signature. If the signatures are missing the format information -// an error is thrown. The formatted signature must be created by -// the same method as format signature. -func ParsePrettySignature(content []byte, signatureKey string) (*JSONSignature, error) { - var contentMap map[string]json.RawMessage - err := json.Unmarshal(content, &contentMap) - if err != nil { - return nil, fmt.Errorf("error unmarshalling content: %s", err) - } - sigMessage, ok := contentMap[signatureKey] - if !ok { - return nil, ErrMissingSignatureKey - } - - var signatureBlocks []jsParsedSignature - err = json.Unmarshal([]byte(sigMessage), &signatureBlocks) - if err != nil { - return nil, fmt.Errorf("error unmarshalling signatures: %s", err) - } - - js := newJSONSignature() - js.signatures = make([]jsSignature, len(signatureBlocks)) - - for i, signatureBlock := range signatureBlocks { - protectedBytes, err := joseBase64UrlDecode(signatureBlock.Protected) - if err != nil { - return nil, fmt.Errorf("base64 decode error: %s", err) - } - var protectedHeader map[string]interface{} - err = json.Unmarshal(protectedBytes, &protectedHeader) - if err != nil { - return nil, fmt.Errorf("error unmarshalling protected header: %s", err) - } - - formatLength, ok := readIntFromMap("formatLength", protectedHeader) - if !ok { - return nil, errors.New("missing formatted length") - } - encodedTail, ok := readStringFromMap("formatTail", protectedHeader) - if !ok { - return nil, errors.New("missing formatted tail") - } - formatTail, err := joseBase64UrlDecode(encodedTail) - if err != nil { - return nil, fmt.Errorf("base64 decode error on tail: %s", err) - } - if js.formatLength == 0 { - js.formatLength = formatLength - } else if js.formatLength != formatLength { - return nil, errors.New("conflicting format length") - } - if len(js.formatTail) == 0 { - js.formatTail = formatTail - } else if bytes.Compare(js.formatTail, formatTail) != 0 { - return nil, errors.New("conflicting format tail") - } - - header := jsHeader{ - Algorithm: signatureBlock.Header.Algorithm, - Chain: signatureBlock.Header.Chain, - } - if signatureBlock.Header.JWK != nil { - publicKey, err := UnmarshalPublicKeyJWK([]byte(signatureBlock.Header.JWK)) - if err != nil { - return nil, fmt.Errorf("error unmarshalling public key: %s", err) - } - header.JWK = publicKey - } - js.signatures[i] = jsSignature{ - Header: header, - Signature: signatureBlock.Signature, - Protected: signatureBlock.Protected, - } - } - if js.formatLength > len(content) { - return nil, errors.New("invalid format length") - } - formatted := make([]byte, js.formatLength+len(js.formatTail)) - copy(formatted, content[:js.formatLength]) - copy(formatted[js.formatLength:], js.formatTail) - js.indent = detectJSONIndent(formatted) - js.payload = joseBase64UrlEncode(formatted) - - return js, nil -} - -// PrettySignature formats a json signature into an easy to read -// single json serialized object. -func (js *JSONSignature) PrettySignature(signatureKey string) ([]byte, error) { - if len(js.signatures) == 0 { - return nil, errors.New("no signatures") - } - payload, err := joseBase64UrlDecode(js.payload) - if err != nil { - return nil, err - } - payload = payload[:js.formatLength] - - sort.Sort(jsSignaturesSorted(js.signatures)) - - var marshalled []byte - var marshallErr error - if js.indent != "" { - marshalled, marshallErr = json.MarshalIndent(js.signatures, js.indent, js.indent) - } else { - marshalled, marshallErr = json.Marshal(js.signatures) - } - if marshallErr != nil { - return nil, marshallErr - } - - buf := bytes.NewBuffer(make([]byte, 0, len(payload)+len(marshalled)+34)) - buf.Write(payload) - buf.WriteByte(',') - if js.indent != "" { - buf.WriteByte('\n') - buf.WriteString(js.indent) - buf.WriteByte('"') - buf.WriteString(signatureKey) - buf.WriteString("\": ") - buf.Write(marshalled) - buf.WriteByte('\n') - } else { - buf.WriteByte('"') - buf.WriteString(signatureKey) - buf.WriteString("\":") - buf.Write(marshalled) - } - buf.WriteByte('}') - - return buf.Bytes(), nil -} - -// Signatures provides the signatures on this JWS as opaque blobs, sorted by -// keyID. These blobs can be stored and reassembled with payloads. Internally, -// they are simply marshaled json web signatures but implementations should -// not rely on this. -func (js *JSONSignature) Signatures() ([][]byte, error) { - sort.Sort(jsSignaturesSorted(js.signatures)) - - var sb [][]byte - for _, jsig := range js.signatures { - p, err := json.Marshal(jsig) - if err != nil { - return nil, err - } - - sb = append(sb, p) - } - - return sb, nil -} - -// Merge combines the signatures from one or more other signatures into the -// method receiver. If the payloads differ for any argument, an error will be -// returned and the receiver will not be modified. -func (js *JSONSignature) Merge(others ...*JSONSignature) error { - merged := js.signatures - for _, other := range others { - if js.payload != other.payload { - return fmt.Errorf("payloads differ from merge target") - } - merged = append(merged, other.signatures...) - } - - js.signatures = merged - return nil -} diff --git a/vendor/github.com/docker/libtrust/key.go b/vendor/github.com/docker/libtrust/key.go deleted file mode 100644 index 73642db2a8..0000000000 --- a/vendor/github.com/docker/libtrust/key.go +++ /dev/null @@ -1,253 +0,0 @@ -package libtrust - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "io" -) - -// PublicKey is a generic interface for a Public Key. -type PublicKey interface { - // KeyType returns the key type for this key. For elliptic curve keys, - // this value should be "EC". For RSA keys, this value should be "RSA". - KeyType() string - // KeyID returns a distinct identifier which is unique to this Public Key. - // The format generated by this library is a base32 encoding of a 240 bit - // hash of the public key data divided into 12 groups like so: - // ABCD:EFGH:IJKL:MNOP:QRST:UVWX:YZ23:4567:ABCD:EFGH:IJKL:MNOP - KeyID() string - // Verify verifyies the signature of the data in the io.Reader using this - // Public Key. The alg parameter should identify the digital signature - // algorithm which was used to produce the signature and should be - // supported by this public key. Returns a nil error if the signature - // is valid. - Verify(data io.Reader, alg string, signature []byte) error - // CryptoPublicKey returns the internal object which can be used as a - // crypto.PublicKey for use with other standard library operations. The type - // is either *rsa.PublicKey or *ecdsa.PublicKey - CryptoPublicKey() crypto.PublicKey - // These public keys can be serialized to the standard JSON encoding for - // JSON Web Keys. See section 6 of the IETF draft RFC for JOSE JSON Web - // Algorithms. - MarshalJSON() ([]byte, error) - // These keys can also be serialized to the standard PEM encoding. - PEMBlock() (*pem.Block, error) - // The string representation of a key is its key type and ID. - String() string - AddExtendedField(string, interface{}) - GetExtendedField(string) interface{} -} - -// PrivateKey is a generic interface for a Private Key. -type PrivateKey interface { - // A PrivateKey contains all fields and methods of a PublicKey of the - // same type. The MarshalJSON method also outputs the private key as a - // JSON Web Key, and the PEMBlock method outputs the private key as a - // PEM block. - PublicKey - // PublicKey returns the PublicKey associated with this PrivateKey. - PublicKey() PublicKey - // Sign signs the data read from the io.Reader using a signature algorithm - // supported by the private key. If the specified hashing algorithm is - // supported by this key, that hash function is used to generate the - // signature otherwise the the default hashing algorithm for this key is - // used. Returns the signature and identifier of the algorithm used. - Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) - // CryptoPrivateKey returns the internal object which can be used as a - // crypto.PublicKey for use with other standard library operations. The - // type is either *rsa.PublicKey or *ecdsa.PublicKey - CryptoPrivateKey() crypto.PrivateKey -} - -// FromCryptoPublicKey returns a libtrust PublicKey representation of the given -// *ecdsa.PublicKey or *rsa.PublicKey. Returns a non-nil error when the given -// key is of an unsupported type. -func FromCryptoPublicKey(cryptoPublicKey crypto.PublicKey) (PublicKey, error) { - switch cryptoPublicKey := cryptoPublicKey.(type) { - case *ecdsa.PublicKey: - return fromECPublicKey(cryptoPublicKey) - case *rsa.PublicKey: - return fromRSAPublicKey(cryptoPublicKey), nil - default: - return nil, fmt.Errorf("public key type %T is not supported", cryptoPublicKey) - } -} - -// FromCryptoPrivateKey returns a libtrust PrivateKey representation of the given -// *ecdsa.PrivateKey or *rsa.PrivateKey. Returns a non-nil error when the given -// key is of an unsupported type. -func FromCryptoPrivateKey(cryptoPrivateKey crypto.PrivateKey) (PrivateKey, error) { - switch cryptoPrivateKey := cryptoPrivateKey.(type) { - case *ecdsa.PrivateKey: - return fromECPrivateKey(cryptoPrivateKey) - case *rsa.PrivateKey: - return fromRSAPrivateKey(cryptoPrivateKey), nil - default: - return nil, fmt.Errorf("private key type %T is not supported", cryptoPrivateKey) - } -} - -// UnmarshalPublicKeyPEM parses the PEM encoded data and returns a libtrust -// PublicKey or an error if there is a problem with the encoding. -func UnmarshalPublicKeyPEM(data []byte) (PublicKey, error) { - pemBlock, _ := pem.Decode(data) - if pemBlock == nil { - return nil, errors.New("unable to find PEM encoded data") - } else if pemBlock.Type != "PUBLIC KEY" { - return nil, fmt.Errorf("unable to get PublicKey from PEM type: %s", pemBlock.Type) - } - - return pubKeyFromPEMBlock(pemBlock) -} - -// UnmarshalPublicKeyPEMBundle parses the PEM encoded data as a bundle of -// PEM blocks appended one after the other and returns a slice of PublicKey -// objects that it finds. -func UnmarshalPublicKeyPEMBundle(data []byte) ([]PublicKey, error) { - pubKeys := []PublicKey{} - - for { - var pemBlock *pem.Block - pemBlock, data = pem.Decode(data) - if pemBlock == nil { - break - } else if pemBlock.Type != "PUBLIC KEY" { - return nil, fmt.Errorf("unable to get PublicKey from PEM type: %s", pemBlock.Type) - } - - pubKey, err := pubKeyFromPEMBlock(pemBlock) - if err != nil { - return nil, err - } - - pubKeys = append(pubKeys, pubKey) - } - - return pubKeys, nil -} - -// UnmarshalPrivateKeyPEM parses the PEM encoded data and returns a libtrust -// PrivateKey or an error if there is a problem with the encoding. -func UnmarshalPrivateKeyPEM(data []byte) (PrivateKey, error) { - pemBlock, _ := pem.Decode(data) - if pemBlock == nil { - return nil, errors.New("unable to find PEM encoded data") - } - - var key PrivateKey - - switch { - case pemBlock.Type == "RSA PRIVATE KEY": - rsaPrivateKey, err := x509.ParsePKCS1PrivateKey(pemBlock.Bytes) - if err != nil { - return nil, fmt.Errorf("unable to decode RSA Private Key PEM data: %s", err) - } - key = fromRSAPrivateKey(rsaPrivateKey) - case pemBlock.Type == "EC PRIVATE KEY": - ecPrivateKey, err := x509.ParseECPrivateKey(pemBlock.Bytes) - if err != nil { - return nil, fmt.Errorf("unable to decode EC Private Key PEM data: %s", err) - } - key, err = fromECPrivateKey(ecPrivateKey) - if err != nil { - return nil, err - } - default: - return nil, fmt.Errorf("unable to get PrivateKey from PEM type: %s", pemBlock.Type) - } - - addPEMHeadersToKey(pemBlock, key.PublicKey()) - - return key, nil -} - -// UnmarshalPublicKeyJWK unmarshals the given JSON Web Key into a generic -// Public Key to be used with libtrust. -func UnmarshalPublicKeyJWK(data []byte) (PublicKey, error) { - jwk := make(map[string]interface{}) - - err := json.Unmarshal(data, &jwk) - if err != nil { - return nil, fmt.Errorf( - "decoding JWK Public Key JSON data: %s\n", err, - ) - } - - // Get the Key Type value. - kty, err := stringFromMap(jwk, "kty") - if err != nil { - return nil, fmt.Errorf("JWK Public Key type: %s", err) - } - - switch { - case kty == "EC": - // Call out to unmarshal EC public key. - return ecPublicKeyFromMap(jwk) - case kty == "RSA": - // Call out to unmarshal RSA public key. - return rsaPublicKeyFromMap(jwk) - default: - return nil, fmt.Errorf( - "JWK Public Key type not supported: %q\n", kty, - ) - } -} - -// UnmarshalPublicKeyJWKSet parses the JSON encoded data as a JSON Web Key Set -// and returns a slice of Public Key objects. -func UnmarshalPublicKeyJWKSet(data []byte) ([]PublicKey, error) { - rawKeys, err := loadJSONKeySetRaw(data) - if err != nil { - return nil, err - } - - pubKeys := make([]PublicKey, 0, len(rawKeys)) - - for _, rawKey := range rawKeys { - pubKey, err := UnmarshalPublicKeyJWK(rawKey) - if err != nil { - return nil, err - } - pubKeys = append(pubKeys, pubKey) - } - - return pubKeys, nil -} - -// UnmarshalPrivateKeyJWK unmarshals the given JSON Web Key into a generic -// Private Key to be used with libtrust. -func UnmarshalPrivateKeyJWK(data []byte) (PrivateKey, error) { - jwk := make(map[string]interface{}) - - err := json.Unmarshal(data, &jwk) - if err != nil { - return nil, fmt.Errorf( - "decoding JWK Private Key JSON data: %s\n", err, - ) - } - - // Get the Key Type value. - kty, err := stringFromMap(jwk, "kty") - if err != nil { - return nil, fmt.Errorf("JWK Private Key type: %s", err) - } - - switch { - case kty == "EC": - // Call out to unmarshal EC private key. - return ecPrivateKeyFromMap(jwk) - case kty == "RSA": - // Call out to unmarshal RSA private key. - return rsaPrivateKeyFromMap(jwk) - default: - return nil, fmt.Errorf( - "JWK Private Key type not supported: %q\n", kty, - ) - } -} diff --git a/vendor/github.com/docker/libtrust/key_files.go b/vendor/github.com/docker/libtrust/key_files.go deleted file mode 100644 index c526de5455..0000000000 --- a/vendor/github.com/docker/libtrust/key_files.go +++ /dev/null @@ -1,255 +0,0 @@ -package libtrust - -import ( - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "io/ioutil" - "os" - "strings" -) - -var ( - // ErrKeyFileDoesNotExist indicates that the private key file does not exist. - ErrKeyFileDoesNotExist = errors.New("key file does not exist") -) - -func readKeyFileBytes(filename string) ([]byte, error) { - data, err := ioutil.ReadFile(filename) - if err != nil { - if os.IsNotExist(err) { - err = ErrKeyFileDoesNotExist - } else { - err = fmt.Errorf("unable to read key file %s: %s", filename, err) - } - - return nil, err - } - - return data, nil -} - -/* - Loading and Saving of Public and Private Keys in either PEM or JWK format. -*/ - -// LoadKeyFile opens the given filename and attempts to read a Private Key -// encoded in either PEM or JWK format (if .json or .jwk file extension). -func LoadKeyFile(filename string) (PrivateKey, error) { - contents, err := readKeyFileBytes(filename) - if err != nil { - return nil, err - } - - var key PrivateKey - - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - key, err = UnmarshalPrivateKeyJWK(contents) - if err != nil { - return nil, fmt.Errorf("unable to decode private key JWK: %s", err) - } - } else { - key, err = UnmarshalPrivateKeyPEM(contents) - if err != nil { - return nil, fmt.Errorf("unable to decode private key PEM: %s", err) - } - } - - return key, nil -} - -// LoadPublicKeyFile opens the given filename and attempts to read a Public Key -// encoded in either PEM or JWK format (if .json or .jwk file extension). -func LoadPublicKeyFile(filename string) (PublicKey, error) { - contents, err := readKeyFileBytes(filename) - if err != nil { - return nil, err - } - - var key PublicKey - - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - key, err = UnmarshalPublicKeyJWK(contents) - if err != nil { - return nil, fmt.Errorf("unable to decode public key JWK: %s", err) - } - } else { - key, err = UnmarshalPublicKeyPEM(contents) - if err != nil { - return nil, fmt.Errorf("unable to decode public key PEM: %s", err) - } - } - - return key, nil -} - -// SaveKey saves the given key to a file using the provided filename. -// This process will overwrite any existing file at the provided location. -func SaveKey(filename string, key PrivateKey) error { - var encodedKey []byte - var err error - - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - // Encode in JSON Web Key format. - encodedKey, err = json.MarshalIndent(key, "", " ") - if err != nil { - return fmt.Errorf("unable to encode private key JWK: %s", err) - } - } else { - // Encode in PEM format. - pemBlock, err := key.PEMBlock() - if err != nil { - return fmt.Errorf("unable to encode private key PEM: %s", err) - } - encodedKey = pem.EncodeToMemory(pemBlock) - } - - err = ioutil.WriteFile(filename, encodedKey, os.FileMode(0600)) - if err != nil { - return fmt.Errorf("unable to write private key file %s: %s", filename, err) - } - - return nil -} - -// SavePublicKey saves the given public key to the file. -func SavePublicKey(filename string, key PublicKey) error { - var encodedKey []byte - var err error - - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - // Encode in JSON Web Key format. - encodedKey, err = json.MarshalIndent(key, "", " ") - if err != nil { - return fmt.Errorf("unable to encode public key JWK: %s", err) - } - } else { - // Encode in PEM format. - pemBlock, err := key.PEMBlock() - if err != nil { - return fmt.Errorf("unable to encode public key PEM: %s", err) - } - encodedKey = pem.EncodeToMemory(pemBlock) - } - - err = ioutil.WriteFile(filename, encodedKey, os.FileMode(0644)) - if err != nil { - return fmt.Errorf("unable to write public key file %s: %s", filename, err) - } - - return nil -} - -// Public Key Set files - -type jwkSet struct { - Keys []json.RawMessage `json:"keys"` -} - -// LoadKeySetFile loads a key set -func LoadKeySetFile(filename string) ([]PublicKey, error) { - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - return loadJSONKeySetFile(filename) - } - - // Must be a PEM format file - return loadPEMKeySetFile(filename) -} - -func loadJSONKeySetRaw(data []byte) ([]json.RawMessage, error) { - if len(data) == 0 { - // This is okay, just return an empty slice. - return []json.RawMessage{}, nil - } - - keySet := jwkSet{} - - err := json.Unmarshal(data, &keySet) - if err != nil { - return nil, fmt.Errorf("unable to decode JSON Web Key Set: %s", err) - } - - return keySet.Keys, nil -} - -func loadJSONKeySetFile(filename string) ([]PublicKey, error) { - contents, err := readKeyFileBytes(filename) - if err != nil && err != ErrKeyFileDoesNotExist { - return nil, err - } - - return UnmarshalPublicKeyJWKSet(contents) -} - -func loadPEMKeySetFile(filename string) ([]PublicKey, error) { - data, err := readKeyFileBytes(filename) - if err != nil && err != ErrKeyFileDoesNotExist { - return nil, err - } - - return UnmarshalPublicKeyPEMBundle(data) -} - -// AddKeySetFile adds a key to a key set -func AddKeySetFile(filename string, key PublicKey) error { - if strings.HasSuffix(filename, ".json") || strings.HasSuffix(filename, ".jwk") { - return addKeySetJSONFile(filename, key) - } - - // Must be a PEM format file - return addKeySetPEMFile(filename, key) -} - -func addKeySetJSONFile(filename string, key PublicKey) error { - encodedKey, err := json.Marshal(key) - if err != nil { - return fmt.Errorf("unable to encode trusted client key: %s", err) - } - - contents, err := readKeyFileBytes(filename) - if err != nil && err != ErrKeyFileDoesNotExist { - return err - } - - rawEntries, err := loadJSONKeySetRaw(contents) - if err != nil { - return err - } - - rawEntries = append(rawEntries, json.RawMessage(encodedKey)) - entriesWrapper := jwkSet{Keys: rawEntries} - - encodedEntries, err := json.MarshalIndent(entriesWrapper, "", " ") - if err != nil { - return fmt.Errorf("unable to encode trusted client keys: %s", err) - } - - err = ioutil.WriteFile(filename, encodedEntries, os.FileMode(0644)) - if err != nil { - return fmt.Errorf("unable to write trusted client keys file %s: %s", filename, err) - } - - return nil -} - -func addKeySetPEMFile(filename string, key PublicKey) error { - // Encode to PEM, open file for appending, write PEM. - file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.FileMode(0644)) - if err != nil { - return fmt.Errorf("unable to open trusted client keys file %s: %s", filename, err) - } - defer file.Close() - - pemBlock, err := key.PEMBlock() - if err != nil { - return fmt.Errorf("unable to encoded trusted key: %s", err) - } - - _, err = file.Write(pem.EncodeToMemory(pemBlock)) - if err != nil { - return fmt.Errorf("unable to write trusted keys file: %s", err) - } - - return nil -} diff --git a/vendor/github.com/docker/libtrust/key_manager.go b/vendor/github.com/docker/libtrust/key_manager.go deleted file mode 100644 index 9a98ae3574..0000000000 --- a/vendor/github.com/docker/libtrust/key_manager.go +++ /dev/null @@ -1,175 +0,0 @@ -package libtrust - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net" - "os" - "path" - "sync" -) - -// ClientKeyManager manages client keys on the filesystem -type ClientKeyManager struct { - key PrivateKey - clientFile string - clientDir string - - clientLock sync.RWMutex - clients []PublicKey - - configLock sync.Mutex - configs []*tls.Config -} - -// NewClientKeyManager loads a new manager from a set of key files -// and managed by the given private key. -func NewClientKeyManager(trustKey PrivateKey, clientFile, clientDir string) (*ClientKeyManager, error) { - m := &ClientKeyManager{ - key: trustKey, - clientFile: clientFile, - clientDir: clientDir, - } - if err := m.loadKeys(); err != nil { - return nil, err - } - // TODO Start watching file and directory - - return m, nil -} - -func (c *ClientKeyManager) loadKeys() (err error) { - // Load authorized keys file - var clients []PublicKey - if c.clientFile != "" { - clients, err = LoadKeySetFile(c.clientFile) - if err != nil { - return fmt.Errorf("unable to load authorized keys: %s", err) - } - } - - // Add clients from authorized keys directory - files, err := ioutil.ReadDir(c.clientDir) - if err != nil && !os.IsNotExist(err) { - return fmt.Errorf("unable to open authorized keys directory: %s", err) - } - for _, f := range files { - if !f.IsDir() { - publicKey, err := LoadPublicKeyFile(path.Join(c.clientDir, f.Name())) - if err != nil { - return fmt.Errorf("unable to load authorized key file: %s", err) - } - clients = append(clients, publicKey) - } - } - - c.clientLock.Lock() - c.clients = clients - c.clientLock.Unlock() - - return nil -} - -// RegisterTLSConfig registers a tls configuration to manager -// such that any changes to the keys may be reflected in -// the tls client CA pool -func (c *ClientKeyManager) RegisterTLSConfig(tlsConfig *tls.Config) error { - c.clientLock.RLock() - certPool, err := GenerateCACertPool(c.key, c.clients) - if err != nil { - return fmt.Errorf("CA pool generation error: %s", err) - } - c.clientLock.RUnlock() - - tlsConfig.ClientCAs = certPool - - c.configLock.Lock() - c.configs = append(c.configs, tlsConfig) - c.configLock.Unlock() - - return nil -} - -// NewIdentityAuthTLSConfig creates a tls.Config for the server to use for -// libtrust identity authentication for the domain specified -func NewIdentityAuthTLSConfig(trustKey PrivateKey, clients *ClientKeyManager, addr string, domain string) (*tls.Config, error) { - tlsConfig := newTLSConfig() - - tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert - if err := clients.RegisterTLSConfig(tlsConfig); err != nil { - return nil, err - } - - // Generate cert - ips, domains, err := parseAddr(addr) - if err != nil { - return nil, err - } - // add domain that it expects clients to use - domains = append(domains, domain) - x509Cert, err := GenerateSelfSignedServerCert(trustKey, domains, ips) - if err != nil { - return nil, fmt.Errorf("certificate generation error: %s", err) - } - tlsConfig.Certificates = []tls.Certificate{{ - Certificate: [][]byte{x509Cert.Raw}, - PrivateKey: trustKey.CryptoPrivateKey(), - Leaf: x509Cert, - }} - - return tlsConfig, nil -} - -// NewCertAuthTLSConfig creates a tls.Config for the server to use for -// certificate authentication -func NewCertAuthTLSConfig(caPath, certPath, keyPath string) (*tls.Config, error) { - tlsConfig := newTLSConfig() - - cert, err := tls.LoadX509KeyPair(certPath, keyPath) - if err != nil { - return nil, fmt.Errorf("Couldn't load X509 key pair (%s, %s): %s. Key encrypted?", certPath, keyPath, err) - } - tlsConfig.Certificates = []tls.Certificate{cert} - - // Verify client certificates against a CA? - if caPath != "" { - certPool := x509.NewCertPool() - file, err := ioutil.ReadFile(caPath) - if err != nil { - return nil, fmt.Errorf("Couldn't read CA certificate: %s", err) - } - certPool.AppendCertsFromPEM(file) - - tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert - tlsConfig.ClientCAs = certPool - } - - return tlsConfig, nil -} - -func newTLSConfig() *tls.Config { - return &tls.Config{ - NextProtos: []string{"http/1.1"}, - // Avoid fallback on insecure SSL protocols - MinVersion: tls.VersionTLS10, - } -} - -// parseAddr parses an address into an array of IPs and domains -func parseAddr(addr string) ([]net.IP, []string, error) { - host, _, err := net.SplitHostPort(addr) - if err != nil { - return nil, nil, err - } - var domains []string - var ips []net.IP - ip := net.ParseIP(host) - if ip != nil { - ips = []net.IP{ip} - } else { - domains = []string{host} - } - return ips, domains, nil -} diff --git a/vendor/github.com/docker/libtrust/rsa_key.go b/vendor/github.com/docker/libtrust/rsa_key.go deleted file mode 100644 index dac4cacf20..0000000000 --- a/vendor/github.com/docker/libtrust/rsa_key.go +++ /dev/null @@ -1,427 +0,0 @@ -package libtrust - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "io" - "math/big" -) - -/* - * RSA DSA PUBLIC KEY - */ - -// rsaPublicKey implements a JWK Public Key using RSA digital signature algorithms. -type rsaPublicKey struct { - *rsa.PublicKey - extended map[string]interface{} -} - -func fromRSAPublicKey(cryptoPublicKey *rsa.PublicKey) *rsaPublicKey { - return &rsaPublicKey{cryptoPublicKey, map[string]interface{}{}} -} - -// KeyType returns the JWK key type for RSA keys, i.e., "RSA". -func (k *rsaPublicKey) KeyType() string { - return "RSA" -} - -// KeyID returns a distinct identifier which is unique to this Public Key. -func (k *rsaPublicKey) KeyID() string { - return keyIDFromCryptoKey(k) -} - -func (k *rsaPublicKey) String() string { - return fmt.Sprintf("RSA Public Key <%s>", k.KeyID()) -} - -// Verify verifyies the signature of the data in the io.Reader using this Public Key. -// The alg parameter should be the name of the JWA digital signature algorithm -// which was used to produce the signature and should be supported by this -// public key. Returns a nil error if the signature is valid. -func (k *rsaPublicKey) Verify(data io.Reader, alg string, signature []byte) error { - // Verify the signature of the given date, return non-nil error if valid. - sigAlg, err := rsaSignatureAlgorithmByName(alg) - if err != nil { - return fmt.Errorf("unable to verify Signature: %s", err) - } - - hasher := sigAlg.HashID().New() - _, err = io.Copy(hasher, data) - if err != nil { - return fmt.Errorf("error reading data to sign: %s", err) - } - hash := hasher.Sum(nil) - - err = rsa.VerifyPKCS1v15(k.PublicKey, sigAlg.HashID(), hash, signature) - if err != nil { - return fmt.Errorf("invalid %s signature: %s", sigAlg.HeaderParam(), err) - } - - return nil -} - -// CryptoPublicKey returns the internal object which can be used as a -// crypto.PublicKey for use with other standard library operations. The type -// is either *rsa.PublicKey or *ecdsa.PublicKey -func (k *rsaPublicKey) CryptoPublicKey() crypto.PublicKey { - return k.PublicKey -} - -func (k *rsaPublicKey) toMap() map[string]interface{} { - jwk := make(map[string]interface{}) - for k, v := range k.extended { - jwk[k] = v - } - jwk["kty"] = k.KeyType() - jwk["kid"] = k.KeyID() - jwk["n"] = joseBase64UrlEncode(k.N.Bytes()) - jwk["e"] = joseBase64UrlEncode(serializeRSAPublicExponentParam(k.E)) - - return jwk -} - -// MarshalJSON serializes this Public Key using the JWK JSON serialization format for -// RSA keys. -func (k *rsaPublicKey) MarshalJSON() (data []byte, err error) { - return json.Marshal(k.toMap()) -} - -// PEMBlock serializes this Public Key to DER-encoded PKIX format. -func (k *rsaPublicKey) PEMBlock() (*pem.Block, error) { - derBytes, err := x509.MarshalPKIXPublicKey(k.PublicKey) - if err != nil { - return nil, fmt.Errorf("unable to serialize RSA PublicKey to DER-encoded PKIX format: %s", err) - } - k.extended["kid"] = k.KeyID() // For display purposes. - return createPemBlock("PUBLIC KEY", derBytes, k.extended) -} - -func (k *rsaPublicKey) AddExtendedField(field string, value interface{}) { - k.extended[field] = value -} - -func (k *rsaPublicKey) GetExtendedField(field string) interface{} { - v, ok := k.extended[field] - if !ok { - return nil - } - return v -} - -func rsaPublicKeyFromMap(jwk map[string]interface{}) (*rsaPublicKey, error) { - // JWK key type (kty) has already been determined to be "RSA". - // Need to extract 'n', 'e', and 'kid' and check for - // consistency. - - // Get the modulus parameter N. - nB64Url, err := stringFromMap(jwk, "n") - if err != nil { - return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err) - } - - n, err := parseRSAModulusParam(nB64Url) - if err != nil { - return nil, fmt.Errorf("JWK RSA Public Key modulus: %s", err) - } - - // Get the public exponent E. - eB64Url, err := stringFromMap(jwk, "e") - if err != nil { - return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err) - } - - e, err := parseRSAPublicExponentParam(eB64Url) - if err != nil { - return nil, fmt.Errorf("JWK RSA Public Key exponent: %s", err) - } - - key := &rsaPublicKey{ - PublicKey: &rsa.PublicKey{N: n, E: e}, - } - - // Key ID is optional, but if it exists, it should match the key. - _, ok := jwk["kid"] - if ok { - kid, err := stringFromMap(jwk, "kid") - if err != nil { - return nil, fmt.Errorf("JWK RSA Public Key ID: %s", err) - } - if kid != key.KeyID() { - return nil, fmt.Errorf("JWK RSA Public Key ID does not match: %s", kid) - } - } - - if _, ok := jwk["d"]; ok { - return nil, fmt.Errorf("JWK RSA Public Key cannot contain private exponent") - } - - key.extended = jwk - - return key, nil -} - -/* - * RSA DSA PRIVATE KEY - */ - -// rsaPrivateKey implements a JWK Private Key using RSA digital signature algorithms. -type rsaPrivateKey struct { - rsaPublicKey - *rsa.PrivateKey -} - -func fromRSAPrivateKey(cryptoPrivateKey *rsa.PrivateKey) *rsaPrivateKey { - return &rsaPrivateKey{ - *fromRSAPublicKey(&cryptoPrivateKey.PublicKey), - cryptoPrivateKey, - } -} - -// PublicKey returns the Public Key data associated with this Private Key. -func (k *rsaPrivateKey) PublicKey() PublicKey { - return &k.rsaPublicKey -} - -func (k *rsaPrivateKey) String() string { - return fmt.Sprintf("RSA Private Key <%s>", k.KeyID()) -} - -// Sign signs the data read from the io.Reader using a signature algorithm supported -// by the RSA private key. If the specified hashing algorithm is supported by -// this key, that hash function is used to generate the signature otherwise the -// the default hashing algorithm for this key is used. Returns the signature -// and the name of the JWK signature algorithm used, e.g., "RS256", "RS384", -// "RS512". -func (k *rsaPrivateKey) Sign(data io.Reader, hashID crypto.Hash) (signature []byte, alg string, err error) { - // Generate a signature of the data using the internal alg. - sigAlg := rsaPKCS1v15SignatureAlgorithmForHashID(hashID) - hasher := sigAlg.HashID().New() - - _, err = io.Copy(hasher, data) - if err != nil { - return nil, "", fmt.Errorf("error reading data to sign: %s", err) - } - hash := hasher.Sum(nil) - - signature, err = rsa.SignPKCS1v15(rand.Reader, k.PrivateKey, sigAlg.HashID(), hash) - if err != nil { - return nil, "", fmt.Errorf("error producing signature: %s", err) - } - - alg = sigAlg.HeaderParam() - - return -} - -// CryptoPrivateKey returns the internal object which can be used as a -// crypto.PublicKey for use with other standard library operations. The type -// is either *rsa.PublicKey or *ecdsa.PublicKey -func (k *rsaPrivateKey) CryptoPrivateKey() crypto.PrivateKey { - return k.PrivateKey -} - -func (k *rsaPrivateKey) toMap() map[string]interface{} { - k.Precompute() // Make sure the precomputed values are stored. - jwk := k.rsaPublicKey.toMap() - - jwk["d"] = joseBase64UrlEncode(k.D.Bytes()) - jwk["p"] = joseBase64UrlEncode(k.Primes[0].Bytes()) - jwk["q"] = joseBase64UrlEncode(k.Primes[1].Bytes()) - jwk["dp"] = joseBase64UrlEncode(k.Precomputed.Dp.Bytes()) - jwk["dq"] = joseBase64UrlEncode(k.Precomputed.Dq.Bytes()) - jwk["qi"] = joseBase64UrlEncode(k.Precomputed.Qinv.Bytes()) - - otherPrimes := k.Primes[2:] - - if len(otherPrimes) > 0 { - otherPrimesInfo := make([]interface{}, len(otherPrimes)) - for i, r := range otherPrimes { - otherPrimeInfo := make(map[string]string, 3) - otherPrimeInfo["r"] = joseBase64UrlEncode(r.Bytes()) - crtVal := k.Precomputed.CRTValues[i] - otherPrimeInfo["d"] = joseBase64UrlEncode(crtVal.Exp.Bytes()) - otherPrimeInfo["t"] = joseBase64UrlEncode(crtVal.Coeff.Bytes()) - otherPrimesInfo[i] = otherPrimeInfo - } - jwk["oth"] = otherPrimesInfo - } - - return jwk -} - -// MarshalJSON serializes this Private Key using the JWK JSON serialization format for -// RSA keys. -func (k *rsaPrivateKey) MarshalJSON() (data []byte, err error) { - return json.Marshal(k.toMap()) -} - -// PEMBlock serializes this Private Key to DER-encoded PKIX format. -func (k *rsaPrivateKey) PEMBlock() (*pem.Block, error) { - derBytes := x509.MarshalPKCS1PrivateKey(k.PrivateKey) - k.extended["keyID"] = k.KeyID() // For display purposes. - return createPemBlock("RSA PRIVATE KEY", derBytes, k.extended) -} - -func rsaPrivateKeyFromMap(jwk map[string]interface{}) (*rsaPrivateKey, error) { - // The JWA spec for RSA Private Keys (draft rfc section 5.3.2) states that - // only the private key exponent 'd' is REQUIRED, the others are just for - // signature/decryption optimizations and SHOULD be included when the JWK - // is produced. We MAY choose to accept a JWK which only includes 'd', but - // we're going to go ahead and not choose to accept it without the extra - // fields. Only the 'oth' field will be optional (for multi-prime keys). - privateExponent, err := parseRSAPrivateKeyParamFromMap(jwk, "d") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key exponent: %s", err) - } - firstPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "p") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err) - } - secondPrimeFactor, err := parseRSAPrivateKeyParamFromMap(jwk, "q") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err) - } - firstFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dp") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err) - } - secondFactorCRT, err := parseRSAPrivateKeyParamFromMap(jwk, "dq") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err) - } - crtCoeff, err := parseRSAPrivateKeyParamFromMap(jwk, "qi") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err) - } - - var oth interface{} - if _, ok := jwk["oth"]; ok { - oth = jwk["oth"] - delete(jwk, "oth") - } - - // JWK key type (kty) has already been determined to be "RSA". - // Need to extract the public key information, then extract the private - // key values. - publicKey, err := rsaPublicKeyFromMap(jwk) - if err != nil { - return nil, err - } - - privateKey := &rsa.PrivateKey{ - PublicKey: *publicKey.PublicKey, - D: privateExponent, - Primes: []*big.Int{firstPrimeFactor, secondPrimeFactor}, - Precomputed: rsa.PrecomputedValues{ - Dp: firstFactorCRT, - Dq: secondFactorCRT, - Qinv: crtCoeff, - }, - } - - if oth != nil { - // Should be an array of more JSON objects. - otherPrimesInfo, ok := oth.([]interface{}) - if !ok { - return nil, errors.New("JWK RSA Private Key: Invalid other primes info: must be an array") - } - numOtherPrimeFactors := len(otherPrimesInfo) - if numOtherPrimeFactors == 0 { - return nil, errors.New("JWK RSA Privake Key: Invalid other primes info: must be absent or non-empty") - } - otherPrimeFactors := make([]*big.Int, numOtherPrimeFactors) - productOfPrimes := new(big.Int).Mul(firstPrimeFactor, secondPrimeFactor) - crtValues := make([]rsa.CRTValue, numOtherPrimeFactors) - - for i, val := range otherPrimesInfo { - otherPrimeinfo, ok := val.(map[string]interface{}) - if !ok { - return nil, errors.New("JWK RSA Private Key: Invalid other prime info: must be a JSON object") - } - - otherPrimeFactor, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "r") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key prime factor: %s", err) - } - otherFactorCRT, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "d") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key CRT exponent: %s", err) - } - otherCrtCoeff, err := parseRSAPrivateKeyParamFromMap(otherPrimeinfo, "t") - if err != nil { - return nil, fmt.Errorf("JWK RSA Private Key CRT coefficient: %s", err) - } - - crtValue := crtValues[i] - crtValue.Exp = otherFactorCRT - crtValue.Coeff = otherCrtCoeff - crtValue.R = productOfPrimes - otherPrimeFactors[i] = otherPrimeFactor - productOfPrimes = new(big.Int).Mul(productOfPrimes, otherPrimeFactor) - } - - privateKey.Primes = append(privateKey.Primes, otherPrimeFactors...) - privateKey.Precomputed.CRTValues = crtValues - } - - key := &rsaPrivateKey{ - rsaPublicKey: *publicKey, - PrivateKey: privateKey, - } - - return key, nil -} - -/* - * Key Generation Functions. - */ - -func generateRSAPrivateKey(bits int) (k *rsaPrivateKey, err error) { - k = new(rsaPrivateKey) - k.PrivateKey, err = rsa.GenerateKey(rand.Reader, bits) - if err != nil { - return nil, err - } - - k.rsaPublicKey.PublicKey = &k.PrivateKey.PublicKey - k.extended = make(map[string]interface{}) - - return -} - -// GenerateRSA2048PrivateKey generates a key pair using 2048-bit RSA. -func GenerateRSA2048PrivateKey() (PrivateKey, error) { - k, err := generateRSAPrivateKey(2048) - if err != nil { - return nil, fmt.Errorf("error generating RSA 2048-bit key: %s", err) - } - - return k, nil -} - -// GenerateRSA3072PrivateKey generates a key pair using 3072-bit RSA. -func GenerateRSA3072PrivateKey() (PrivateKey, error) { - k, err := generateRSAPrivateKey(3072) - if err != nil { - return nil, fmt.Errorf("error generating RSA 3072-bit key: %s", err) - } - - return k, nil -} - -// GenerateRSA4096PrivateKey generates a key pair using 4096-bit RSA. -func GenerateRSA4096PrivateKey() (PrivateKey, error) { - k, err := generateRSAPrivateKey(4096) - if err != nil { - return nil, fmt.Errorf("error generating RSA 4096-bit key: %s", err) - } - - return k, nil -} diff --git a/vendor/github.com/docker/libtrust/util.go b/vendor/github.com/docker/libtrust/util.go deleted file mode 100644 index a5a101d3f1..0000000000 --- a/vendor/github.com/docker/libtrust/util.go +++ /dev/null @@ -1,363 +0,0 @@ -package libtrust - -import ( - "bytes" - "crypto" - "crypto/elliptic" - "crypto/tls" - "crypto/x509" - "encoding/base32" - "encoding/base64" - "encoding/binary" - "encoding/pem" - "errors" - "fmt" - "math/big" - "net/url" - "os" - "path/filepath" - "strings" - "time" -) - -// LoadOrCreateTrustKey will load a PrivateKey from the specified path -func LoadOrCreateTrustKey(trustKeyPath string) (PrivateKey, error) { - if err := os.MkdirAll(filepath.Dir(trustKeyPath), 0700); err != nil { - return nil, err - } - - trustKey, err := LoadKeyFile(trustKeyPath) - if err == ErrKeyFileDoesNotExist { - trustKey, err = GenerateECP256PrivateKey() - if err != nil { - return nil, fmt.Errorf("error generating key: %s", err) - } - - if err := SaveKey(trustKeyPath, trustKey); err != nil { - return nil, fmt.Errorf("error saving key file: %s", err) - } - - dir, file := filepath.Split(trustKeyPath) - if err := SavePublicKey(filepath.Join(dir, "public-"+file), trustKey.PublicKey()); err != nil { - return nil, fmt.Errorf("error saving public key file: %s", err) - } - } else if err != nil { - return nil, fmt.Errorf("error loading key file: %s", err) - } - return trustKey, nil -} - -// NewIdentityAuthTLSClientConfig returns a tls.Config configured to use identity -// based authentication from the specified dockerUrl, the rootConfigPath and -// the server name to which it is connecting. -// If trustUnknownHosts is true it will automatically add the host to the -// known-hosts.json in rootConfigPath. -func NewIdentityAuthTLSClientConfig(dockerUrl string, trustUnknownHosts bool, rootConfigPath string, serverName string) (*tls.Config, error) { - tlsConfig := newTLSConfig() - - trustKeyPath := filepath.Join(rootConfigPath, "key.json") - knownHostsPath := filepath.Join(rootConfigPath, "known-hosts.json") - - u, err := url.Parse(dockerUrl) - if err != nil { - return nil, fmt.Errorf("unable to parse machine url") - } - - if u.Scheme == "unix" { - return nil, nil - } - - addr := u.Host - proto := "tcp" - - trustKey, err := LoadOrCreateTrustKey(trustKeyPath) - if err != nil { - return nil, fmt.Errorf("unable to load trust key: %s", err) - } - - knownHosts, err := LoadKeySetFile(knownHostsPath) - if err != nil { - return nil, fmt.Errorf("could not load trusted hosts file: %s", err) - } - - allowedHosts, err := FilterByHosts(knownHosts, addr, false) - if err != nil { - return nil, fmt.Errorf("error filtering hosts: %s", err) - } - - certPool, err := GenerateCACertPool(trustKey, allowedHosts) - if err != nil { - return nil, fmt.Errorf("Could not create CA pool: %s", err) - } - - tlsConfig.ServerName = serverName - tlsConfig.RootCAs = certPool - - x509Cert, err := GenerateSelfSignedClientCert(trustKey) - if err != nil { - return nil, fmt.Errorf("certificate generation error: %s", err) - } - - tlsConfig.Certificates = []tls.Certificate{{ - Certificate: [][]byte{x509Cert.Raw}, - PrivateKey: trustKey.CryptoPrivateKey(), - Leaf: x509Cert, - }} - - tlsConfig.InsecureSkipVerify = true - - testConn, err := tls.Dial(proto, addr, tlsConfig) - if err != nil { - return nil, fmt.Errorf("tls Handshake error: %s", err) - } - - opts := x509.VerifyOptions{ - Roots: tlsConfig.RootCAs, - CurrentTime: time.Now(), - DNSName: tlsConfig.ServerName, - Intermediates: x509.NewCertPool(), - } - - certs := testConn.ConnectionState().PeerCertificates - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - - if _, err := certs[0].Verify(opts); err != nil { - if _, ok := err.(x509.UnknownAuthorityError); ok { - if trustUnknownHosts { - pubKey, err := FromCryptoPublicKey(certs[0].PublicKey) - if err != nil { - return nil, fmt.Errorf("error extracting public key from cert: %s", err) - } - - pubKey.AddExtendedField("hosts", []string{addr}) - - if err := AddKeySetFile(knownHostsPath, pubKey); err != nil { - return nil, fmt.Errorf("error adding machine to known hosts: %s", err) - } - } else { - return nil, fmt.Errorf("unable to connect. unknown host: %s", addr) - } - } - } - - testConn.Close() - tlsConfig.InsecureSkipVerify = false - - return tlsConfig, nil -} - -// joseBase64UrlEncode encodes the given data using the standard base64 url -// encoding format but with all trailing '=' characters omitted in accordance -// with the jose specification. -// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-2 -func joseBase64UrlEncode(b []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") -} - -// joseBase64UrlDecode decodes the given string using the standard base64 url -// decoder but first adds the appropriate number of trailing '=' characters in -// accordance with the jose specification. -// http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-31#section-2 -func joseBase64UrlDecode(s string) ([]byte, error) { - s = strings.Replace(s, "\n", "", -1) - s = strings.Replace(s, " ", "", -1) - switch len(s) % 4 { - case 0: - case 2: - s += "==" - case 3: - s += "=" - default: - return nil, errors.New("illegal base64url string") - } - return base64.URLEncoding.DecodeString(s) -} - -func keyIDEncode(b []byte) string { - s := strings.TrimRight(base32.StdEncoding.EncodeToString(b), "=") - var buf bytes.Buffer - var i int - for i = 0; i < len(s)/4-1; i++ { - start := i * 4 - end := start + 4 - buf.WriteString(s[start:end] + ":") - } - buf.WriteString(s[i*4:]) - return buf.String() -} - -func keyIDFromCryptoKey(pubKey PublicKey) string { - // Generate and return a 'libtrust' fingerprint of the public key. - // For an RSA key this should be: - // SHA256(DER encoded ASN1) - // Then truncated to 240 bits and encoded into 12 base32 groups like so: - // ABCD:EFGH:IJKL:MNOP:QRST:UVWX:YZ23:4567:ABCD:EFGH:IJKL:MNOP - derBytes, err := x509.MarshalPKIXPublicKey(pubKey.CryptoPublicKey()) - if err != nil { - return "" - } - hasher := crypto.SHA256.New() - hasher.Write(derBytes) - return keyIDEncode(hasher.Sum(nil)[:30]) -} - -func stringFromMap(m map[string]interface{}, key string) (string, error) { - val, ok := m[key] - if !ok { - return "", fmt.Errorf("%q value not specified", key) - } - - str, ok := val.(string) - if !ok { - return "", fmt.Errorf("%q value must be a string", key) - } - delete(m, key) - - return str, nil -} - -func parseECCoordinate(cB64Url string, curve elliptic.Curve) (*big.Int, error) { - curveByteLen := (curve.Params().BitSize + 7) >> 3 - - cBytes, err := joseBase64UrlDecode(cB64Url) - if err != nil { - return nil, fmt.Errorf("invalid base64 URL encoding: %s", err) - } - cByteLength := len(cBytes) - if cByteLength != curveByteLen { - return nil, fmt.Errorf("invalid number of octets: got %d, should be %d", cByteLength, curveByteLen) - } - return new(big.Int).SetBytes(cBytes), nil -} - -func parseECPrivateParam(dB64Url string, curve elliptic.Curve) (*big.Int, error) { - dBytes, err := joseBase64UrlDecode(dB64Url) - if err != nil { - return nil, fmt.Errorf("invalid base64 URL encoding: %s", err) - } - - // The length of this octet string MUST be ceiling(log-base-2(n)/8) - // octets (where n is the order of the curve). This is because the private - // key d must be in the interval [1, n-1] so the bitlength of d should be - // no larger than the bitlength of n-1. The easiest way to find the octet - // length is to take bitlength(n-1), add 7 to force a carry, and shift this - // bit sequence right by 3, which is essentially dividing by 8 and adding - // 1 if there is any remainder. Thus, the private key value d should be - // output to (bitlength(n-1)+7)>>3 octets. - n := curve.Params().N - octetLength := (new(big.Int).Sub(n, big.NewInt(1)).BitLen() + 7) >> 3 - dByteLength := len(dBytes) - - if dByteLength != octetLength { - return nil, fmt.Errorf("invalid number of octets: got %d, should be %d", dByteLength, octetLength) - } - - return new(big.Int).SetBytes(dBytes), nil -} - -func parseRSAModulusParam(nB64Url string) (*big.Int, error) { - nBytes, err := joseBase64UrlDecode(nB64Url) - if err != nil { - return nil, fmt.Errorf("invalid base64 URL encoding: %s", err) - } - - return new(big.Int).SetBytes(nBytes), nil -} - -func serializeRSAPublicExponentParam(e int) []byte { - // We MUST use the minimum number of octets to represent E. - // E is supposed to be 65537 for performance and security reasons - // and is what golang's rsa package generates, but it might be - // different if imported from some other generator. - buf := make([]byte, 4) - binary.BigEndian.PutUint32(buf, uint32(e)) - var i int - for i = 0; i < 8; i++ { - if buf[i] != 0 { - break - } - } - return buf[i:] -} - -func parseRSAPublicExponentParam(eB64Url string) (int, error) { - eBytes, err := joseBase64UrlDecode(eB64Url) - if err != nil { - return 0, fmt.Errorf("invalid base64 URL encoding: %s", err) - } - // Only the minimum number of bytes were used to represent E, but - // binary.BigEndian.Uint32 expects at least 4 bytes, so we need - // to add zero padding if necassary. - byteLen := len(eBytes) - buf := make([]byte, 4-byteLen, 4) - eBytes = append(buf, eBytes...) - - return int(binary.BigEndian.Uint32(eBytes)), nil -} - -func parseRSAPrivateKeyParamFromMap(m map[string]interface{}, key string) (*big.Int, error) { - b64Url, err := stringFromMap(m, key) - if err != nil { - return nil, err - } - - paramBytes, err := joseBase64UrlDecode(b64Url) - if err != nil { - return nil, fmt.Errorf("invaled base64 URL encoding: %s", err) - } - - return new(big.Int).SetBytes(paramBytes), nil -} - -func createPemBlock(name string, derBytes []byte, headers map[string]interface{}) (*pem.Block, error) { - pemBlock := &pem.Block{Type: name, Bytes: derBytes, Headers: map[string]string{}} - for k, v := range headers { - switch val := v.(type) { - case string: - pemBlock.Headers[k] = val - case []string: - if k == "hosts" { - pemBlock.Headers[k] = strings.Join(val, ",") - } else { - // Return error, non-encodable type - } - default: - // Return error, non-encodable type - } - } - - return pemBlock, nil -} - -func pubKeyFromPEMBlock(pemBlock *pem.Block) (PublicKey, error) { - cryptoPublicKey, err := x509.ParsePKIXPublicKey(pemBlock.Bytes) - if err != nil { - return nil, fmt.Errorf("unable to decode Public Key PEM data: %s", err) - } - - pubKey, err := FromCryptoPublicKey(cryptoPublicKey) - if err != nil { - return nil, err - } - - addPEMHeadersToKey(pemBlock, pubKey) - - return pubKey, nil -} - -func addPEMHeadersToKey(pemBlock *pem.Block, pubKey PublicKey) { - for key, value := range pemBlock.Headers { - var safeVal interface{} - if key == "hosts" { - safeVal = strings.Split(value, ",") - } else { - safeVal = value - } - pubKey.AddExtendedField(key, safeVal) - } -} diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md deleted file mode 100644 index 25fdaf639d..0000000000 --- a/vendor/github.com/fatih/color/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Fatih Arslan - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md deleted file mode 100644 index 623baf3c39..0000000000 --- a/vendor/github.com/fatih/color/README.md +++ /dev/null @@ -1,177 +0,0 @@ -# Color [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/color) [![Build Status](http://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color) - - - -Color lets you use colorized outputs in terms of [ANSI Escape -Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It -has support for Windows too! The API can be used in several ways, pick one that -suits you. - - -![Color](http://i.imgur.com/c1JI0lA.png) - - -## Install - -```bash -go get github.com/fatih/color -``` - -Note that the `vendor` folder is here for stability. Remove the folder if you -already have the dependencies in your GOPATH. - -## Examples - -### Standard colors - -```go -// Print with default helper functions -color.Cyan("Prints text in cyan.") - -// A newline will be appended automatically -color.Blue("Prints %s in blue.", "text") - -// These are using the default foreground colors -color.Red("We have red") -color.Magenta("And many others ..") - -``` - -### Mix and reuse colors - -```go -// Create a new color object -c := color.New(color.FgCyan).Add(color.Underline) -c.Println("Prints cyan text with an underline.") - -// Or just add them to New() -d := color.New(color.FgCyan, color.Bold) -d.Printf("This prints bold cyan %s\n", "too!.") - -// Mix up foreground and background colors, create new mixes! -red := color.New(color.FgRed) - -boldRed := red.Add(color.Bold) -boldRed.Println("This will print text in bold red.") - -whiteBackground := red.Add(color.BgWhite) -whiteBackground.Println("Red text with white background.") -``` - -### Use your own output (io.Writer) - -```go -// Use your own io.Writer output -color.New(color.FgBlue).Fprintln(myWriter, "blue color!") - -blue := color.New(color.FgBlue) -blue.Fprint(writer, "This will print text in blue.") -``` - -### Custom print functions (PrintFunc) - -```go -// Create a custom print function for convenience -red := color.New(color.FgRed).PrintfFunc() -red("Warning") -red("Error: %s", err) - -// Mix up multiple attributes -notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() -notice("Don't forget this...") -``` - -### Custom fprint functions (FprintFunc) - -```go -blue := color.New(FgBlue).FprintfFunc() -blue(myWriter, "important notice: %s", stars) - -// Mix up with multiple attributes -success := color.New(color.Bold, color.FgGreen).FprintlnFunc() -success(myWriter, "Don't forget this...") -``` - -### Insert into noncolor strings (SprintFunc) - -```go -// Create SprintXxx functions to mix strings with other non-colorized strings: -yellow := color.New(color.FgYellow).SprintFunc() -red := color.New(color.FgRed).SprintFunc() -fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error")) - -info := color.New(color.FgWhite, color.BgGreen).SprintFunc() -fmt.Printf("This %s rocks!\n", info("package")) - -// Use helper functions -fmt.Println("This", color.RedString("warning"), "should be not neglected.") -fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.") - -// Windows supported too! Just don't forget to change the output to color.Output -fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) -``` - -### Plug into existing code - -```go -// Use handy standard colors -color.Set(color.FgYellow) - -fmt.Println("Existing text will now be in yellow") -fmt.Printf("This one %s\n", "too") - -color.Unset() // Don't forget to unset - -// You can mix up parameters -color.Set(color.FgMagenta, color.Bold) -defer color.Unset() // Use it in your function - -fmt.Println("All text will now be bold magenta.") -``` - -### Disable color - -There might be a case where you want to disable color output (for example to -pipe the standard output of your app to somewhere else). `Color` has support to -disable colors both globally and for single color definition. For example -suppose you have a CLI app and a `--no-color` bool flag. You can easily disable -the color output with: - -```go - -var flagNoColor = flag.Bool("no-color", false, "Disable color output") - -if *flagNoColor { - color.NoColor = true // disables colorized output -} -``` - -It also has support for single color definitions (local). You can -disable/enable color output on the fly: - -```go -c := color.New(color.FgCyan) -c.Println("Prints cyan text") - -c.DisableColor() -c.Println("This is printed without any color") - -c.EnableColor() -c.Println("This prints again cyan...") -``` - -## Todo - -* Save/Return previous values -* Evaluate fmt.Formatter interface - - -## Credits - - * [Fatih Arslan](https://github.com/fatih) - * Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable) - -## License - -The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details - diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go deleted file mode 100644 index 7b5f3146d3..0000000000 --- a/vendor/github.com/fatih/color/color.go +++ /dev/null @@ -1,600 +0,0 @@ -package color - -import ( - "fmt" - "io" - "os" - "strconv" - "strings" - "sync" - - "github.com/mattn/go-colorable" - "github.com/mattn/go-isatty" -) - -var ( - // NoColor defines if the output is colorized or not. It's dynamically set to - // false or true based on the stdout's file descriptor referring to a terminal - // or not. This is a global option and affects all colors. For more control - // over each color block use the methods DisableColor() individually. - NoColor = os.Getenv("TERM") == "dumb" || - (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) - - // Output defines the standard output of the print functions. By default - // os.Stdout is used. - Output = colorable.NewColorableStdout() - - // colorsCache is used to reduce the count of created Color objects and - // allows to reuse already created objects with required Attribute. - colorsCache = make(map[Attribute]*Color) - colorsCacheMu sync.Mutex // protects colorsCache -) - -// Color defines a custom color object which is defined by SGR parameters. -type Color struct { - params []Attribute - noColor *bool -} - -// Attribute defines a single SGR Code -type Attribute int - -const escape = "\x1b" - -// Base attributes -const ( - Reset Attribute = iota - Bold - Faint - Italic - Underline - BlinkSlow - BlinkRapid - ReverseVideo - Concealed - CrossedOut -) - -// Foreground text colors -const ( - FgBlack Attribute = iota + 30 - FgRed - FgGreen - FgYellow - FgBlue - FgMagenta - FgCyan - FgWhite -) - -// Foreground Hi-Intensity text colors -const ( - FgHiBlack Attribute = iota + 90 - FgHiRed - FgHiGreen - FgHiYellow - FgHiBlue - FgHiMagenta - FgHiCyan - FgHiWhite -) - -// Background text colors -const ( - BgBlack Attribute = iota + 40 - BgRed - BgGreen - BgYellow - BgBlue - BgMagenta - BgCyan - BgWhite -) - -// Background Hi-Intensity text colors -const ( - BgHiBlack Attribute = iota + 100 - BgHiRed - BgHiGreen - BgHiYellow - BgHiBlue - BgHiMagenta - BgHiCyan - BgHiWhite -) - -// New returns a newly created color object. -func New(value ...Attribute) *Color { - c := &Color{params: make([]Attribute, 0)} - c.Add(value...) - return c -} - -// Set sets the given parameters immediately. It will change the color of -// output with the given SGR parameters until color.Unset() is called. -func Set(p ...Attribute) *Color { - c := New(p...) - c.Set() - return c -} - -// Unset resets all escape attributes and clears the output. Usually should -// be called after Set(). -func Unset() { - if NoColor { - return - } - - fmt.Fprintf(Output, "%s[%dm", escape, Reset) -} - -// Set sets the SGR sequence. -func (c *Color) Set() *Color { - if c.isNoColorSet() { - return c - } - - fmt.Fprintf(Output, c.format()) - return c -} - -func (c *Color) unset() { - if c.isNoColorSet() { - return - } - - Unset() -} - -func (c *Color) setWriter(w io.Writer) *Color { - if c.isNoColorSet() { - return c - } - - fmt.Fprintf(w, c.format()) - return c -} - -func (c *Color) unsetWriter(w io.Writer) { - if c.isNoColorSet() { - return - } - - if NoColor { - return - } - - fmt.Fprintf(w, "%s[%dm", escape, Reset) -} - -// Add is used to chain SGR parameters. Use as many as parameters to combine -// and create custom color objects. Example: Add(color.FgRed, color.Underline). -func (c *Color) Add(value ...Attribute) *Color { - c.params = append(c.params, value...) - return c -} - -func (c *Color) prepend(value Attribute) { - c.params = append(c.params, 0) - copy(c.params[1:], c.params[0:]) - c.params[0] = value -} - -// Fprint formats using the default formats for its operands and writes to w. -// Spaces are added between operands when neither is a string. -// It returns the number of bytes written and any write error encountered. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - c.setWriter(w) - defer c.unsetWriter(w) - - return fmt.Fprint(w, a...) -} - -// Print formats using the default formats for its operands and writes to -// standard output. Spaces are added between operands when neither is a -// string. It returns the number of bytes written and any write error -// encountered. This is the standard fmt.Print() method wrapped with the given -// color. -func (c *Color) Print(a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprint(Output, a...) -} - -// Fprintf formats according to a format specifier and writes to w. -// It returns the number of bytes written and any write error encountered. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - c.setWriter(w) - defer c.unsetWriter(w) - - return fmt.Fprintf(w, format, a...) -} - -// Printf formats according to a format specifier and writes to standard output. -// It returns the number of bytes written and any write error encountered. -// This is the standard fmt.Printf() method wrapped with the given color. -func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprintf(Output, format, a...) -} - -// Fprintln formats using the default formats for its operands and writes to w. -// Spaces are always added between operands and a newline is appended. -// On Windows, users should wrap w with colorable.NewColorable() if w is of -// type *os.File. -func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - c.setWriter(w) - defer c.unsetWriter(w) - - return fmt.Fprintln(w, a...) -} - -// Println formats using the default formats for its operands and writes to -// standard output. Spaces are always added between operands and a newline is -// appended. It returns the number of bytes written and any write error -// encountered. This is the standard fmt.Print() method wrapped with the given -// color. -func (c *Color) Println(a ...interface{}) (n int, err error) { - c.Set() - defer c.unset() - - return fmt.Fprintln(Output, a...) -} - -// Sprint is just like Print, but returns a string instead of printing it. -func (c *Color) Sprint(a ...interface{}) string { - return c.wrap(fmt.Sprint(a...)) -} - -// Sprintln is just like Println, but returns a string instead of printing it. -func (c *Color) Sprintln(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) -} - -// Sprintf is just like Printf, but returns a string instead of printing it. -func (c *Color) Sprintf(format string, a ...interface{}) string { - return c.wrap(fmt.Sprintf(format, a...)) -} - -// FprintFunc returns a new function that prints the passed arguments as -// colorized with color.Fprint(). -func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) { - return func(w io.Writer, a ...interface{}) { - c.Fprint(w, a...) - } -} - -// PrintFunc returns a new function that prints the passed arguments as -// colorized with color.Print(). -func (c *Color) PrintFunc() func(a ...interface{}) { - return func(a ...interface{}) { - c.Print(a...) - } -} - -// FprintfFunc returns a new function that prints the passed arguments as -// colorized with color.Fprintf(). -func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) { - return func(w io.Writer, format string, a ...interface{}) { - c.Fprintf(w, format, a...) - } -} - -// PrintfFunc returns a new function that prints the passed arguments as -// colorized with color.Printf(). -func (c *Color) PrintfFunc() func(format string, a ...interface{}) { - return func(format string, a ...interface{}) { - c.Printf(format, a...) - } -} - -// FprintlnFunc returns a new function that prints the passed arguments as -// colorized with color.Fprintln(). -func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) { - return func(w io.Writer, a ...interface{}) { - c.Fprintln(w, a...) - } -} - -// PrintlnFunc returns a new function that prints the passed arguments as -// colorized with color.Println(). -func (c *Color) PrintlnFunc() func(a ...interface{}) { - return func(a ...interface{}) { - c.Println(a...) - } -} - -// SprintFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprint(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output, example: -// -// put := New(FgYellow).SprintFunc() -// fmt.Fprintf(color.Output, "This is a %s", put("warning")) -func (c *Color) SprintFunc() func(a ...interface{}) string { - return func(a ...interface{}) string { - return c.wrap(fmt.Sprint(a...)) - } -} - -// SprintfFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprintf(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output. -func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { - return func(format string, a ...interface{}) string { - return c.wrap(fmt.Sprintf(format, a...)) - } -} - -// SprintlnFunc returns a new function that returns colorized strings for the -// given arguments with fmt.Sprintln(). Useful to put into or mix into other -// string. Windows users should use this in conjunction with color.Output. -func (c *Color) SprintlnFunc() func(a ...interface{}) string { - return func(a ...interface{}) string { - return c.wrap(fmt.Sprintln(a...)) - } -} - -// sequence returns a formated SGR sequence to be plugged into a "\x1b[...m" -// an example output might be: "1;36" -> bold cyan -func (c *Color) sequence() string { - format := make([]string, len(c.params)) - for i, v := range c.params { - format[i] = strconv.Itoa(int(v)) - } - - return strings.Join(format, ";") -} - -// wrap wraps the s string with the colors attributes. The string is ready to -// be printed. -func (c *Color) wrap(s string) string { - if c.isNoColorSet() { - return s - } - - return c.format() + s + c.unformat() -} - -func (c *Color) format() string { - return fmt.Sprintf("%s[%sm", escape, c.sequence()) -} - -func (c *Color) unformat() string { - return fmt.Sprintf("%s[%dm", escape, Reset) -} - -// DisableColor disables the color output. Useful to not change any existing -// code and still being able to output. Can be used for flags like -// "--no-color". To enable back use EnableColor() method. -func (c *Color) DisableColor() { - c.noColor = boolPtr(true) -} - -// EnableColor enables the color output. Use it in conjunction with -// DisableColor(). Otherwise this method has no side effects. -func (c *Color) EnableColor() { - c.noColor = boolPtr(false) -} - -func (c *Color) isNoColorSet() bool { - // check first if we have user setted action - if c.noColor != nil { - return *c.noColor - } - - // if not return the global option, which is disabled by default - return NoColor -} - -// Equals returns a boolean value indicating whether two colors are equal. -func (c *Color) Equals(c2 *Color) bool { - if len(c.params) != len(c2.params) { - return false - } - - for _, attr := range c.params { - if !c2.attrExists(attr) { - return false - } - } - - return true -} - -func (c *Color) attrExists(a Attribute) bool { - for _, attr := range c.params { - if attr == a { - return true - } - } - - return false -} - -func boolPtr(v bool) *bool { - return &v -} - -func getCachedColor(p Attribute) *Color { - colorsCacheMu.Lock() - defer colorsCacheMu.Unlock() - - c, ok := colorsCache[p] - if !ok { - c = New(p) - colorsCache[p] = c - } - - return c -} - -func colorPrint(format string, p Attribute, a ...interface{}) { - c := getCachedColor(p) - - if !strings.HasSuffix(format, "\n") { - format += "\n" - } - - if len(a) == 0 { - c.Print(format) - } else { - c.Printf(format, a...) - } -} - -func colorString(format string, p Attribute, a ...interface{}) string { - c := getCachedColor(p) - - if len(a) == 0 { - return c.SprintFunc()(format) - } - - return c.SprintfFunc()(format, a...) -} - -// Black is a convenient helper function to print with black foreground. A -// newline is appended to format by default. -func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) } - -// Red is a convenient helper function to print with red foreground. A -// newline is appended to format by default. -func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) } - -// Green is a convenient helper function to print with green foreground. A -// newline is appended to format by default. -func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) } - -// Yellow is a convenient helper function to print with yellow foreground. -// A newline is appended to format by default. -func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) } - -// Blue is a convenient helper function to print with blue foreground. A -// newline is appended to format by default. -func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) } - -// Magenta is a convenient helper function to print with magenta foreground. -// A newline is appended to format by default. -func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) } - -// Cyan is a convenient helper function to print with cyan foreground. A -// newline is appended to format by default. -func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) } - -// White is a convenient helper function to print with white foreground. A -// newline is appended to format by default. -func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) } - -// BlackString is a convenient helper function to return a string with black -// foreground. -func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) } - -// RedString is a convenient helper function to return a string with red -// foreground. -func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) } - -// GreenString is a convenient helper function to return a string with green -// foreground. -func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) } - -// YellowString is a convenient helper function to return a string with yellow -// foreground. -func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) } - -// BlueString is a convenient helper function to return a string with blue -// foreground. -func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) } - -// MagentaString is a convenient helper function to return a string with magenta -// foreground. -func MagentaString(format string, a ...interface{}) string { - return colorString(format, FgMagenta, a...) -} - -// CyanString is a convenient helper function to return a string with cyan -// foreground. -func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) } - -// WhiteString is a convenient helper function to return a string with white -// foreground. -func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) } - -// HiBlack is a convenient helper function to print with hi-intensity black foreground. A -// newline is appended to format by default. -func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) } - -// HiRed is a convenient helper function to print with hi-intensity red foreground. A -// newline is appended to format by default. -func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) } - -// HiGreen is a convenient helper function to print with hi-intensity green foreground. A -// newline is appended to format by default. -func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) } - -// HiYellow is a convenient helper function to print with hi-intensity yellow foreground. -// A newline is appended to format by default. -func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) } - -// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A -// newline is appended to format by default. -func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) } - -// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground. -// A newline is appended to format by default. -func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) } - -// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A -// newline is appended to format by default. -func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) } - -// HiWhite is a convenient helper function to print with hi-intensity white foreground. A -// newline is appended to format by default. -func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) } - -// HiBlackString is a convenient helper function to return a string with hi-intensity black -// foreground. -func HiBlackString(format string, a ...interface{}) string { - return colorString(format, FgHiBlack, a...) -} - -// HiRedString is a convenient helper function to return a string with hi-intensity red -// foreground. -func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) } - -// HiGreenString is a convenient helper function to return a string with hi-intensity green -// foreground. -func HiGreenString(format string, a ...interface{}) string { - return colorString(format, FgHiGreen, a...) -} - -// HiYellowString is a convenient helper function to return a string with hi-intensity yellow -// foreground. -func HiYellowString(format string, a ...interface{}) string { - return colorString(format, FgHiYellow, a...) -} - -// HiBlueString is a convenient helper function to return a string with hi-intensity blue -// foreground. -func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) } - -// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta -// foreground. -func HiMagentaString(format string, a ...interface{}) string { - return colorString(format, FgHiMagenta, a...) -} - -// HiCyanString is a convenient helper function to return a string with hi-intensity cyan -// foreground. -func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) } - -// HiWhiteString is a convenient helper function to return a string with hi-intensity white -// foreground. -func HiWhiteString(format string, a ...interface{}) string { - return colorString(format, FgHiWhite, a...) -} diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go deleted file mode 100644 index cf1e96500f..0000000000 --- a/vendor/github.com/fatih/color/doc.go +++ /dev/null @@ -1,133 +0,0 @@ -/* -Package color is an ANSI color package to output colorized or SGR defined -output to the standard output. The API can be used in several way, pick one -that suits you. - -Use simple and default helper functions with predefined foreground colors: - - color.Cyan("Prints text in cyan.") - - // a newline will be appended automatically - color.Blue("Prints %s in blue.", "text") - - // More default foreground colors.. - color.Red("We have red") - color.Yellow("Yellow color too!") - color.Magenta("And many others ..") - - // Hi-intensity colors - color.HiGreen("Bright green color.") - color.HiBlack("Bright black means gray..") - color.HiWhite("Shiny white color!") - -However there are times where custom color mixes are required. Below are some -examples to create custom color objects and use the print functions of each -separate color object. - - // Create a new color object - c := color.New(color.FgCyan).Add(color.Underline) - c.Println("Prints cyan text with an underline.") - - // Or just add them to New() - d := color.New(color.FgCyan, color.Bold) - d.Printf("This prints bold cyan %s\n", "too!.") - - - // Mix up foreground and background colors, create new mixes! - red := color.New(color.FgRed) - - boldRed := red.Add(color.Bold) - boldRed.Println("This will print text in bold red.") - - whiteBackground := red.Add(color.BgWhite) - whiteBackground.Println("Red text with White background.") - - // Use your own io.Writer output - color.New(color.FgBlue).Fprintln(myWriter, "blue color!") - - blue := color.New(color.FgBlue) - blue.Fprint(myWriter, "This will print text in blue.") - -You can create PrintXxx functions to simplify even more: - - // Create a custom print function for convenient - red := color.New(color.FgRed).PrintfFunc() - red("warning") - red("error: %s", err) - - // Mix up multiple attributes - notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() - notice("don't forget this...") - -You can also FprintXxx functions to pass your own io.Writer: - - blue := color.New(FgBlue).FprintfFunc() - blue(myWriter, "important notice: %s", stars) - - // Mix up with multiple attributes - success := color.New(color.Bold, color.FgGreen).FprintlnFunc() - success(myWriter, don't forget this...") - - -Or create SprintXxx functions to mix strings with other non-colorized strings: - - yellow := New(FgYellow).SprintFunc() - red := New(FgRed).SprintFunc() - - fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error")) - - info := New(FgWhite, BgGreen).SprintFunc() - fmt.Printf("this %s rocks!\n", info("package")) - -Windows support is enabled by default. All Print functions work as intended. -However only for color.SprintXXX functions, user should use fmt.FprintXXX and -set the output to color.Output: - - fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) - - info := New(FgWhite, BgGreen).SprintFunc() - fmt.Fprintf(color.Output, "this %s rocks!\n", info("package")) - -Using with existing code is possible. Just use the Set() method to set the -standard output to the given parameters. That way a rewrite of an existing -code is not required. - - // Use handy standard colors. - color.Set(color.FgYellow) - - fmt.Println("Existing text will be now in Yellow") - fmt.Printf("This one %s\n", "too") - - color.Unset() // don't forget to unset - - // You can mix up parameters - color.Set(color.FgMagenta, color.Bold) - defer color.Unset() // use it in your function - - fmt.Println("All text will be now bold magenta.") - -There might be a case where you want to disable color output (for example to -pipe the standard output of your app to somewhere else). `Color` has support to -disable colors both globally and for single color definition. For example -suppose you have a CLI app and a `--no-color` bool flag. You can easily disable -the color output with: - - var flagNoColor = flag.Bool("no-color", false, "Disable color output") - - if *flagNoColor { - color.NoColor = true // disables colorized output - } - -It also has support for single color definitions (local). You can -disable/enable color output on the fly: - - c := color.New(color.FgCyan) - c.Println("Prints cyan text") - - c.DisableColor() - c.Println("This is printed without any color") - - c.EnableColor() - c.Println("This prints again cyan...") -*/ -package color diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE deleted file mode 100644 index 7805d36de7..0000000000 --- a/vendor/github.com/ghodss/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md deleted file mode 100644 index 0200f75b4d..0000000000 --- a/vendor/github.com/ghodss/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go deleted file mode 100644 index 5860074026..0000000000 --- a/vendor/github.com/ghodss/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// 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 yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go deleted file mode 100644 index 4fb4054a8b..0000000000 --- a/vendor/github.com/ghodss/yaml/yaml.go +++ /dev/null @@ -1,277 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - - "gopkg.in/yaml.v2" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// Converts YAML to JSON then uses JSON to unmarshal into an object. -func Unmarshal(y []byte, o interface{}) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = json.Unmarshal(j, o) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through -// this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yaml.Unmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE deleted file mode 100644 index 37ec93a14f..0000000000 --- a/vendor/github.com/go-ini/ini/LICENSE +++ /dev/null @@ -1,191 +0,0 @@ -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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work - -To apply the Apache License to your work, attach the following boilerplate -notice, with the fields enclosed by brackets "[]" replaced with your own -identifying information. (Don't include the brackets!) The text should be -enclosed in the appropriate comment syntax for the file format. We also -recommend that a file or class name and description of purpose be included on -the same "printed page" as the copyright notice for easier identification within -third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-ini/ini/Makefile b/vendor/github.com/go-ini/ini/Makefile deleted file mode 100644 index ac034e5258..0000000000 --- a/vendor/github.com/go-ini/ini/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -.PHONY: build test bench vet - -build: vet bench - -test: - go test -v -cover -race - -bench: - go test -v -cover -race -test.bench=. -test.benchmem - -vet: - go vet diff --git a/vendor/github.com/go-ini/ini/README.md b/vendor/github.com/go-ini/ini/README.md deleted file mode 100644 index e67d51f320..0000000000 --- a/vendor/github.com/go-ini/ini/README.md +++ /dev/null @@ -1,746 +0,0 @@ -INI [![Build Status](https://travis-ci.org/go-ini/ini.svg?branch=master)](https://travis-ci.org/go-ini/ini) [![Sourcegraph](https://sourcegraph.com/github.com/go-ini/ini/-/badge.svg)](https://sourcegraph.com/github.com/go-ini/ini?badge) -=== - -![](https://avatars0.githubusercontent.com/u/10216035?v=3&s=200) - -Package ini provides INI file read and write functionality in Go. - -[简体中文](README_ZH.md) - -## Feature - -- Load multiple data sources(`[]byte`, file and `io.ReadCloser`) with overwrites. -- Read with recursion values. -- Read with parent-child sections. -- Read with auto-increment key names. -- Read with multiple-line values. -- Read with tons of helper methods. -- Read and convert values to Go types. -- Read and **WRITE** comments of sections and keys. -- Manipulate sections, keys and comments with ease. -- Keep sections and keys in order as you parse and save. - -## Installation - -To use a tagged revision: - - go get gopkg.in/ini.v1 - -To use with latest changes: - - go get github.com/go-ini/ini - -Please add `-u` flag to update in the future. - -### Testing - -If you want to test on your machine, please apply `-t` flag: - - go get -t gopkg.in/ini.v1 - -Please add `-u` flag to update in the future. - -## Getting Started - -### Loading from data sources - -A **Data Source** is either raw data in type `[]byte`, a file name with type `string` or `io.ReadCloser`. You can load **as many data sources as you want**. Passing other types will simply return an error. - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -Or start with an empty object: - -```go -cfg := ini.Empty() -``` - -When you cannot decide how many data sources to load at the beginning, you will still be able to **Append()** them later. - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use `LooseLoad` to ignore nonexistent files without returning error. - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -The cool thing is, whenever the file is available to load while you're calling `Reload` method, it will be counted as usual. - -#### Ignore cases of key name - -When you do not care about cases of section and key names, you can use `InsensitiveLoad` to force all names to be lowercased while parsing. - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 and sec2 are the exactly same section object -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 and key2 are the exactly same key object -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### MySQL-like boolean key - -MySQL's configuration allows a key without value as follows: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options: - -```go -cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -The value of those keys are always `true`, and when you save to a file, it will keep in the same foramt as you read. - -To generate such keys in your program, you could use `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### Comment - -Take care that following format will be treated as comment: - -1. Line begins with `#` or `;` -2. Words after `#` or `;` -3. Words after section name (i.e words after `[some section name]`) - -If you want to save a value with `#` or `;`, please quote them with ``` ` ``` or ``` """ ```. - -Alternatively, you can use following `LoadOptions` to completely ignore inline comments: - -```go -cfg, err := LoadSources(LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### Working with sections - -To get a section, you would need to: - -```go -section, err := cfg.GetSection("section name") -``` - -For a shortcut for default section, just give an empty string as name: - -```go -section, err := cfg.GetSection("") -``` - -When you're pretty sure the section exists, following code could make your life easier: - -```go -section := cfg.Section("section name") -``` - -What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you. - -To create a new section: - -```go -err := cfg.NewSection("new section") -``` - -To get a list of sections or section names: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### Working with keys - -To get a key under a section: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -Same rule applies to key operations: - -```go -key := cfg.Section("").Key("key name") -``` - -To check if a key exists: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -To create a new key: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -To get a list of keys or key names: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -To get a clone hash of keys and corresponding values: - -```go -hash := cfg.Section("").KeysHash() -``` - -### Working with values - -To get a string value: - -```go -val := cfg.Section("").Key("key name").String() -``` - -To validate key value on the fly: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -To check if raw value exists: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -To get value with types: - -```go -// For boolean values: -// true when value is: 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false when value is: 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// Methods start with Must also accept one argument for default value -// when key not found or fail to parse value to given type. -// Except method MustString, which you have to pass a default value. - -v = cfg.Section("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -What if my value is three-line long? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -Not a problem! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -That's cool, how about continuation lines? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -Piece of cake! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -Well, I hate continuation lines, how do I disable that? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -Holy crap! - -Note that single quotes around values will be stripped: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -That's all? Hmm, no. - -#### Helper methods of working with values - -To get value with given candidates: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates. - -To validate value in a given range: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### Auto-split values into a slice - -To use zero value of type for invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -To exclude invalid values out of result slice: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -Or to return nothing but error when have invalid inputs: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### Save your configuration - -Finally, it's time to save your configuration to somewhere. - -A typical way to save configuration is writing it to a file: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -Another way to save is writing to a `io.Writer` interface: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -By default, spaces are used to align "=" sign between key and values, to disable that: - -```go -ini.PrettyFormat = false -``` - -## Advanced Usage - -### Recursive Values - -For all value of keys, there is a special syntax `%()s`, where `` is the key name in same section or default section, and `%()s` will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions. - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### Parent-child Sections - -You can use `.` in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section. - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### Retrieve parent keys available to a child section - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### Unparseable Sections - -Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use `LoadOptions.UnparsableSections`: - -```go -cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### Auto-increment Key Names - -If key name is `-` in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter. - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### Map To Struct - -Want more objective way to play with INI? Cool. - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // Things can be simpler. - err = ini.MapTo(p, "path/to/ini") - // ... - - // Just map a section? Fine. - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -Can I have default value for field? Absolutely. - -Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type. - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -It's really cool, but what's the point if you can't give me my file back from struct? - -### Reflect From Struct - -Why not? - -```go -type Embeded struct { - Dates []time.Time `delim:"|"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int - GPA float64 - NeverMind string `ini:"-"` - *Embeded -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -So, what do I get? - -```ini -NAME = Unknwon -Male = true -Age = 21 -GPA = 2.8 - -[Embeded] -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### Name Mapper - -To save your time and make your code cleaner, this library supports [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) between struct field and actual section and key name. - -There are 2 built-in name mappers: - -- `AllCapsUnderscore`: it converts to format `ALL_CAPS_UNDERSCORE` then match section or key. -- `TitleUnderscore`: it converts to format `title_underscore` then match section or key. - -To use them: - -```go -type Info struct { - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -Same rules of name mapper apply to `ini.ReflectFromWithMapper` function. - -#### Value Mapper - -To expand values (e.g. from environment variables), you can use the `ValueMapper` to transform values: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -This would set the value of `env.Foo` to the value of the environment variable `MY_VAR`. - -#### Other Notes On Map/Reflect - -Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome. - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -Example configuration: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## Getting Help - -- [API Documentation](https://gowalker.org/gopkg.in/ini.v1) -- [File An Issue](https://github.com/go-ini/ini/issues/new) - -## FAQs - -### What does `BlockMode` field do? - -By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set `cfg.BlockMode = false` to speed up read operations about **50-70%** faster. - -### Why another INI library? - -Many people are using my another INI library [goconfig](https://github.com/Unknwon/goconfig), so the reason for this one is I would like to make more Go style code. Also when you set `cfg.BlockMode = false`, this one is about **10-30%** faster. - -To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using `gopkg.in` to version my package at this time.(PS: shorter import path) - -## License - -This project is under Apache v2 License. See the [LICENSE](LICENSE) file for the full license text. diff --git a/vendor/github.com/go-ini/ini/README_ZH.md b/vendor/github.com/go-ini/ini/README_ZH.md deleted file mode 100644 index 0cf4194492..0000000000 --- a/vendor/github.com/go-ini/ini/README_ZH.md +++ /dev/null @@ -1,733 +0,0 @@ -本包提供了 Go 语言中读写 INI 文件的功能。 - -## 功能特性 - -- 支持覆盖加载多个数据源(`[]byte`、文件和 `io.ReadCloser`) -- 支持递归读取键值 -- 支持读取父子分区 -- 支持读取自增键名 -- 支持读取多行的键值 -- 支持大量辅助方法 -- 支持在读取时直接转换为 Go 语言类型 -- 支持读取和 **写入** 分区和键的注释 -- 轻松操作分区、键值和注释 -- 在保存文件时分区和键值会保持原有的顺序 - -## 下载安装 - -使用一个特定版本: - - go get gopkg.in/ini.v1 - -使用最新版: - - go get github.com/go-ini/ini - -如需更新请添加 `-u` 选项。 - -### 测试安装 - -如果您想要在自己的机器上运行测试,请使用 `-t` 标记: - - go get -t gopkg.in/ini.v1 - -如需更新请添加 `-u` 选项。 - -## 开始使用 - -### 从数据源加载 - -一个 **数据源** 可以是 `[]byte` 类型的原始数据,`string` 类型的文件路径或 `io.ReadCloser`。您可以加载 **任意多个** 数据源。如果您传递其它类型的数据源,则会直接返回错误。 - -```go -cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data")))) -``` - -或者从一个空白的文件开始: - -```go -cfg := ini.Empty() -``` - -当您在一开始无法决定需要加载哪些数据源时,仍可以使用 **Append()** 在需要的时候加载它们。 - -```go -err := cfg.Append("other file", []byte("other raw data")) -``` - -当您想要加载一系列文件,但是不能够确定其中哪些文件是不存在的,可以通过调用函数 `LooseLoad` 来忽略它们(`Load` 会因为文件不存在而返回错误): - -```go -cfg, err := ini.LooseLoad("filename", "filename_404") -``` - -更牛逼的是,当那些之前不存在的文件在重新调用 `Reload` 方法的时候突然出现了,那么它们会被正常加载。 - -#### 忽略键名的大小写 - -有时候分区和键的名称大小写混合非常烦人,这个时候就可以通过 `InsensitiveLoad` 将所有分区和键名在读取里强制转换为小写: - -```go -cfg, err := ini.InsensitiveLoad("filename") -//... - -// sec1 和 sec2 指向同一个分区对象 -sec1, err := cfg.GetSection("Section") -sec2, err := cfg.GetSection("SecTIOn") - -// key1 和 key2 指向同一个键对象 -key1, err := sec1.GetKey("Key") -key2, err := sec2.GetKey("KeY") -``` - -#### 类似 MySQL 配置中的布尔值键 - -MySQL 的配置文件中会出现没有具体值的布尔类型的键: - -```ini -[mysqld] -... -skip-host-cache -skip-name-resolve -``` - -默认情况下这被认为是缺失值而无法完成解析,但可以通过高级的加载选项对它们进行处理: - -```go -cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf")) -``` - -这些键的值永远为 `true`,且在保存到文件时也只会输出键名。 - -如果您想要通过程序来生成此类键,则可以使用 `NewBooleanKey`: - -```go -key, err := sec.NewBooleanKey("skip-host-cache") -``` - -#### 关于注释 - -下述几种情况的内容将被视为注释: - -1. 所有以 `#` 或 `;` 开头的行 -2. 所有在 `#` 或 `;` 之后的内容 -3. 分区标签后的文字 (即 `[分区名]` 之后的内容) - -如果你希望使用包含 `#` 或 `;` 的值,请使用 ``` ` ``` 或 ``` """ ``` 进行包覆。 - -除此之外,您还可以通过 `LoadOptions` 完全忽略行内注释: - -```go -cfg, err := LoadSources(LoadOptions{IgnoreInlineComment: true}, "app.ini")) -``` - -### 操作分区(Section) - -获取指定分区: - -```go -section, err := cfg.GetSection("section name") -``` - -如果您想要获取默认分区,则可以用空字符串代替分区名: - -```go -section, err := cfg.GetSection("") -``` - -当您非常确定某个分区是存在的,可以使用以下简便方法: - -```go -section := cfg.Section("section name") -``` - -如果不小心判断错了,要获取的分区其实是不存在的,那会发生什么呢?没事的,它会自动创建并返回一个对应的分区对象给您。 - -创建一个分区: - -```go -err := cfg.NewSection("new section") -``` - -获取所有分区对象或名称: - -```go -sections := cfg.Sections() -names := cfg.SectionStrings() -``` - -### 操作键(Key) - -获取某个分区下的键: - -```go -key, err := cfg.Section("").GetKey("key name") -``` - -和分区一样,您也可以直接获取键而忽略错误处理: - -```go -key := cfg.Section("").Key("key name") -``` - -判断某个键是否存在: - -```go -yes := cfg.Section("").HasKey("key name") -``` - -创建一个新的键: - -```go -err := cfg.Section("").NewKey("name", "value") -``` - -获取分区下的所有键或键名: - -```go -keys := cfg.Section("").Keys() -names := cfg.Section("").KeyStrings() -``` - -获取分区下的所有键值对的克隆: - -```go -hash := cfg.Section("").KeysHash() -``` - -### 操作键值(Value) - -获取一个类型为字符串(string)的值: - -```go -val := cfg.Section("").Key("key name").String() -``` - -获取值的同时通过自定义函数进行处理验证: - -```go -val := cfg.Section("").Key("key name").Validate(func(in string) string { - if len(in) == 0 { - return "default" - } - return in -}) -``` - -如果您不需要任何对值的自动转变功能(例如递归读取),可以直接获取原值(这种方式性能最佳): - -```go -val := cfg.Section("").Key("key name").Value() -``` - -判断某个原值是否存在: - -```go -yes := cfg.Section("").HasValue("test value") -``` - -获取其它类型的值: - -```go -// 布尔值的规则: -// true 当值为:1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On -// false 当值为:0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off -v, err = cfg.Section("").Key("BOOL").Bool() -v, err = cfg.Section("").Key("FLOAT64").Float64() -v, err = cfg.Section("").Key("INT").Int() -v, err = cfg.Section("").Key("INT64").Int64() -v, err = cfg.Section("").Key("UINT").Uint() -v, err = cfg.Section("").Key("UINT64").Uint64() -v, err = cfg.Section("").Key("TIME").TimeFormat(time.RFC3339) -v, err = cfg.Section("").Key("TIME").Time() // RFC3339 - -v = cfg.Section("").Key("BOOL").MustBool() -v = cfg.Section("").Key("FLOAT64").MustFloat64() -v = cfg.Section("").Key("INT").MustInt() -v = cfg.Section("").Key("INT64").MustInt64() -v = cfg.Section("").Key("UINT").MustUint() -v = cfg.Section("").Key("UINT64").MustUint64() -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339) -v = cfg.Section("").Key("TIME").MustTime() // RFC3339 - -// 由 Must 开头的方法名允许接收一个相同类型的参数来作为默认值, -// 当键不存在或者转换失败时,则会直接返回该默认值。 -// 但是,MustString 方法必须传递一个默认值。 - -v = cfg.Seciont("").Key("String").MustString("default") -v = cfg.Section("").Key("BOOL").MustBool(true) -v = cfg.Section("").Key("FLOAT64").MustFloat64(1.25) -v = cfg.Section("").Key("INT").MustInt(10) -v = cfg.Section("").Key("INT64").MustInt64(99) -v = cfg.Section("").Key("UINT").MustUint(3) -v = cfg.Section("").Key("UINT64").MustUint64(6) -v = cfg.Section("").Key("TIME").MustTimeFormat(time.RFC3339, time.Now()) -v = cfg.Section("").Key("TIME").MustTime(time.Now()) // RFC3339 -``` - -如果我的值有好多行怎么办? - -```ini -[advance] -ADDRESS = """404 road, -NotFound, State, 5000 -Earth""" -``` - -嗯哼?小 case! - -```go -cfg.Section("advance").Key("ADDRESS").String() - -/* --- start --- -404 road, -NotFound, State, 5000 -Earth ------- end --- */ -``` - -赞爆了!那要是我属于一行的内容写不下想要写到第二行怎么办? - -```ini -[advance] -two_lines = how about \ - continuation lines? -lots_of_lines = 1 \ - 2 \ - 3 \ - 4 -``` - -简直是小菜一碟! - -```go -cfg.Section("advance").Key("two_lines").String() // how about continuation lines? -cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4 -``` - -可是我有时候觉得两行连在一起特别没劲,怎么才能不自动连接两行呢? - -```go -cfg, err := ini.LoadSources(ini.LoadOptions{ - IgnoreContinuation: true, -}, "filename") -``` - -哇靠给力啊! - -需要注意的是,值两侧的单引号会被自动剔除: - -```ini -foo = "some value" // foo: some value -bar = 'some value' // bar: some value -``` - -这就是全部了?哈哈,当然不是。 - -#### 操作键值的辅助方法 - -获取键值时设定候选值: - -```go -v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"}) -v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75}) -v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30}) -v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30}) -v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9}) -v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9}) -v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3}) -v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339 -``` - -如果获取到的值不是候选值的任意一个,则会返回默认值,而默认值不需要是候选值中的一员。 - -验证获取的值是否在指定范围内: - -```go -vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2) -vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20) -vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20) -vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9) -vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9) -vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime) -vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339 -``` - -##### 自动分割键值到切片(slice) - -当存在无效输入时,使用零值代替: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0] -vals = cfg.Section("").Key("STRINGS").Strings(",") -vals = cfg.Section("").Key("FLOAT64S").Float64s(",") -vals = cfg.Section("").Key("INTS").Ints(",") -vals = cfg.Section("").Key("INT64S").Int64s(",") -vals = cfg.Section("").Key("UINTS").Uints(",") -vals = cfg.Section("").Key("UINT64S").Uint64s(",") -vals = cfg.Section("").Key("TIMES").Times(",") -``` - -从结果切片中剔除无效输入: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> [2.2] -vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",") -vals = cfg.Section("").Key("INTS").ValidInts(",") -vals = cfg.Section("").Key("INT64S").ValidInt64s(",") -vals = cfg.Section("").Key("UINTS").ValidUints(",") -vals = cfg.Section("").Key("UINT64S").ValidUint64s(",") -vals = cfg.Section("").Key("TIMES").ValidTimes(",") -``` - -当存在无效输入时,直接返回错误: - -```go -// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4] -// Input: how, 2.2, are, you -> error -vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",") -vals = cfg.Section("").Key("INTS").StrictInts(",") -vals = cfg.Section("").Key("INT64S").StrictInt64s(",") -vals = cfg.Section("").Key("UINTS").StrictUints(",") -vals = cfg.Section("").Key("UINT64S").StrictUint64s(",") -vals = cfg.Section("").Key("TIMES").StrictTimes(",") -``` - -### 保存配置 - -终于到了这个时刻,是时候保存一下配置了。 - -比较原始的做法是输出配置到某个文件: - -```go -// ... -err = cfg.SaveTo("my.ini") -err = cfg.SaveToIndent("my.ini", "\t") -``` - -另一个比较高级的做法是写入到任何实现 `io.Writer` 接口的对象中: - -```go -// ... -cfg.WriteTo(writer) -cfg.WriteToIndent(writer, "\t") -``` - -默认情况下,空格将被用于对齐键值之间的等号以美化输出结果,以下代码可以禁用该功能: - -```go -ini.PrettyFormat = false -``` - -## 高级用法 - -### 递归读取键值 - -在获取所有键值的过程中,特殊语法 `%()s` 会被应用,其中 `` 可以是相同分区或者默认分区下的键名。字符串 `%()s` 会被相应的键值所替代,如果指定的键不存在,则会用空字符串替代。您可以最多使用 99 层的递归嵌套。 - -```ini -NAME = ini - -[author] -NAME = Unknwon -GITHUB = https://github.com/%(NAME)s - -[package] -FULL_NAME = github.com/go-ini/%(NAME)s -``` - -```go -cfg.Section("author").Key("GITHUB").String() // https://github.com/Unknwon -cfg.Section("package").Key("FULL_NAME").String() // github.com/go-ini/ini -``` - -### 读取父子分区 - -您可以在分区名称中使用 `.` 来表示两个或多个分区之间的父子关系。如果某个键在子分区中不存在,则会去它的父分区中再次寻找,直到没有父分区为止。 - -```ini -NAME = ini -VERSION = v1 -IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s - -[package] -CLONE_URL = https://%(IMPORT_PATH)s - -[package.sub] -``` - -```go -cfg.Section("package.sub").Key("CLONE_URL").String() // https://gopkg.in/ini.v1 -``` - -#### 获取上级父分区下的所有键名 - -```go -cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"] -``` - -### 无法解析的分区 - -如果遇到一些比较特殊的分区,它们不包含常见的键值对,而是没有固定格式的纯文本,则可以使用 `LoadOptions.UnparsableSections` 进行处理: - -```go -cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS] -<1> This slide has the fuel listed in the wrong units `)) - -body := cfg.Section("COMMENTS").Body() - -/* --- start --- -<1> This slide has the fuel listed in the wrong units ------- end --- */ -``` - -### 读取自增键名 - -如果数据源中的键名为 `-`,则认为该键使用了自增键名的特殊语法。计数器从 1 开始,并且分区之间是相互独立的。 - -```ini -[features] --: Support read/write comments of keys and sections --: Support auto-increment of key names --: Support load multiple files to overwrite key values -``` - -```go -cfg.Section("features").KeyStrings() // []{"#1", "#2", "#3"} -``` - -### 映射到结构 - -想要使用更加面向对象的方式玩转 INI 吗?好主意。 - -```ini -Name = Unknwon -age = 21 -Male = true -Born = 1993-01-01T20:17:05Z - -[Note] -Content = Hi is a good man! -Cities = HangZhou, Boston -``` - -```go -type Note struct { - Content string - Cities []string -} - -type Person struct { - Name string - Age int `ini:"age"` - Male bool - Born time.Time - Note - Created time.Time `ini:"-"` -} - -func main() { - cfg, err := ini.Load("path/to/ini") - // ... - p := new(Person) - err = cfg.MapTo(p) - // ... - - // 一切竟可以如此的简单。 - err = ini.MapTo(p, "path/to/ini") - // ... - - // 嗯哼?只需要映射一个分区吗? - n := new(Note) - err = cfg.Section("Note").MapTo(n) - // ... -} -``` - -结构的字段怎么设置默认值呢?很简单,只要在映射之前对指定字段进行赋值就可以了。如果键未找到或者类型错误,该值不会发生改变。 - -```go -// ... -p := &Person{ - Name: "Joe", -} -// ... -``` - -这样玩 INI 真的好酷啊!然而,如果不能还给我原来的配置文件,有什么卵用? - -### 从结构反射 - -可是,我有说不能吗? - -```go -type Embeded struct { - Dates []time.Time `delim:"|"` - Places []string `ini:"places,omitempty"` - None []int `ini:",omitempty"` -} - -type Author struct { - Name string `ini:"NAME"` - Male bool - Age int - GPA float64 - NeverMind string `ini:"-"` - *Embeded -} - -func main() { - a := &Author{"Unknwon", true, 21, 2.8, "", - &Embeded{ - []time.Time{time.Now(), time.Now()}, - []string{"HangZhou", "Boston"}, - []int{}, - }} - cfg := ini.Empty() - err = ini.ReflectFrom(cfg, a) - // ... -} -``` - -瞧瞧,奇迹发生了。 - -```ini -NAME = Unknwon -Male = true -Age = 21 -GPA = 2.8 - -[Embeded] -Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00 -places = HangZhou,Boston -``` - -#### 名称映射器(Name Mapper) - -为了节省您的时间并简化代码,本库支持类型为 [`NameMapper`](https://gowalker.org/gopkg.in/ini.v1#NameMapper) 的名称映射器,该映射器负责结构字段名与分区名和键名之间的映射。 - -目前有 2 款内置的映射器: - -- `AllCapsUnderscore`:该映射器将字段名转换至格式 `ALL_CAPS_UNDERSCORE` 后再去匹配分区名和键名。 -- `TitleUnderscore`:该映射器将字段名转换至格式 `title_underscore` 后再去匹配分区名和键名。 - -使用方法: - -```go -type Info struct{ - PackageName string -} - -func main() { - err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini")) - // ... - - cfg, err := ini.Load([]byte("PACKAGE_NAME=ini")) - // ... - info := new(Info) - cfg.NameMapper = ini.AllCapsUnderscore - err = cfg.MapTo(info) - // ... -} -``` - -使用函数 `ini.ReflectFromWithMapper` 时也可应用相同的规则。 - -#### 值映射器(Value Mapper) - -值映射器允许使用一个自定义函数自动展开值的具体内容,例如:运行时获取环境变量: - -```go -type Env struct { - Foo string `ini:"foo"` -} - -func main() { - cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n") - cfg.ValueMapper = os.ExpandEnv - // ... - env := &Env{} - err = cfg.Section("env").MapTo(env) -} -``` - -本例中,`env.Foo` 将会是运行时所获取到环境变量 `MY_VAR` 的值。 - -#### 映射/反射的其它说明 - -任何嵌入的结构都会被默认认作一个不同的分区,并且不会自动产生所谓的父子分区关联: - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon - -[Child] -Age = 21 -``` - -很好,但是,我就是要嵌入结构也在同一个分区。好吧,你爹是李刚! - -```go -type Child struct { - Age string -} - -type Parent struct { - Name string - Child `ini:"Parent"` -} - -type Config struct { - City string - Parent -} -``` - -示例配置文件: - -```ini -City = Boston - -[Parent] -Name = Unknwon -Age = 21 -``` - -## 获取帮助 - -- [API 文档](https://gowalker.org/gopkg.in/ini.v1) -- [创建工单](https://github.com/go-ini/ini/issues/new) - -## 常见问题 - -### 字段 `BlockMode` 是什么? - -默认情况下,本库会在您进行读写操作时采用锁机制来确保数据时间。但在某些情况下,您非常确定只进行读操作。此时,您可以通过设置 `cfg.BlockMode = false` 来将读操作提升大约 **50-70%** 的性能。 - -### 为什么要写另一个 INI 解析库? - -许多人都在使用我的 [goconfig](https://github.com/Unknwon/goconfig) 来完成对 INI 文件的操作,但我希望使用更加 Go 风格的代码。并且当您设置 `cfg.BlockMode = false` 时,会有大约 **10-30%** 的性能提升。 - -为了做出这些改变,我必须对 API 进行破坏,所以新开一个仓库是最安全的做法。除此之外,本库直接使用 `gopkg.in` 来进行版本化发布。(其实真相是导入路径更短了) diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go deleted file mode 100644 index 80afe74315..0000000000 --- a/vendor/github.com/go-ini/ini/error.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 Unknwon -// -// 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 ini - -import ( - "fmt" -) - -type ErrDelimiterNotFound struct { - Line string -} - -func IsErrDelimiterNotFound(err error) bool { - _, ok := err.(ErrDelimiterNotFound) - return ok -} - -func (err ErrDelimiterNotFound) Error() string { - return fmt.Sprintf("key-value delimiter not found: %s", err.Line) -} diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go deleted file mode 100644 index f8827ddd2b..0000000000 --- a/vendor/github.com/go-ini/ini/ini.go +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright 2014 Unknwon -// -// 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 ini provides INI file read and write functionality in Go. -package ini - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "time" -) - -const ( - // Name for default section. You can use this constant or the string literal. - // In most of cases, an empty string is all you need to access the section. - DEFAULT_SECTION = "DEFAULT" - - // Maximum allowed depth when recursively substituing variable names. - _DEPTH_VALUES = 99 - _VERSION = "1.28.1" -) - -// Version returns current package version literal. -func Version() string { - return _VERSION -} - -var ( - // Delimiter to determine or compose a new line. - // This variable will be changed to "\r\n" automatically on Windows - // at package init time. - LineBreak = "\n" - - // Variable regexp pattern: %(variable)s - varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`) - - // Indicate whether to align "=" sign with spaces to produce pretty output - // or reduce all possible spaces for compact format. - PrettyFormat = true - - // Explicitly write DEFAULT section header - DefaultHeader = false - - // Indicate whether to put a line between sections - PrettySection = true -) - -func init() { - if runtime.GOOS == "windows" { - LineBreak = "\r\n" - } -} - -func inSlice(str string, s []string) bool { - for _, v := range s { - if str == v { - return true - } - } - return false -} - -// dataSource is an interface that returns object which can be read and closed. -type dataSource interface { - ReadCloser() (io.ReadCloser, error) -} - -// sourceFile represents an object that contains content on the local file system. -type sourceFile struct { - name string -} - -func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) { - return os.Open(s.name) -} - -type bytesReadCloser struct { - reader io.Reader -} - -func (rc *bytesReadCloser) Read(p []byte) (n int, err error) { - return rc.reader.Read(p) -} - -func (rc *bytesReadCloser) Close() error { - return nil -} - -// sourceData represents an object that contains content in memory. -type sourceData struct { - data []byte -} - -func (s *sourceData) ReadCloser() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(s.data)), nil -} - -// sourceReadCloser represents an input stream with Close method. -type sourceReadCloser struct { - reader io.ReadCloser -} - -func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { - return s.reader, nil -} - -// File represents a combination of a or more INI file(s) in memory. -type File struct { - // Should make things safe, but sometimes doesn't matter. - BlockMode bool - // Make sure data is safe in multiple goroutines. - lock sync.RWMutex - - // Allow combination of multiple data sources. - dataSources []dataSource - // Actual data is stored here. - sections map[string]*Section - - // To keep data in order. - sectionList []string - - options LoadOptions - - NameMapper - ValueMapper -} - -// newFile initializes File object with given data sources. -func newFile(dataSources []dataSource, opts LoadOptions) *File { - return &File{ - BlockMode: true, - dataSources: dataSources, - sections: make(map[string]*Section), - sectionList: make([]string, 0, 10), - options: opts, - } -} - -func parseDataSource(source interface{}) (dataSource, error) { - switch s := source.(type) { - case string: - return sourceFile{s}, nil - case []byte: - return &sourceData{s}, nil - case io.ReadCloser: - return &sourceReadCloser{s}, nil - default: - return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s) - } -} - -type LoadOptions struct { - // Loose indicates whether the parser should ignore nonexistent files or return error. - Loose bool - // Insensitive indicates whether the parser forces all section and key names to lowercase. - Insensitive bool - // IgnoreContinuation indicates whether to ignore continuation lines while parsing. - IgnoreContinuation bool - // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value. - IgnoreInlineComment bool - // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing. - // This type of keys are mostly used in my.cnf. - AllowBooleanKeys bool - // AllowShadows indicates whether to keep track of keys with same name under same section. - AllowShadows bool - // Some INI formats allow group blocks that store a block of raw content that doesn't otherwise - // conform to key/value pairs. Specify the names of those blocks here. - UnparseableSections []string -} - -func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) { - sources := make([]dataSource, len(others)+1) - sources[0], err = parseDataSource(source) - if err != nil { - return nil, err - } - for i := range others { - sources[i+1], err = parseDataSource(others[i]) - if err != nil { - return nil, err - } - } - f := newFile(sources, opts) - if err = f.Reload(); err != nil { - return nil, err - } - return f, nil -} - -// Load loads and parses from INI data sources. -// Arguments can be mixed of file name with string type, or raw data in []byte. -// It will return error if list contains nonexistent files. -func Load(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{}, source, others...) -} - -// LooseLoad has exactly same functionality as Load function -// except it ignores nonexistent files instead of returning error. -func LooseLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Loose: true}, source, others...) -} - -// InsensitiveLoad has exactly same functionality as Load function -// except it forces all section and key names to be lowercased. -func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Insensitive: true}, source, others...) -} - -// InsensitiveLoad has exactly same functionality as Load function -// except it allows have shadow keys. -func ShadowLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{AllowShadows: true}, source, others...) -} - -// Empty returns an empty file object. -func Empty() *File { - // Ignore error here, we sure our data is good. - f, _ := Load([]byte("")) - return f -} - -// NewSection creates a new section. -func (f *File) NewSection(name string) (*Section, error) { - if len(name) == 0 { - return nil, errors.New("error creating new section: empty section name") - } else if f.options.Insensitive && name != DEFAULT_SECTION { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if inSlice(name, f.sectionList) { - return f.sections[name], nil - } - - f.sectionList = append(f.sectionList, name) - f.sections[name] = newSection(f, name) - return f.sections[name], nil -} - -// NewRawSection creates a new section with an unparseable body. -func (f *File) NewRawSection(name, body string) (*Section, error) { - section, err := f.NewSection(name) - if err != nil { - return nil, err - } - - section.isRawSection = true - section.rawBody = body - return section, nil -} - -// NewSections creates a list of sections. -func (f *File) NewSections(names ...string) (err error) { - for _, name := range names { - if _, err = f.NewSection(name); err != nil { - return err - } - } - return nil -} - -// GetSection returns section by given name. -func (f *File) GetSection(name string) (*Section, error) { - if len(name) == 0 { - name = DEFAULT_SECTION - } else if f.options.Insensitive { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sec := f.sections[name] - if sec == nil { - return nil, fmt.Errorf("section '%s' does not exist", name) - } - return sec, nil -} - -// Section assumes named section exists and returns a zero-value when not. -func (f *File) Section(name string) *Section { - sec, err := f.GetSection(name) - if err != nil { - // Note: It's OK here because the only possible error is empty section name, - // but if it's empty, this piece of code won't be executed. - sec, _ = f.NewSection(name) - return sec - } - return sec -} - -// Section returns list of Section. -func (f *File) Sections() []*Section { - sections := make([]*Section, len(f.sectionList)) - for i := range f.sectionList { - sections[i] = f.Section(f.sectionList[i]) - } - return sections -} - -// ChildSections returns a list of child sections of given section name. -func (f *File) ChildSections(name string) []*Section { - return f.Section(name).ChildSections() -} - -// SectionStrings returns list of section names. -func (f *File) SectionStrings() []string { - list := make([]string, len(f.sectionList)) - copy(list, f.sectionList) - return list -} - -// DeleteSection deletes a section. -func (f *File) DeleteSection(name string) { - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if len(name) == 0 { - name = DEFAULT_SECTION - } - - for i, s := range f.sectionList { - if s == name { - f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...) - delete(f.sections, name) - return - } - } -} - -func (f *File) reload(s dataSource) error { - r, err := s.ReadCloser() - if err != nil { - return err - } - defer r.Close() - - return f.parse(r) -} - -// Reload reloads and parses all data sources. -func (f *File) Reload() (err error) { - for _, s := range f.dataSources { - if err = f.reload(s); err != nil { - // In loose mode, we create an empty default section for nonexistent files. - if os.IsNotExist(err) && f.options.Loose { - f.parse(bytes.NewBuffer(nil)) - continue - } - return err - } - } - return nil -} - -// Append appends one or more data sources and reloads automatically. -func (f *File) Append(source interface{}, others ...interface{}) error { - ds, err := parseDataSource(source) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - for _, s := range others { - ds, err = parseDataSource(s) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - } - return f.Reload() -} - -// WriteToIndent writes content into io.Writer with given indention. -// If PrettyFormat has been set to be true, -// it will align "=" sign with spaces under each section. -func (f *File) WriteToIndent(w io.Writer, indent string) (n int64, err error) { - equalSign := "=" - if PrettyFormat { - equalSign = " = " - } - - // Use buffer to make sure target is safe until finish encoding. - buf := bytes.NewBuffer(nil) - for i, sname := range f.sectionList { - sec := f.Section(sname) - if len(sec.Comment) > 0 { - if sec.Comment[0] != '#' && sec.Comment[0] != ';' { - sec.Comment = "; " + sec.Comment - } - if _, err = buf.WriteString(sec.Comment + LineBreak); err != nil { - return 0, err - } - } - - if i > 0 || DefaultHeader { - if _, err = buf.WriteString("[" + sname + "]" + LineBreak); err != nil { - return 0, err - } - } else { - // Write nothing if default section is empty - if len(sec.keyList) == 0 { - continue - } - } - - if sec.isRawSection { - if _, err = buf.WriteString(sec.rawBody); err != nil { - return 0, err - } - continue - } - - // Count and generate alignment length and buffer spaces using the - // longest key. Keys may be modifed if they contain certain characters so - // we need to take that into account in our calculation. - alignLength := 0 - if PrettyFormat { - for _, kname := range sec.keyList { - keyLength := len(kname) - // First case will surround key by ` and second by """ - if strings.ContainsAny(kname, "\"=:") { - keyLength += 2 - } else if strings.Contains(kname, "`") { - keyLength += 6 - } - - if keyLength > alignLength { - alignLength = keyLength - } - } - } - alignSpaces := bytes.Repeat([]byte(" "), alignLength) - - KEY_LIST: - for _, kname := range sec.keyList { - key := sec.Key(kname) - if len(key.Comment) > 0 { - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - if key.Comment[0] != '#' && key.Comment[0] != ';' { - key.Comment = "; " + key.Comment - } - if _, err = buf.WriteString(key.Comment + LineBreak); err != nil { - return 0, err - } - } - - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - switch { - case key.isAutoIncrement: - kname = "-" - case strings.ContainsAny(kname, "\"=:"): - kname = "`" + kname + "`" - case strings.Contains(kname, "`"): - kname = `"""` + kname + `"""` - } - - for _, val := range key.ValueWithShadows() { - if _, err = buf.WriteString(kname); err != nil { - return 0, err - } - - if key.isBooleanType { - if kname != sec.keyList[len(sec.keyList)-1] { - buf.WriteString(LineBreak) - } - continue KEY_LIST - } - - // Write out alignment spaces before "=" sign - if PrettyFormat { - buf.Write(alignSpaces[:alignLength-len(kname)]) - } - - // In case key value contains "\n", "`", "\"", "#" or ";" - if strings.ContainsAny(val, "\n`") { - val = `"""` + val + `"""` - } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") { - val = "`" + val + "`" - } - if _, err = buf.WriteString(equalSign + val + LineBreak); err != nil { - return 0, err - } - } - } - - if PrettySection { - // Put a line between sections - if _, err = buf.WriteString(LineBreak); err != nil { - return 0, err - } - } - } - - return buf.WriteTo(w) -} - -// WriteTo writes file content into io.Writer. -func (f *File) WriteTo(w io.Writer) (int64, error) { - return f.WriteToIndent(w, "") -} - -// SaveToIndent writes content to file system with given value indention. -func (f *File) SaveToIndent(filename, indent string) error { - // Note: Because we are truncating with os.Create, - // so it's safer to save to a temporary file location and rename afte done. - tmpPath := filename + "." + strconv.Itoa(time.Now().Nanosecond()) + ".tmp" - defer os.Remove(tmpPath) - - fw, err := os.Create(tmpPath) - if err != nil { - return err - } - - if _, err = f.WriteToIndent(fw, indent); err != nil { - fw.Close() - return err - } - fw.Close() - - // Remove old file and rename the new one. - os.Remove(filename) - return os.Rename(tmpPath, filename) -} - -// SaveTo writes content to file system. -func (f *File) SaveTo(filename string) error { - return f.SaveToIndent(filename, "") -} diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go deleted file mode 100644 index 838356af01..0000000000 --- a/vendor/github.com/go-ini/ini/key.go +++ /dev/null @@ -1,699 +0,0 @@ -// Copyright 2014 Unknwon -// -// 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 ini - -import ( - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -// Key represents a key under a section. -type Key struct { - s *Section - name string - value string - isAutoIncrement bool - isBooleanType bool - - isShadow bool - shadows []*Key - - Comment string -} - -// newKey simply return a key object with given values. -func newKey(s *Section, name, val string) *Key { - return &Key{ - s: s, - name: name, - value: val, - } -} - -func (k *Key) addShadow(val string) error { - if k.isShadow { - return errors.New("cannot add shadow to another shadow key") - } else if k.isAutoIncrement || k.isBooleanType { - return errors.New("cannot add shadow to auto-increment or boolean key") - } - - shadow := newKey(k.s, k.name, val) - shadow.isShadow = true - k.shadows = append(k.shadows, shadow) - return nil -} - -// AddShadow adds a new shadow key to itself. -func (k *Key) AddShadow(val string) error { - if !k.s.f.options.AllowShadows { - return errors.New("shadow key is not allowed") - } - return k.addShadow(val) -} - -// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv -type ValueMapper func(string) string - -// Name returns name of key. -func (k *Key) Name() string { - return k.name -} - -// Value returns raw value of key for performance purpose. -func (k *Key) Value() string { - return k.value -} - -// ValueWithShadows returns raw values of key and its shadows if any. -func (k *Key) ValueWithShadows() []string { - if len(k.shadows) == 0 { - return []string{k.value} - } - vals := make([]string, len(k.shadows)+1) - vals[0] = k.value - for i := range k.shadows { - vals[i+1] = k.shadows[i].value - } - return vals -} - -// transformValue takes a raw value and transforms to its final string. -func (k *Key) transformValue(val string) string { - if k.s.f.ValueMapper != nil { - val = k.s.f.ValueMapper(val) - } - - // Fail-fast if no indicate char found for recursive value - if !strings.Contains(val, "%") { - return val - } - for i := 0; i < _DEPTH_VALUES; i++ { - vr := varPattern.FindString(val) - if len(vr) == 0 { - break - } - - // Take off leading '%(' and trailing ')s'. - noption := strings.TrimLeft(vr, "%(") - noption = strings.TrimRight(noption, ")s") - - // Search in the same section. - nk, err := k.s.GetKey(noption) - if err != nil { - // Search again in default section. - nk, _ = k.s.f.Section("").GetKey(noption) - } - - // Substitute by new value and take off leading '%(' and trailing ')s'. - val = strings.Replace(val, vr, nk.value, -1) - } - return val -} - -// String returns string representation of value. -func (k *Key) String() string { - return k.transformValue(k.value) -} - -// Validate accepts a validate function which can -// return modifed result as key value. -func (k *Key) Validate(fn func(string) string) string { - return fn(k.String()) -} - -// parseBool returns the boolean value represented by the string. -// -// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, -// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. -// Any other value returns an error. -func parseBool(str string) (value bool, err error) { - switch str { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": - return false, nil - } - return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) -} - -// Bool returns bool type value. -func (k *Key) Bool() (bool, error) { - return parseBool(k.String()) -} - -// Float64 returns float64 type value. -func (k *Key) Float64() (float64, error) { - return strconv.ParseFloat(k.String(), 64) -} - -// Int returns int type value. -func (k *Key) Int() (int, error) { - return strconv.Atoi(k.String()) -} - -// Int64 returns int64 type value. -func (k *Key) Int64() (int64, error) { - return strconv.ParseInt(k.String(), 10, 64) -} - -// Uint returns uint type valued. -func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 10, 64) - return uint(u), e -} - -// Uint64 returns uint64 type value. -func (k *Key) Uint64() (uint64, error) { - return strconv.ParseUint(k.String(), 10, 64) -} - -// Duration returns time.Duration type value. -func (k *Key) Duration() (time.Duration, error) { - return time.ParseDuration(k.String()) -} - -// TimeFormat parses with given format and returns time.Time type value. -func (k *Key) TimeFormat(format string) (time.Time, error) { - return time.Parse(format, k.String()) -} - -// Time parses with RFC3339 format and returns time.Time type value. -func (k *Key) Time() (time.Time, error) { - return k.TimeFormat(time.RFC3339) -} - -// MustString returns default value if key value is empty. -func (k *Key) MustString(defaultVal string) string { - val := k.String() - if len(val) == 0 { - k.value = defaultVal - return defaultVal - } - return val -} - -// MustBool always returns value without error, -// it returns false if error occurs. -func (k *Key) MustBool(defaultVal ...bool) bool { - val, err := k.Bool() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatBool(defaultVal[0]) - return defaultVal[0] - } - return val -} - -// MustFloat64 always returns value without error, -// it returns 0.0 if error occurs. -func (k *Key) MustFloat64(defaultVal ...float64) float64 { - val, err := k.Float64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) - return defaultVal[0] - } - return val -} - -// MustInt always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt(defaultVal ...int) int { - val, err := k.Int() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(int64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustInt64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt64(defaultVal ...int64) int64 { - val, err := k.Int64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustUint always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint(defaultVal ...uint) uint { - val, err := k.Uint() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustUint64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint64(defaultVal ...uint64) uint64 { - val, err := k.Uint64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustDuration always returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { - val, err := k.Duration() - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].String() - return defaultVal[0] - } - return val -} - -// MustTimeFormat always parses with given format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { - val, err := k.TimeFormat(format) - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].Format(format) - return defaultVal[0] - } - return val -} - -// MustTime always parses with RFC3339 format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTime(defaultVal ...time.Time) time.Time { - return k.MustTimeFormat(time.RFC3339, defaultVal...) -} - -// In always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) In(defaultVal string, candidates []string) string { - val := k.String() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InFloat64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { - val := k.MustFloat64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt(defaultVal int, candidates []int) int { - val := k.MustInt() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { - val := k.MustInt64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint(defaultVal uint, candidates []uint) uint { - val := k.MustUint() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { - val := k.MustUint64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTimeFormat always parses with given format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { - val := k.MustTimeFormat(format) - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTime always parses with RFC3339 format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { - return k.InTimeFormat(time.RFC3339, defaultVal, candidates) -} - -// RangeFloat64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { - val := k.MustFloat64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt(defaultVal, min, max int) int { - val := k.MustInt() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { - val := k.MustInt64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeTimeFormat checks if value with given format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { - val := k.MustTimeFormat(format) - if val.Unix() < min.Unix() || val.Unix() > max.Unix() { - return defaultVal - } - return val -} - -// RangeTime checks if value with RFC3339 format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { - return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) -} - -// Strings returns list of string divided by given delimiter. -func (k *Key) Strings(delim string) []string { - str := k.String() - if len(str) == 0 { - return []string{} - } - - vals := strings.Split(str, delim) - for i := range vals { - // vals[i] = k.transformValue(strings.TrimSpace(vals[i])) - vals[i] = strings.TrimSpace(vals[i]) - } - return vals -} - -// StringsWithShadows returns list of string divided by given delimiter. -// Shadows will also be appended if any. -func (k *Key) StringsWithShadows(delim string) []string { - vals := k.ValueWithShadows() - results := make([]string, 0, len(vals)*2) - for i := range vals { - if len(vals) == 0 { - continue - } - - results = append(results, strings.Split(vals[i], delim)...) - } - - for i := range results { - results[i] = k.transformValue(strings.TrimSpace(results[i])) - } - return results -} - -// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Float64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), true, false) - return vals -} - -// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Ints(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), true, false) - return vals -} - -// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Int64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), true, false) - return vals -} - -// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), true, false) - return vals -} - -// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), true, false) - return vals -} - -// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) TimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false) - return vals -} - -// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) Times(delim string) []time.Time { - return k.TimesFormat(time.RFC3339, delim) -} - -// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then -// it will not be included to result list. -func (k *Key) ValidFloat64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), false, false) - return vals -} - -// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will -// not be included to result list. -func (k *Key) ValidInts(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), false, false) - return vals -} - -// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, -// then it will not be included to result list. -func (k *Key) ValidInt64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), false, false) - return vals -} - -// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, -// then it will not be included to result list. -func (k *Key) ValidUints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), false, false) - return vals -} - -// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned -// integer, then it will not be included to result list. -func (k *Key) ValidUint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), false, false) - return vals -} - -// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false) - return vals -} - -// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimes(delim string) []time.Time { - return k.ValidTimesFormat(time.RFC3339, delim) -} - -// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictFloat64s(delim string) ([]float64, error) { - return k.parseFloat64s(k.Strings(delim), false, true) -} - -// StrictInts returns list of int divided by given delimiter or error on first invalid input. -func (k *Key) StrictInts(delim string) ([]int, error) { - return k.parseInts(k.Strings(delim), false, true) -} - -// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictInt64s(delim string) ([]int64, error) { - return k.parseInt64s(k.Strings(delim), false, true) -} - -// StrictUints returns list of uint divided by given delimiter or error on first invalid input. -func (k *Key) StrictUints(delim string) ([]uint, error) { - return k.parseUints(k.Strings(delim), false, true) -} - -// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictUint64s(delim string) ([]uint64, error) { - return k.parseUint64s(k.Strings(delim), false, true) -} - -// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { - return k.parseTimesFormat(format, k.Strings(delim), false, true) -} - -// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimes(delim string) ([]time.Time, error) { - return k.StrictTimesFormat(time.RFC3339, delim) -} - -// parseFloat64s transforms strings to float64s. -func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) { - vals := make([]float64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseFloat(str, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInts transforms strings to ints. -func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) { - vals := make([]int, 0, len(strs)) - for _, str := range strs { - val, err := strconv.Atoi(str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInt64s transforms strings to int64s. -func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) { - vals := make([]int64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseInt(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseUints transforms strings to uints. -func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) { - vals := make([]uint, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 0) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, uint(val)) - } - } - return vals, nil -} - -// parseUint64s transforms strings to uint64s. -func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) { - vals := make([]uint64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 10, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseTimesFormat transforms strings to times in given format. -func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { - vals := make([]time.Time, 0, len(strs)) - for _, str := range strs { - val, err := time.Parse(format, str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// SetValue changes key value. -func (k *Key) SetValue(v string) { - if k.s.f.BlockMode { - k.s.f.lock.Lock() - defer k.s.f.lock.Unlock() - } - - k.value = v - k.s.keysHash[k.name] = v -} diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go deleted file mode 100644 index 69d5476273..0000000000 --- a/vendor/github.com/go-ini/ini/parser.go +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright 2015 Unknwon -// -// 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 ini - -import ( - "bufio" - "bytes" - "fmt" - "io" - "strconv" - "strings" - "unicode" -) - -type tokenType int - -const ( - _TOKEN_INVALID tokenType = iota - _TOKEN_COMMENT - _TOKEN_SECTION - _TOKEN_KEY -) - -type parser struct { - buf *bufio.Reader - isEOF bool - count int - comment *bytes.Buffer -} - -func newParser(r io.Reader) *parser { - return &parser{ - buf: bufio.NewReader(r), - count: 1, - comment: &bytes.Buffer{}, - } -} - -// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. -// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding -func (p *parser) BOM() error { - mask, err := p.buf.Peek(2) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 2 { - return nil - } - - switch { - case mask[0] == 254 && mask[1] == 255: - fallthrough - case mask[0] == 255 && mask[1] == 254: - p.buf.Read(mask) - case mask[0] == 239 && mask[1] == 187: - mask, err := p.buf.Peek(3) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 3 { - return nil - } - if mask[2] == 191 { - p.buf.Read(mask) - } - } - return nil -} - -func (p *parser) readUntil(delim byte) ([]byte, error) { - data, err := p.buf.ReadBytes(delim) - if err != nil { - if err == io.EOF { - p.isEOF = true - } else { - return nil, err - } - } - return data, nil -} - -func cleanComment(in []byte) ([]byte, bool) { - i := bytes.IndexAny(in, "#;") - if i == -1 { - return nil, false - } - return in[i:], true -} - -func readKeyName(in []byte) (string, int, error) { - line := string(in) - - // Check if key name surrounded by quotes. - var keyQuote string - if line[0] == '"' { - if len(line) > 6 && string(line[0:3]) == `"""` { - keyQuote = `"""` - } else { - keyQuote = `"` - } - } else if line[0] == '`' { - keyQuote = "`" - } - - // Get out key name - endIdx := -1 - if len(keyQuote) > 0 { - startIdx := len(keyQuote) - // FIXME: fail case -> """"""name"""=value - pos := strings.Index(line[startIdx:], keyQuote) - if pos == -1 { - return "", -1, fmt.Errorf("missing closing key quote: %s", line) - } - pos += startIdx - - // Find key-value delimiter - i := strings.IndexAny(line[pos+startIdx:], "=:") - if i < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - endIdx = pos + i - return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil - } - - endIdx = strings.IndexAny(line, "=:") - if endIdx < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil -} - -func (p *parser) readMultilines(line, val, valQuote string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := string(data) - - pos := strings.LastIndex(next, valQuote) - if pos > -1 { - val += next[:pos] - - comment, has := cleanComment([]byte(next[pos:])) - if has { - p.comment.Write(bytes.TrimSpace(comment)) - } - break - } - val += next - if p.isEOF { - return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) - } - } - return val, nil -} - -func (p *parser) readContinuationLines(val string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := strings.TrimSpace(string(data)) - - if len(next) == 0 { - break - } - val += next - if val[len(val)-1] != '\\' { - break - } - val = val[:len(val)-1] - } - return val, nil -} - -// hasSurroundedQuote check if and only if the first and last characters -// are quotes \" or \'. -// It returns false if any other parts also contain same kind of quotes. -func hasSurroundedQuote(in string, quote byte) bool { - return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote && - strings.IndexByte(in[1:], quote) == len(in)-2 -} - -func (p *parser) readValue(in []byte, ignoreContinuation, ignoreInlineComment bool) (string, error) { - line := strings.TrimLeftFunc(string(in), unicode.IsSpace) - if len(line) == 0 { - return "", nil - } - - var valQuote string - if len(line) > 3 && string(line[0:3]) == `"""` { - valQuote = `"""` - } else if line[0] == '`' { - valQuote = "`" - } - - if len(valQuote) > 0 { - startIdx := len(valQuote) - pos := strings.LastIndex(line[startIdx:], valQuote) - // Check for multi-line value - if pos == -1 { - return p.readMultilines(line, line[startIdx:], valQuote) - } - - return line[startIdx : pos+startIdx], nil - } - - // Won't be able to reach here if value only contains whitespace - line = strings.TrimSpace(line) - - // Check continuation lines when desired - if !ignoreContinuation && line[len(line)-1] == '\\' { - return p.readContinuationLines(line[:len(line)-1]) - } - - // Check if ignore inline comment - if !ignoreInlineComment { - i := strings.IndexAny(line, "#;") - if i > -1 { - p.comment.WriteString(line[i:]) - line = strings.TrimSpace(line[:i]) - } - } - - // Trim single quotes - if hasSurroundedQuote(line, '\'') || - hasSurroundedQuote(line, '"') { - line = line[1 : len(line)-1] - } - return line, nil -} - -// parse parses data through an io.Reader. -func (f *File) parse(reader io.Reader) (err error) { - p := newParser(reader) - if err = p.BOM(); err != nil { - return fmt.Errorf("BOM: %v", err) - } - - // Ignore error because default section name is never empty string. - section, _ := f.NewSection(DEFAULT_SECTION) - - var line []byte - var inUnparseableSection bool - for !p.isEOF { - line, err = p.readUntil('\n') - if err != nil { - return err - } - - line = bytes.TrimLeftFunc(line, unicode.IsSpace) - if len(line) == 0 { - continue - } - - // Comments - if line[0] == '#' || line[0] == ';' { - // Note: we do not care ending line break, - // it is needed for adding second line, - // so just clean it once at the end when set to value. - p.comment.Write(line) - continue - } - - // Section - if line[0] == '[' { - // Read to the next ']' (TODO: support quoted strings) - // TODO(unknwon): use LastIndexByte when stop supporting Go1.4 - closeIdx := bytes.LastIndex(line, []byte("]")) - if closeIdx == -1 { - return fmt.Errorf("unclosed section: %s", line) - } - - name := string(line[1:closeIdx]) - section, err = f.NewSection(name) - if err != nil { - return err - } - - comment, has := cleanComment(line[closeIdx+1:]) - if has { - p.comment.Write(comment) - } - - section.Comment = strings.TrimSpace(p.comment.String()) - - // Reset aotu-counter and comments - p.comment.Reset() - p.count = 1 - - inUnparseableSection = false - for i := range f.options.UnparseableSections { - if f.options.UnparseableSections[i] == name || - (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { - inUnparseableSection = true - continue - } - } - continue - } - - if inUnparseableSection { - section.isRawSection = true - section.rawBody += string(line) - continue - } - - kname, offset, err := readKeyName(line) - if err != nil { - // Treat as boolean key when desired, and whole line is key name. - if IsErrDelimiterNotFound(err) && f.options.AllowBooleanKeys { - kname, err := p.readValue(line, f.options.IgnoreContinuation, f.options.IgnoreInlineComment) - if err != nil { - return err - } - key, err := section.NewBooleanKey(kname) - if err != nil { - return err - } - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - continue - } - return err - } - - // Auto increment. - isAutoIncr := false - if kname == "-" { - isAutoIncr = true - kname = "#" + strconv.Itoa(p.count) - p.count++ - } - - value, err := p.readValue(line[offset:], f.options.IgnoreContinuation, f.options.IgnoreInlineComment) - if err != nil { - return err - } - - key, err := section.NewKey(kname, value) - if err != nil { - return err - } - key.isAutoIncrement = isAutoIncr - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - } - return nil -} diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go deleted file mode 100644 index 94f7375ed4..0000000000 --- a/vendor/github.com/go-ini/ini/section.go +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright 2014 Unknwon -// -// 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 ini - -import ( - "errors" - "fmt" - "strings" -) - -// Section represents a config section. -type Section struct { - f *File - Comment string - name string - keys map[string]*Key - keyList []string - keysHash map[string]string - - isRawSection bool - rawBody string -} - -func newSection(f *File, name string) *Section { - return &Section{ - f: f, - name: name, - keys: make(map[string]*Key), - keyList: make([]string, 0, 10), - keysHash: make(map[string]string), - } -} - -// Name returns name of Section. -func (s *Section) Name() string { - return s.name -} - -// Body returns rawBody of Section if the section was marked as unparseable. -// It still follows the other rules of the INI format surrounding leading/trailing whitespace. -func (s *Section) Body() string { - return strings.TrimSpace(s.rawBody) -} - -// NewKey creates a new key to given section. -func (s *Section) NewKey(name, val string) (*Key, error) { - if len(name) == 0 { - return nil, errors.New("error creating new key: empty key name") - } else if s.f.options.Insensitive { - name = strings.ToLower(name) - } - - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - if inSlice(name, s.keyList) { - if s.f.options.AllowShadows { - if err := s.keys[name].addShadow(val); err != nil { - return nil, err - } - } else { - s.keys[name].value = val - } - return s.keys[name], nil - } - - s.keyList = append(s.keyList, name) - s.keys[name] = newKey(s, name, val) - s.keysHash[name] = val - return s.keys[name], nil -} - -// NewBooleanKey creates a new boolean type key to given section. -func (s *Section) NewBooleanKey(name string) (*Key, error) { - key, err := s.NewKey(name, "true") - if err != nil { - return nil, err - } - - key.isBooleanType = true - return key, nil -} - -// GetKey returns key in section by given name. -func (s *Section) GetKey(name string) (*Key, error) { - // FIXME: change to section level lock? - if s.f.BlockMode { - s.f.lock.RLock() - } - if s.f.options.Insensitive { - name = strings.ToLower(name) - } - key := s.keys[name] - if s.f.BlockMode { - s.f.lock.RUnlock() - } - - if key == nil { - // Check if it is a child-section. - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - return sec.GetKey(name) - } else { - break - } - } - return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) - } - return key, nil -} - -// HasKey returns true if section contains a key with given name. -func (s *Section) HasKey(name string) bool { - key, _ := s.GetKey(name) - return key != nil -} - -// Haskey is a backwards-compatible name for HasKey. -func (s *Section) Haskey(name string) bool { - return s.HasKey(name) -} - -// HasValue returns true if section contains given raw value. -func (s *Section) HasValue(value string) bool { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - for _, k := range s.keys { - if value == k.value { - return true - } - } - return false -} - -// Key assumes named Key exists in section and returns a zero-value when not. -func (s *Section) Key(name string) *Key { - key, err := s.GetKey(name) - if err != nil { - // It's OK here because the only possible error is empty key name, - // but if it's empty, this piece of code won't be executed. - key, _ = s.NewKey(name, "") - return key - } - return key -} - -// Keys returns list of keys of section. -func (s *Section) Keys() []*Key { - keys := make([]*Key, len(s.keyList)) - for i := range s.keyList { - keys[i] = s.Key(s.keyList[i]) - } - return keys -} - -// ParentKeys returns list of keys of parent section. -func (s *Section) ParentKeys() []*Key { - var parentKeys []*Key - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - parentKeys = append(parentKeys, sec.Keys()...) - } else { - break - } - - } - return parentKeys -} - -// KeyStrings returns list of key names of section. -func (s *Section) KeyStrings() []string { - list := make([]string, len(s.keyList)) - copy(list, s.keyList) - return list -} - -// KeysHash returns keys hash consisting of names and values. -func (s *Section) KeysHash() map[string]string { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - hash := map[string]string{} - for key, value := range s.keysHash { - hash[key] = value - } - return hash -} - -// DeleteKey deletes a key from section. -func (s *Section) DeleteKey(name string) { - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - for i, k := range s.keyList { - if k == name { - s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) - delete(s.keys, name) - return - } - } -} - -// ChildSections returns a list of child sections of current section. -// For example, "[parent.child1]" and "[parent.child12]" are child sections -// of section "[parent]". -func (s *Section) ChildSections() []*Section { - prefix := s.name + "." - children := make([]*Section, 0, 3) - for _, name := range s.f.sectionList { - if strings.HasPrefix(name, prefix) { - children = append(children, s.f.sections[name]) - } - } - return children -} diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go deleted file mode 100644 index eeb8dabaac..0000000000 --- a/vendor/github.com/go-ini/ini/struct.go +++ /dev/null @@ -1,500 +0,0 @@ -// Copyright 2014 Unknwon -// -// 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 ini - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "time" - "unicode" -) - -// NameMapper represents a ini tag name mapper. -type NameMapper func(string) string - -// Built-in name getters. -var ( - // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. - AllCapsUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - } - newstr = append(newstr, unicode.ToUpper(chr)) - } - return string(newstr) - } - // TitleUnderscore converts to format title_underscore. - TitleUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - chr -= ('A' - 'a') - } - newstr = append(newstr, chr) - } - return string(newstr) - } -) - -func (s *Section) parseFieldName(raw, actual string) string { - if len(actual) > 0 { - return actual - } - if s.f.NameMapper != nil { - return s.f.NameMapper(raw) - } - return raw -} - -func parseDelim(actual string) string { - if len(actual) > 0 { - return actual - } - return "," -} - -var reflectTime = reflect.TypeOf(time.Now()).Kind() - -// setSliceWithProperType sets proper values to slice based on its type. -func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - var strs []string - if allowShadow { - strs = key.StringsWithShadows(delim) - } else { - strs = key.Strings(delim) - } - - numVals := len(strs) - if numVals == 0 { - return nil - } - - var vals interface{} - var err error - - sliceOf := field.Type().Elem().Kind() - switch sliceOf { - case reflect.String: - vals = strs - case reflect.Int: - vals, err = key.parseInts(strs, true, false) - case reflect.Int64: - vals, err = key.parseInt64s(strs, true, false) - case reflect.Uint: - vals, err = key.parseUints(strs, true, false) - case reflect.Uint64: - vals, err = key.parseUint64s(strs, true, false) - case reflect.Float64: - vals, err = key.parseFloat64s(strs, true, false) - case reflectTime: - vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - if isStrict { - return err - } - - slice := reflect.MakeSlice(field.Type(), numVals, numVals) - for i := 0; i < numVals; i++ { - switch sliceOf { - case reflect.String: - slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i])) - case reflect.Int: - slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i])) - case reflect.Int64: - slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i])) - case reflect.Uint: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i])) - case reflect.Uint64: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i])) - case reflect.Float64: - slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i])) - case reflectTime: - slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i])) - } - } - field.Set(slice) - return nil -} - -func wrapStrictError(err error, isStrict bool) error { - if isStrict { - return err - } - return nil -} - -// setWithProperType sets proper value to field based on its type, -// but it does not return error for failing parsing, -// because we want to use default value that is already assigned to strcut. -func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - switch t.Kind() { - case reflect.String: - if len(key.String()) == 0 { - return nil - } - field.SetString(key.String()) - case reflect.Bool: - boolVal, err := key.Bool() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetBool(boolVal) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - intVal, err := key.Int64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetInt(intVal) - // byte is an alias for uint8, so supporting uint8 breaks support for byte - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - uintVal, err := key.Uint64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetUint(uintVal) - - case reflect.Float32, reflect.Float64: - floatVal, err := key.Float64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetFloat(floatVal) - case reflectTime: - timeVal, err := key.Time() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.Set(reflect.ValueOf(timeVal)) - case reflect.Slice: - return setSliceWithProperType(key, field, delim, allowShadow, isStrict) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) { - opts := strings.SplitN(tag, ",", 3) - rawName = opts[0] - if len(opts) > 1 { - omitEmpty = opts[1] == "omitempty" - } - if len(opts) > 2 { - allowShadow = opts[2] == "allowshadow" - } - return rawName, omitEmpty, allowShadow -} - -func (s *Section) mapTo(val reflect.Value, isStrict bool) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - rawName, _, allowShadow := parseTagOptions(tag) - fieldName := s.parseFieldName(tpField.Name, rawName) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous - isStruct := tpField.Type.Kind() == reflect.Struct - if isAnonymous { - field.Set(reflect.New(tpField.Type.Elem())) - } - - if isAnonymous || isStruct { - if sec, err := s.f.GetSection(fieldName); err == nil { - if err = sec.mapTo(field, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - continue - } - } - - if key, err := s.GetKey(fieldName); err == nil { - delim := parseDelim(tpField.Tag.Get("delim")) - if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - } - } - return nil -} - -// MapTo maps section to given struct. -func (s *Section) MapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, false) -} - -// MapTo maps section to given struct in strict mode, -// which returns all possible error including value parsing error. -func (s *Section) StrictMapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, true) -} - -// MapTo maps file to given struct. -func (f *File) MapTo(v interface{}) error { - return f.Section("").MapTo(v) -} - -// MapTo maps file to given struct in strict mode, -// which returns all possible error including value parsing error. -func (f *File) StrictMapTo(v interface{}) error { - return f.Section("").StrictMapTo(v) -} - -// MapTo maps data sources to given struct with name mapper. -func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.MapTo(v) -} - -// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode, -// which returns all possible error including value parsing error. -func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.StrictMapTo(v) -} - -// MapTo maps data sources to given struct. -func MapTo(v, source interface{}, others ...interface{}) error { - return MapToWithMapper(v, nil, source, others...) -} - -// StrictMapTo maps data sources to given struct in strict mode, -// which returns all possible error including value parsing error. -func StrictMapTo(v, source interface{}, others ...interface{}) error { - return StrictMapToWithMapper(v, nil, source, others...) -} - -// reflectSliceWithProperType does the opposite thing as setSliceWithProperType. -func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { - slice := field.Slice(0, field.Len()) - if field.Len() == 0 { - return nil - } - - var buf bytes.Buffer - sliceOf := field.Type().Elem().Kind() - for i := 0; i < field.Len(); i++ { - switch sliceOf { - case reflect.String: - buf.WriteString(slice.Index(i).String()) - case reflect.Int, reflect.Int64: - buf.WriteString(fmt.Sprint(slice.Index(i).Int())) - case reflect.Uint, reflect.Uint64: - buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) - case reflect.Float64: - buf.WriteString(fmt.Sprint(slice.Index(i).Float())) - case reflectTime: - buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - buf.WriteString(delim) - } - key.SetValue(buf.String()[:buf.Len()-1]) - return nil -} - -// reflectWithProperType does the opposite thing as setWithProperType. -func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { - switch t.Kind() { - case reflect.String: - key.SetValue(field.String()) - case reflect.Bool: - key.SetValue(fmt.Sprint(field.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - key.SetValue(fmt.Sprint(field.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - key.SetValue(fmt.Sprint(field.Uint())) - case reflect.Float32, reflect.Float64: - key.SetValue(fmt.Sprint(field.Float())) - case reflectTime: - key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) - case reflect.Slice: - return reflectSliceWithProperType(key, field, delim) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -// CR: copied from encoding/json/encode.go with modifications of time.Time support. -// TODO: add more test coverage. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflectTime: - t, ok := v.Interface().(time.Time) - return ok && t.IsZero() - } - return false -} - -func (s *Section) reflectFrom(val reflect.Value) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - opts := strings.SplitN(tag, ",", 2) - if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) { - continue - } - - fieldName := s.parseFieldName(tpField.Name, opts[0]) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) || - (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { - // Note: The only error here is section doesn't exist. - sec, err := s.f.GetSection(fieldName) - if err != nil { - // Note: fieldName can never be empty here, ignore error. - sec, _ = s.f.NewSection(fieldName) - } - if err = sec.reflectFrom(field); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - continue - } - - // Note: Same reason as secion. - key, err := s.GetKey(fieldName) - if err != nil { - key, _ = s.NewKey(fieldName, "") - } - if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - - } - return nil -} - -// ReflectFrom reflects secion from given struct. -func (s *Section) ReflectFrom(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot reflect from non-pointer struct") - } - - return s.reflectFrom(val) -} - -// ReflectFrom reflects file from given struct. -func (f *File) ReflectFrom(v interface{}) error { - return f.Section("").ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct with name mapper. -func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { - cfg.NameMapper = mapper - return cfg.ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct. -func ReflectFrom(cfg *File, v interface{}) error { - return ReflectFromWithMapper(cfg, v, nil) -} diff --git a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e3..0000000000 --- a/vendor/github.com/go-openapi/jsonpointer/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonpointer/LICENSE b/vendor/github.com/go-openapi/jsonpointer/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/go-openapi/jsonpointer/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/jsonpointer/README.md b/vendor/github.com/go-openapi/jsonpointer/README.md deleted file mode 100644 index 813788aff1..0000000000 --- a/vendor/github.com/go-openapi/jsonpointer/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonpointer [![Build Status](https://travis-ci.org/go-openapi/jsonpointer.svg?branch=master)](https://travis-ci.org/go-openapi/jsonpointer) [![codecov](https://codecov.io/gh/go-openapi/jsonpointer/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonpointer) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonpointer/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonpointer?status.svg)](http://godoc.org/github.com/go-openapi/jsonpointer) -An implementation of JSON Pointer - Go language - -## Status -Completed YES - -Tested YES - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -### Note -The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented. diff --git a/vendor/github.com/go-openapi/jsonpointer/pointer.go b/vendor/github.com/go-openapi/jsonpointer/pointer.go deleted file mode 100644 index fe2d6ee574..0000000000 --- a/vendor/github.com/go-openapi/jsonpointer/pointer.go +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonpointer -// repository-desc An implementation of JSON Pointer - Go language -// -// description Main and unique file. -// -// created 25-02-2013 - -package jsonpointer - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "strings" - - "github.com/go-openapi/swag" -) - -const ( - emptyPointer = `` - pointerSeparator = `/` - - invalidStart = `JSON pointer must be empty or start with a "` + pointerSeparator -) - -var jsonPointableType = reflect.TypeOf(new(JSONPointable)).Elem() -var jsonSetableType = reflect.TypeOf(new(JSONSetable)).Elem() - -// JSONPointable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONPointable interface { - JSONLookup(string) (interface{}, error) -} - -// JSONSetable is an interface for structs to implement when they need to customize the -// json pointer process -type JSONSetable interface { - JSONSet(string, interface{}) error -} - -// New creates a new json pointer for the given string -func New(jsonPointerString string) (Pointer, error) { - - var p Pointer - err := p.parse(jsonPointerString) - return p, err - -} - -// Pointer the json pointer reprsentation -type Pointer struct { - referenceTokens []string -} - -// "Constructor", parses the given string JSON pointer -func (p *Pointer) parse(jsonPointerString string) error { - - var err error - - if jsonPointerString != emptyPointer { - if !strings.HasPrefix(jsonPointerString, pointerSeparator) { - err = errors.New(invalidStart) - } else { - referenceTokens := strings.Split(jsonPointerString, pointerSeparator) - for _, referenceToken := range referenceTokens[1:] { - p.referenceTokens = append(p.referenceTokens, referenceToken) - } - } - } - - return err -} - -// Get uses the pointer to retrieve a value from a JSON document -func (p *Pointer) Get(document interface{}) (interface{}, reflect.Kind, error) { - return p.get(document, swag.DefaultJSONNameProvider) -} - -// Set uses the pointer to set a value from a JSON document -func (p *Pointer) Set(document interface{}, value interface{}) (interface{}, error) { - return document, p.set(document, value, swag.DefaultJSONNameProvider) -} - -// GetForToken gets a value for a json pointer token 1 level deep -func GetForToken(document interface{}, decodedToken string) (interface{}, reflect.Kind, error) { - return getSingleImpl(document, decodedToken, swag.DefaultJSONNameProvider) -} - -// SetForToken gets a value for a json pointer token 1 level deep -func SetForToken(document interface{}, decodedToken string, value interface{}) (interface{}, error) { - return document, setSingleImpl(document, value, decodedToken, swag.DefaultJSONNameProvider) -} - -func getSingleImpl(node interface{}, decodedToken string, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - switch kind { - - case reflect.Struct: - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return nil, kind, err - } - return r, kind, nil - } - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return nil, kind, fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - return fld.Interface(), kind, nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if mv.IsValid() && !swag.IsZero(mv) { - return mv.Interface(), kind, nil - } - return nil, kind, fmt.Errorf("object has no key %q", decodedToken) - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return nil, kind, err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return nil, kind, fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength-1, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - return elem.Interface(), kind, nil - - default: - return nil, kind, fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func setSingleImpl(node, data interface{}, decodedToken string, nameProvider *swag.NameProvider) error { - rValue := reflect.Indirect(reflect.ValueOf(node)) - switch rValue.Kind() { - - case reflect.Struct: - if ns, ok := node.(JSONSetable); ok { // pointer impl - return ns.JSONSet(decodedToken, data) - } - - if rValue.Type().Implements(jsonSetableType) { - return node.(JSONSetable).JSONSet(decodedToken, data) - } - - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.IsValid() { - fld.Set(reflect.ValueOf(data)) - } - return nil - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - rValue.SetMapIndex(kv, reflect.ValueOf(data)) - return nil - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if !elem.CanSet() { - return fmt.Errorf("can't set slice index %s to %v", decodedToken, data) - } - elem.Set(reflect.ValueOf(data)) - return nil - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - -} - -func (p *Pointer) get(node interface{}, nameProvider *swag.NameProvider) (interface{}, reflect.Kind, error) { - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - kind := reflect.Invalid - - // Full document when empty - if len(p.referenceTokens) == 0 { - return node, kind, nil - } - - for _, token := range p.referenceTokens { - - decodedToken := Unescape(token) - - r, knd, err := getSingleImpl(node, decodedToken, nameProvider) - if err != nil { - return nil, knd, err - } - node, kind = r, knd - - } - - rValue := reflect.ValueOf(node) - kind = rValue.Kind() - - return node, kind, nil -} - -func (p *Pointer) set(node, data interface{}, nameProvider *swag.NameProvider) error { - knd := reflect.ValueOf(node).Kind() - - if knd != reflect.Ptr && knd != reflect.Struct && knd != reflect.Map && knd != reflect.Slice && knd != reflect.Array { - return fmt.Errorf("only structs, pointers, maps and slices are supported for setting values") - } - - if nameProvider == nil { - nameProvider = swag.DefaultJSONNameProvider - } - - // Full document when empty - if len(p.referenceTokens) == 0 { - return nil - } - - lastI := len(p.referenceTokens) - 1 - for i, token := range p.referenceTokens { - isLastToken := i == lastI - decodedToken := Unescape(token) - - if isLastToken { - - return setSingleImpl(node, data, decodedToken, nameProvider) - } - - rValue := reflect.Indirect(reflect.ValueOf(node)) - kind := rValue.Kind() - - switch kind { - - case reflect.Struct: - if rValue.Type().Implements(jsonPointableType) { - r, err := node.(JSONPointable).JSONLookup(decodedToken) - if err != nil { - return err - } - fld := reflect.ValueOf(r) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = r - continue - } - nm, ok := nameProvider.GetGoNameForType(rValue.Type(), decodedToken) - if !ok { - return fmt.Errorf("object has no field %q", decodedToken) - } - fld := rValue.FieldByName(nm) - if fld.CanAddr() && fld.Kind() != reflect.Interface && fld.Kind() != reflect.Map && fld.Kind() != reflect.Slice && fld.Kind() != reflect.Ptr { - node = fld.Addr().Interface() - continue - } - node = fld.Interface() - - case reflect.Map: - kv := reflect.ValueOf(decodedToken) - mv := rValue.MapIndex(kv) - - if !mv.IsValid() { - return fmt.Errorf("object has no key %q", decodedToken) - } - if mv.CanAddr() && mv.Kind() != reflect.Interface && mv.Kind() != reflect.Map && mv.Kind() != reflect.Slice && mv.Kind() != reflect.Ptr { - node = mv.Addr().Interface() - continue - } - node = mv.Interface() - - case reflect.Slice: - tokenIndex, err := strconv.Atoi(decodedToken) - if err != nil { - return err - } - sLength := rValue.Len() - if tokenIndex < 0 || tokenIndex >= sLength { - return fmt.Errorf("index out of bounds array[0,%d] index '%d'", sLength, tokenIndex) - } - - elem := rValue.Index(tokenIndex) - if elem.CanAddr() && elem.Kind() != reflect.Interface && elem.Kind() != reflect.Map && elem.Kind() != reflect.Slice && elem.Kind() != reflect.Ptr { - node = elem.Addr().Interface() - continue - } - node = elem.Interface() - - default: - return fmt.Errorf("invalid token reference %q", decodedToken) - } - - } - - return nil -} - -// DecodedTokens returns the decoded tokens -func (p *Pointer) DecodedTokens() []string { - result := make([]string, 0, len(p.referenceTokens)) - for _, t := range p.referenceTokens { - result = append(result, Unescape(t)) - } - return result -} - -// IsEmpty returns true if this is an empty json pointer -// this indicates that it points to the root document -func (p *Pointer) IsEmpty() bool { - return len(p.referenceTokens) == 0 -} - -// Pointer to string representation function -func (p *Pointer) String() string { - - if len(p.referenceTokens) == 0 { - return emptyPointer - } - - pointerString := pointerSeparator + strings.Join(p.referenceTokens, pointerSeparator) - - return pointerString -} - -// Specific JSON pointer encoding here -// ~0 => ~ -// ~1 => / -// ... and vice versa - -const ( - encRefTok0 = `~0` - encRefTok1 = `~1` - decRefTok0 = `~` - decRefTok1 = `/` -) - -// Unescape unescapes a json pointer reference token string to the original representation -func Unescape(token string) string { - step1 := strings.Replace(token, encRefTok1, decRefTok1, -1) - step2 := strings.Replace(step1, encRefTok0, decRefTok0, -1) - return step2 -} - -// Escape escapes a pointer reference token string -func Escape(token string) string { - step1 := strings.Replace(token, decRefTok0, encRefTok0, -1) - step2 := strings.Replace(step1, decRefTok1, encRefTok1, -1) - return step2 -} diff --git a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e3..0000000000 --- a/vendor/github.com/go-openapi/jsonreference/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/jsonreference/LICENSE b/vendor/github.com/go-openapi/jsonreference/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/go-openapi/jsonreference/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/jsonreference/README.md b/vendor/github.com/go-openapi/jsonreference/README.md deleted file mode 100644 index 66345f4c61..0000000000 --- a/vendor/github.com/go-openapi/jsonreference/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# gojsonreference [![Build Status](https://travis-ci.org/go-openapi/jsonreference.svg?branch=master)](https://travis-ci.org/go-openapi/jsonreference) [![codecov](https://codecov.io/gh/go-openapi/jsonreference/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/jsonreference) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/jsonreference/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/jsonreference?status.svg)](http://godoc.org/github.com/go-openapi/jsonreference) -An implementation of JSON Reference - Go language - -## Status -Work in progress ( 90% done ) - -## Dependencies -https://github.com/go-openapi/jsonpointer - -## References -http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07 - -http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 diff --git a/vendor/github.com/go-openapi/jsonreference/reference.go b/vendor/github.com/go-openapi/jsonreference/reference.go deleted file mode 100644 index 3bc0a6e26f..0000000000 --- a/vendor/github.com/go-openapi/jsonreference/reference.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2013 sigu-399 ( https://github.com/sigu-399 ) -// -// 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. - -// author sigu-399 -// author-github https://github.com/sigu-399 -// author-mail sigu.399@gmail.com -// -// repository-name jsonreference -// repository-desc An implementation of JSON Reference - Go language -// -// description Main and unique file. -// -// created 26-02-2013 - -package jsonreference - -import ( - "errors" - "net/url" - "strings" - - "github.com/PuerkitoBio/purell" - "github.com/go-openapi/jsonpointer" -) - -const ( - fragmentRune = `#` -) - -// New creates a new reference for the given string -func New(jsonReferenceString string) (Ref, error) { - - var r Ref - err := r.parse(jsonReferenceString) - return r, err - -} - -// MustCreateRef parses the ref string and panics when it's invalid. -// Use the New method for a version that returns an error -func MustCreateRef(ref string) Ref { - r, err := New(ref) - if err != nil { - panic(err) - } - return r -} - -// Ref represents a json reference object -type Ref struct { - referenceURL *url.URL - referencePointer jsonpointer.Pointer - - HasFullURL bool - HasURLPathOnly bool - HasFragmentOnly bool - HasFileScheme bool - HasFullFilePath bool -} - -// GetURL gets the URL for this reference -func (r *Ref) GetURL() *url.URL { - return r.referenceURL -} - -// GetPointer gets the json pointer for this reference -func (r *Ref) GetPointer() *jsonpointer.Pointer { - return &r.referencePointer -} - -// String returns the best version of the url for this reference -func (r *Ref) String() string { - - if r.referenceURL != nil { - return r.referenceURL.String() - } - - if r.HasFragmentOnly { - return fragmentRune + r.referencePointer.String() - } - - return r.referencePointer.String() -} - -// IsRoot returns true if this reference is a root document -func (r *Ref) IsRoot() bool { - return r.referenceURL != nil && - !r.IsCanonical() && - !r.HasURLPathOnly && - r.referenceURL.Fragment == "" -} - -// IsCanonical returns true when this pointer starts with http(s):// or file:// -func (r *Ref) IsCanonical() bool { - return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullURL) -} - -// "Constructor", parses the given string JSON reference -func (r *Ref) parse(jsonReferenceString string) error { - - parsed, err := url.Parse(jsonReferenceString) - if err != nil { - return err - } - - r.referenceURL, _ = url.Parse(purell.NormalizeURL(parsed, purell.FlagsSafe|purell.FlagRemoveDuplicateSlashes)) - refURL := r.referenceURL - - if refURL.Scheme != "" && refURL.Host != "" { - r.HasFullURL = true - } else { - if refURL.Path != "" { - r.HasURLPathOnly = true - } else if refURL.RawQuery == "" && refURL.Fragment != "" { - r.HasFragmentOnly = true - } - } - - r.HasFileScheme = refURL.Scheme == "file" - r.HasFullFilePath = strings.HasPrefix(refURL.Path, "/") - - // invalid json-pointer error means url has no json-pointer fragment. simply ignore error - r.referencePointer, _ = jsonpointer.New(refURL.Fragment) - - return nil -} - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - childURL := child.GetURL() - parentURL := r.GetURL() - if childURL == nil { - return nil, errors.New("child url is nil") - } - if parentURL == nil { - return &child, nil - } - - ref, err := New(parentURL.ResolveReference(childURL).String()) - if err != nil { - return nil, err - } - return &ref, nil -} diff --git a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e3..0000000000 --- a/vendor/github.com/go-openapi/spec/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/spec/LICENSE b/vendor/github.com/go-openapi/spec/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/go-openapi/spec/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/spec/README.md b/vendor/github.com/go-openapi/spec/README.md deleted file mode 100644 index 1d1622082f..0000000000 --- a/vendor/github.com/go-openapi/spec/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# OAI object model [![Build Status](https://travis-ci.org/go-openapi/spec.svg?branch=master)](https://travis-ci.org/go-openapi/spec) [![codecov](https://codecov.io/gh/go-openapi/spec/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/spec) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/spec/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/spec?status.svg)](http://godoc.org/github.com/go-openapi/spec) - -The object model for OpenAPI specification documents diff --git a/vendor/github.com/go-openapi/spec/bindata.go b/vendor/github.com/go-openapi/spec/bindata.go deleted file mode 100644 index 9afb5df194..0000000000 --- a/vendor/github.com/go-openapi/spec/bindata.go +++ /dev/null @@ -1,260 +0,0 @@ -// Code generated by go-bindata. -// sources: -// schemas/jsonschema-draft-04.json -// schemas/v2/schema.json -// DO NOT EDIT! - -package spec - -import ( - "bytes" - "compress/gzip" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - "time" -) - -func bindataRead(data []byte, name string) ([]byte, error) { - gz, err := gzip.NewReader(bytes.NewBuffer(data)) - if err != nil { - return nil, fmt.Errorf("Read %q: %v", name, err) - } - - var buf bytes.Buffer - _, err = io.Copy(&buf, gz) - clErr := gz.Close() - - if err != nil { - return nil, fmt.Errorf("Read %q: %v", name, err) - } - if clErr != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -type asset struct { - bytes []byte - info os.FileInfo -} - -type bindataFileInfo struct { - name string - size int64 - mode os.FileMode - modTime time.Time -} - -func (fi bindataFileInfo) Name() string { - return fi.name -} -func (fi bindataFileInfo) Size() int64 { - return fi.size -} -func (fi bindataFileInfo) Mode() os.FileMode { - return fi.mode -} -func (fi bindataFileInfo) ModTime() time.Time { - return fi.modTime -} -func (fi bindataFileInfo) IsDir() bool { - return false -} -func (fi bindataFileInfo) Sys() interface{} { - return nil -} - -var _jsonschemaDraft04JSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xc4\x57\x3b\x6f\xdb\x3e\x10\xdf\xf3\x29\x08\x26\x63\xf2\x97\xff\x40\x27\x6f\x45\xbb\x18\x68\xd1\x0c\xdd\x0c\x0f\xb4\x75\xb2\x19\x50\xa4\x42\x51\x81\x0d\x43\xdf\xbd\xa0\xa8\x07\x29\x91\x92\x2d\xbb\x8d\x97\x28\xbc\xd7\xef\x8e\xf7\xe2\xf9\x01\x21\x84\x30\x8d\xf1\x12\xe1\x83\x52\xd9\x32\x8a\xde\x72\xc1\x5f\xf2\xdd\x01\x52\xf2\x9f\x90\xfb\x28\x96\x24\x51\x2f\x8b\x2f\x91\x39\x7b\xc4\xcf\x46\xe8\xc9\xfc\x3f\x43\x32\x86\x7c\x27\x69\xa6\xa8\xe0\x5a\xfa\x9b\x90\x80\x0c\x0b\x4a\x41\x91\x5a\x45\xc7\x9d\x50\x4e\x35\x73\x8e\x97\xc8\x20\xae\x08\x86\xed\xab\x94\xe4\xe4\x10\x2a\xa2\x3a\x65\xa0\x95\x93\x8a\xfc\xec\x12\x53\xca\x57\x0a\x52\xad\xef\xff\x1e\x89\xd6\xe7\x67\x84\x9f\x24\x24\x5a\xc5\x23\x46\x65\xcb\x54\x76\xfc\x38\x13\x39\x55\xf4\x03\x56\x5c\xc1\x1e\x64\x18\x04\xad\x19\x86\x30\x68\x5a\xa4\x78\x89\x16\x97\xe8\xff\x0e\x09\x29\x98\x5a\x0c\xed\x10\xc6\x7e\x69\xa8\x6b\x07\x76\x64\x45\x2e\xea\x63\x45\xe5\xb3\x66\x8e\x8d\x4e\x0d\x01\x95\x68\xe3\x85\x91\xd3\x34\x63\xf0\xfb\x94\x41\x3e\x34\x0d\xbc\x72\x60\xdd\x46\x1a\xe1\xad\x10\x0c\x08\xd7\x9f\xad\xe3\x08\xf3\x82\x31\xf3\x37\xdd\x9a\x13\xb1\x7d\x83\x9d\xd2\x5f\xb9\x92\x94\xef\x71\xc8\x7e\x45\x9d\x73\xcf\xd6\x65\x36\x7c\x8d\xa9\xf2\xf2\x94\x28\x38\x7d\x2f\xa0\xa1\x2a\x59\x40\x07\xf3\xc1\x02\xdb\xda\x68\x1c\x33\xa7\x99\x14\x19\x48\x45\x7b\xd1\x33\x45\x17\xf0\xa6\x46\xd9\x03\x92\x08\x99\x12\x7d\x57\xb8\x90\x14\x7b\x63\xd5\x15\xe5\xbd\x35\x2b\xaa\x18\x4c\xea\xf5\x8a\xba\xf5\x3e\x4b\x41\x93\xa5\x67\xfb\x38\x2d\x98\xa2\x19\x83\x2a\xf7\x03\x6a\x9b\x74\x0b\x56\x5e\x8f\x02\xc7\x1d\x2b\x72\xfa\x01\x3f\x5b\x16\xf7\xc6\x6d\xfb\xe4\x58\xb3\x8c\x1b\xf7\x0a\x77\x86\xa6\xb4\xb4\xf5\xe4\x92\xbb\xa0\x24\x84\xe5\x01\x84\xad\x13\x37\x21\x9c\xd2\x72\x0b\x42\x72\xfc\x01\x7c\xaf\x0e\xbd\x9e\x3b\xd5\xbc\x1c\x1f\xaf\xd6\xd0\xb6\x52\xb7\xdf\x12\xa5\x40\x4e\xe7\x68\xb0\x78\x24\xec\xe1\xe8\x0f\x26\x89\xe3\x0a\x0a\x61\x4d\x23\xe9\xf7\x70\x7e\x32\x3d\xdc\x39\xd6\xbf\xf3\x30\xd0\xfd\xf6\x55\xb3\x79\x27\x96\xfe\x6d\x82\x37\x73\xf6\x8f\x36\x3a\x03\xa4\x6d\x7d\x1c\x9e\x73\x35\xf6\x18\xbf\x15\x76\x4a\x8e\x2b\xcf\x00\xbf\x2a\x99\xae\x55\xe0\xcf\x25\x77\x68\xfc\x95\xba\x79\x75\x06\xcb\x5c\x77\x67\x69\xf1\xfb\x2c\xe1\xbd\xa0\x12\xe2\x31\x45\xf6\x30\x0f\x14\xc8\xab\x7f\x60\x4e\x27\xe0\x3f\xaf\x92\xd0\x6a\x8a\x82\xdb\xc0\xa4\xbb\x63\x65\x34\x0d\x28\xb0\x6b\x7c\x1e\x1e\xd3\x51\xc7\x6e\xf4\x33\x60\xc5\x90\x01\x8f\x81\xef\xee\x88\x68\x90\x69\x23\xb9\x8a\x2e\x69\x98\x7d\xa6\x91\x32\x1a\xc8\x6e\x9c\x13\x7f\x10\xea\xcd\xfd\x4e\xef\xa6\xb1\x25\xd9\xde\x22\x8d\xfa\x59\x63\xc5\x0d\x80\xf5\x28\xf1\xd6\xb9\x37\x9e\xa3\xee\xb5\x4c\xbe\x37\xe0\x55\xc6\x27\x82\x75\x49\xd0\xda\xe0\xb9\x1d\xca\xbf\x5b\xd4\xcf\xbf\x0b\x47\xac\x2d\x59\x07\xfe\x7a\x49\xc1\x61\xa6\x24\x17\x2a\xf0\xbe\x2e\xdb\x17\x7f\xa0\x3c\x7d\x4b\xf3\xba\xdb\xc3\xed\x06\xee\xdb\x5e\xd7\xdd\x42\x5c\x47\xb2\xb3\x68\x75\x8c\xf2\xe1\x4f\x00\x00\x00\xff\xff\x4e\x9b\x8d\xdf\x17\x11\x00\x00") - -func jsonschemaDraft04JSONBytes() ([]byte, error) { - return bindataRead( - _jsonschemaDraft04JSON, - "jsonschema-draft-04.json", - ) -} - -func jsonschemaDraft04JSON() (*asset, error) { - bytes, err := jsonschemaDraft04JSONBytes() - if err != nil { - return nil, err - } - - info := bindataFileInfo{name: "jsonschema-draft-04.json", size: 4375, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} - a := &asset{bytes: bytes, info: info} - return a, nil -} - -var _v2SchemaJSON = []byte("\x1f\x8b\x08\x00\x00\x09\x6e\x88\x00\xff\xec\x5d\x4f\x93\xdb\x36\xb2\xbf\xfb\x53\xa0\x14\x57\xd9\xae\xd8\x92\xe3\xf7\x2e\xcf\x97\xd4\xbc\xd8\x49\x66\x37\x5e\x4f\x79\x26\xbb\x87\x78\x5c\x05\x91\x2d\x09\x09\x09\x30\x00\x38\x33\x5a\xef\x7c\xf7\x2d\xf0\x9f\x08\x02\x20\x41\x8a\xd2\xc8\x0e\x0f\xa9\x78\x28\xa0\xd1\xdd\x68\x34\x7e\xdd\xf8\xf7\xf9\x11\x42\x33\x49\x64\x04\xb3\xd7\x68\x76\x86\xfe\x76\xf9\xfe\x1f\xe8\x32\xd8\x40\x8c\xd1\x8a\x71\x74\x79\x8b\xd7\x6b\xe0\xe8\xd5\xfc\x25\x3a\xbb\x38\x9f\xcf\x9e\xab\x0a\x24\x54\xa5\x37\x52\x26\xaf\x17\x0b\x91\x17\x99\x13\xb6\xb8\x79\xb5\x10\x59\xdd\xf9\xef\x82\xd1\x6f\xf2\xc2\x8f\xf3\x4f\xb5\x1a\xea\xc7\x17\x45\x41\xc6\xd7\x8b\x90\xe3\x95\x7c\xf1\xf2\x7f\x8b\xca\x45\x3d\xb9\x4d\x32\xa6\xd8\xf2\x77\x08\x64\xfe\x8d\xc3\x9f\x29\xe1\xa0\x9a\xff\xed\x11\x42\x08\xcd\x8a\xd6\xb3\x9f\x15\x67\x74\xc5\xca\x7f\x27\x58\x6e\xc4\xec\x11\x42\xd7\x59\x5d\x1c\x86\x44\x12\x46\x71\x74\xc1\x59\x02\x5c\x12\x10\xb3\xd7\x68\x85\x23\x01\x59\x81\x04\x4b\x09\x9c\x6a\xbf\x7e\xce\x49\x7d\xba\x7b\x51\xfd\xa1\x44\xe2\xb0\x52\xac\x7d\xb3\x08\x61\x45\x68\x46\x56\x2c\x6e\x80\x86\x8c\xbf\xbd\x93\x40\x05\x61\x74\x96\x95\xbe\x7f\x84\xd0\x7d\x4e\xde\x42\xb7\xe4\xbe\x46\xbb\x14\x5b\x48\x4e\xe8\xba\x90\x05\xa1\x19\xd0\x34\xae\xc4\xce\xbe\xbc\x9a\xbf\x9c\x15\x7f\x5d\x57\xc5\x42\x10\x01\x27\x89\xe2\x48\x51\xb9\xda\x40\xd5\x87\x37\xc0\x15\x5f\x88\xad\x90\xdc\x10\x81\x42\x16\xa4\x31\x50\x39\x2f\x38\xad\xab\xb0\x53\xd8\xac\x94\x56\x6f\xc3\x84\xf4\x11\xa4\x50\xb3\xfa\xe9\xd3\x6f\x9f\x3e\xdf\x2f\xd0\xeb\x8f\x1f\x3f\x7e\xbc\xfe\xf6\xe9\xf7\xaf\x5f\x7f\xfc\x18\x7e\xfb\xec\xfb\xc7\xb3\x36\x79\x54\x43\xe8\x29\xc5\x31\x20\xc6\x11\x49\x9e\xe5\x12\x41\x66\xa0\xe8\xed\x1d\x8e\x93\x08\x5e\xa3\x27\x3b\xc3\x7c\xa2\x73\xba\xc4\x02\x2e\xb0\xdc\xf4\xe5\x76\xd1\xca\x96\xa2\x8a\x94\xcd\x21\xc9\x6c\xec\x2c\x70\x42\x9e\x34\x74\x9d\x19\x7c\xcd\x20\x9c\xea\x2e\x0a\xfe\x42\x84\xd4\x29\x04\x8c\x8a\xb4\x41\xa2\xc1\xdc\x19\x8a\x88\x90\x4a\x49\xef\xce\xdf\xbd\x45\x4a\x52\x81\x70\x10\x40\x22\x21\x44\xcb\x6d\xc5\xec\x4e\x3c\x1c\x45\xef\x57\x9a\xb5\x7d\xae\xfe\xe5\xe4\x31\x86\x90\xe0\xab\x6d\x02\x3b\x2e\xcb\x11\x90\xd9\xa8\xc6\x77\xc2\x59\x98\x06\xfd\xf9\x2e\x78\x45\x01\xa6\xa8\xa0\x71\x5c\xbe\x33\xa7\xd2\xd9\x5f\x95\xef\xd9\xd5\xac\xfd\xdc\x5d\xbf\x5e\xb8\xd1\x3e\xc7\x31\x48\xe0\x5e\x4c\x14\x65\xdf\xb8\xa8\x71\x10\x09\xa3\xc2\xc7\x02\xcb\xa2\x4e\x5a\x02\x82\x94\x13\xb9\xf5\x30\xe6\xb2\xa4\xb5\xfe\x9b\x3e\x7a\xb2\x55\xd2\xa8\x4a\xbc\x16\xb6\x71\x8e\x39\xc7\xdb\x9d\xe1\x10\x09\x71\xbd\x9c\xb3\x41\x89\xd7\xa5\x89\xdc\x57\xb5\x53\x4a\xfe\x4c\xe1\xbc\xa0\x21\x79\x0a\x1a\x0f\x70\xa7\x5c\x08\x8e\xde\xb0\xc0\x43\x24\xad\x74\x63\x0e\xb1\xd9\x90\xe1\xb0\x2d\x13\xa7\x6d\x78\xfd\x04\x14\x38\x8e\x90\xaa\xce\x63\xac\x3e\x23\xbc\x64\xa9\xb4\xf8\x03\x63\xde\xcd\xbe\x16\x13\x4a\x55\xac\x82\x12\xc6\xac\xd4\x35\xf7\x22\xd4\x3a\xff\x22\x73\x0e\x6e\x51\xa0\x75\x1e\xae\x8f\xe8\x5d\xc7\x59\xe6\xe4\x9a\x18\x8d\xd6\x1c\x53\x84\x4d\xb7\x67\x28\x37\x09\x84\x69\x88\x12\x0e\x01\x11\x80\x32\xa2\xf5\xb9\xaa\xc6\xd9\x73\x53\xab\xfb\xb4\x2e\x20\xc6\x54\x92\xa0\x9a\xf3\x69\x1a\x2f\x81\x77\x37\xae\x53\x1a\xce\x40\xc4\xa8\x82\x1c\xb5\xef\xda\x24\x7d\xb9\x61\x69\x14\xa2\x25\xa0\x90\xac\x56\xc0\x81\x4a\xb4\xe2\x2c\xce\x4a\x64\x7a\x9a\x23\xf4\x13\x91\x3f\xa7\x4b\xf4\x63\x84\x6f\x18\x87\x10\xbd\xc3\xfc\x8f\x90\xdd\x52\x44\x04\xc2\x51\xc4\x6e\x21\x74\x48\x21\x81\xc7\xe2\xfd\xea\x12\xf8\x0d\x09\xf6\xe9\x47\x35\xaf\x67\xc4\x14\xf7\x22\x27\x97\xe1\xe2\x76\x2d\x06\x8c\x4a\x1c\x48\x3f\x73\x2d\x0b\x5b\x29\x45\x24\x00\x2a\x0c\x11\xec\x94\xca\xc2\xa6\xc1\x37\x21\x43\x83\x3b\x5f\x97\xf1\x43\x5e\x53\x73\x19\xa5\x36\xd8\x2d\x05\x2e\x34\x0b\xeb\x39\xfc\x1d\x63\x51\x01\xbd\x3d\xbb\x90\x84\x40\x25\x59\x6d\x09\x5d\xa3\x1c\x37\xe6\x5c\x16\x9a\x40\x09\x70\xc1\xe8\x82\xf1\x35\xa6\xe4\xdf\x99\x5c\x8e\x9e\x4d\x79\xb4\x27\x2f\xbf\x7e\xf8\x05\x25\x8c\x50\xa9\x98\x29\x90\x62\x60\xea\x75\xae\x13\xca\xbf\x2b\x1a\x29\x27\x76\xd6\x20\xc6\x64\x5f\xe6\x32\x1a\x08\x87\x21\x07\x21\xbc\xb4\xe4\xe0\x32\x67\xa6\xcd\xf3\x1e\xcd\xd9\x6b\xb6\x6f\x8e\x27\xa7\xed\xdb\xe7\xbc\xcc\x1a\x07\xce\x6f\x87\x33\xf0\xba\x51\x17\x22\x66\x78\x79\x8e\xce\xe5\x13\x81\x80\x06\x2c\xe5\x78\x0d\xa1\xb2\xb8\x54\xa8\x79\x09\xbd\xbf\x3c\x47\x01\x8b\x13\x2c\xc9\x32\xaa\xaa\x1d\xd5\xee\xab\x36\xbd\x6c\xfd\x54\x6c\xc8\x08\x01\x3c\xbd\xe7\x07\x88\xb0\x24\x37\x79\x90\x28\x4a\x1d\x10\x1a\x92\x1b\x12\xa6\x38\x42\x40\xc3\x4c\x43\x62\x8e\xae\x36\xb0\x45\x71\x2a\xa4\x9a\x23\x79\x59\xb1\xa8\xf2\xa4\x0c\x60\x9f\xcc\x8d\x40\xf5\x80\xca\xa8\x99\xc3\xa7\x85\x1f\x31\x25\xa9\x82\xc5\x6d\xbd\xd8\x36\x76\x7c\x02\x28\x97\xf6\x1d\x74\x3b\x11\x7e\x91\xae\x32\xf8\x6c\xf4\xe6\x7b\x9a\xa5\x1f\x62\xc6\x21\xcf\x9a\xe5\xed\x8b\x02\xf3\x2c\x33\x33\xdf\x00\xca\xc9\x09\xb4\x04\xf5\xa5\x08\xd7\xc3\x02\x18\x66\xf1\xab\x1e\x83\x37\x4c\xcd\x12\xc1\x1d\x50\xf6\xaa\xbd\xfe\xe2\x73\x48\x38\x08\xa0\x32\x9b\x18\x44\x86\x0b\x6a\xc1\xaa\x26\x96\x2d\x96\x3c\xa0\x54\x65\x73\x87\x15\xca\x15\xe5\xf5\x94\x46\x9f\x33\x1a\x0c\x9a\xb1\x5a\xd9\x6a\x95\xcd\xcb\x7e\xec\x9a\xc5\x94\x3b\x37\x26\x31\xd7\xfc\xe4\x1f\x13\x8c\x31\x75\x9c\xba\xf7\x87\x3c\xa1\xb7\x4f\x17\x1b\x09\x82\x98\xc4\x70\x95\xd3\xe8\x4c\x48\x5a\xa6\xd6\x2a\x3d\x56\x42\x80\x9f\xaf\xae\x2e\x50\x0c\x42\xe0\x35\x34\x3c\x8a\x62\x03\x37\xba\xb2\x27\x04\xda\x25\x8d\x06\xe2\xa0\x13\x8a\xf3\xf5\xec\x10\x72\x67\x88\x90\x3d\x4b\x64\xeb\xaa\xda\x8f\xf7\x5a\x75\x47\x9a\xa8\x51\x70\x26\xd2\x38\xc6\x7c\xbb\x57\xfc\xbd\xe4\x04\x56\xa8\xa0\x54\x9a\x45\xd5\xf7\x0f\x16\xfc\x57\x1c\x3c\xdf\x23\xba\x77\x38\xda\x16\x4b\x31\x53\x6a\x4d\x9a\x15\x63\xe7\xe1\x18\x69\x9f\x22\xe0\x24\xbb\x94\x4b\x97\xee\x2d\xf9\x70\x87\x72\x7b\xe6\xc4\x33\x2a\x66\x5e\x1c\x35\x72\xe3\x2d\xda\x73\xe4\xc7\x51\x6d\xa4\xa1\x2a\x4f\xde\x94\xcb\xb2\x3e\x31\x48\xae\x82\xce\xc9\xc8\x65\xcd\xc3\xb7\x34\xb6\x2b\xdf\x58\x65\x78\x6e\x73\xac\x5e\x24\x0d\x3f\xdc\x70\x23\xc6\xda\x52\x0b\x2d\x63\x7d\xa9\x49\x2d\x54\x48\x28\xc0\x12\x9c\xe3\x63\xc9\x58\x04\x98\x36\x07\xc8\x0a\xa7\x91\xd4\xf0\xbc\xc1\xa8\xb9\x70\xd0\xc6\xa9\xb6\x78\x80\x5a\xa3\xb4\x2c\xf4\x18\x0b\x8a\x9d\xd0\xb4\x55\x10\xee\x0d\xc5\xd6\xe0\x99\x93\xdc\xa1\x04\xbb\xf1\xa7\x23\xd1\xd1\x97\x8c\x87\x13\x0a\x21\x02\xe9\x99\x25\xed\x20\xc5\x92\x66\x3c\x32\x9c\xd6\x06\xb0\x31\x5c\x86\x29\x0a\xcb\x60\x33\x12\xa5\x91\xfc\x96\x75\xd0\x59\xd7\x13\xbd\xd3\x23\x79\xdd\x2a\x90\xa6\x38\x06\x91\x39\x7f\x20\x72\x03\x1c\x2d\x01\x61\xba\x45\x37\x38\x22\x61\x8e\x71\x85\xc4\x32\x15\x28\x60\x61\x16\xb8\x3d\x29\xdc\x4d\x3d\x2f\x12\x13\x7d\xc8\x7e\x37\xee\xa8\x7f\xfa\xdb\xcb\x17\xff\x77\xfd\xf9\x7f\xee\x9f\x3d\xfe\xcf\xa7\xa7\x45\xfb\xcf\x1e\xf7\xf3\xe0\xff\xc4\x51\x0a\x8e\x4c\xcb\x01\xdc\x0a\x65\xb2\x01\x83\xed\x3d\xe4\xa9\xa3\x4e\x2d\x59\xc5\xe8\x2f\x48\x7d\x5a\x6e\x37\xbf\x5c\x9f\x35\x13\x64\x14\xfa\xef\x0b\x68\xa6\x0d\xb4\x8e\xf1\xa8\xff\xbb\x60\xf4\x03\x64\xab\x5b\x81\x65\x51\xe6\xda\xca\xfa\xf0\xb0\xac\x3e\x9c\xca\x26\x0e\x1d\xdb\x57\x5b\xbb\xb4\x9a\xa6\xb6\x9b\x1a\x6b\xd1\x9a\x9e\x7e\x33\x9a\xec\x41\x69\x45\x22\xb8\xb4\x51\xeb\x04\x77\xca\x6f\x7b\x7b\xc8\xb2\xb0\x95\x92\x25\x5b\xd0\x42\xaa\x2a\xdd\x32\x78\x4f\x0c\xab\x68\x46\x6c\xea\x6d\xf4\x5c\x5e\xde\xc4\xac\xa5\xf9\xd1\x00\x9f\x7d\x98\x65\x24\xbd\xc7\x97\xd4\xb3\x3a\xa8\x2b\xa0\x34\x76\xf9\x65\x5f\x2d\x25\x95\x1b\xcf\xd6\xf4\x9b\x5f\x09\x95\xb0\x36\x3f\xdb\xd0\x39\x2a\x93\x1c\x9d\x03\xa2\x4a\xca\xf5\xf6\x10\xb6\x94\x89\x0b\x6a\x70\x12\x13\x49\x6e\x40\xe4\x29\x12\x2b\xbd\x80\x45\x11\x04\xaa\xc2\x8f\x56\x9e\x5c\x6b\xec\x8d\x5a\x0e\x14\x59\x06\x2b\x1e\x24\xcb\xc2\x56\x4a\x31\xbe\x23\x71\x1a\xfb\x51\x2a\x0b\x3b\x1c\x48\x10\xa5\x82\xdc\xc0\xbb\x3e\x24\x8d\x5a\x76\x2e\x09\xed\xc1\x65\x51\xb8\x83\xcb\x3e\x24\x8d\x5a\x2e\x5d\xfe\x02\x74\x2d\x3d\xf1\xef\xae\xb8\x4b\xe6\x5e\xd4\xaa\xe2\x2e\x5c\x5e\xec\x0e\xf5\x5b\x0c\xcb\x0a\xbb\xa4\x3c\xf7\x1f\x2a\x55\x69\x97\x8c\x7d\x68\x95\xa5\xad\xb4\xf4\x9c\xa5\x07\xb9\x7a\x05\xbb\xad\x50\x6f\xfb\xa0\x4e\x9b\x48\x23\x49\x92\x28\x87\x19\x3e\x32\xee\xca\x3b\x46\x7e\x7f\x18\x64\xcc\xcc\x0f\x34\xe9\x36\x8b\xb7\x6c\xa8\xa5\x5b\x54\x4c\x54\x5b\x15\x3a\xf1\x6c\x2d\xfe\x96\xc8\x0d\xba\x7b\x81\x88\xc8\x23\xab\xee\x7d\x3b\x92\xa7\x60\x29\xe3\xdc\xff\xb8\x64\xe1\xf6\xa2\x5a\x59\xdc\x6f\xeb\x45\x7d\x6a\xd1\x76\x1e\xea\xb8\xf1\xfa\x14\xd3\x36\x63\xe5\xd7\xf3\xe4\xbe\x25\xbd\x5e\x05\xeb\x73\x74\xb5\x21\x2a\x2e\x4e\xa3\x30\xdf\xbf\x43\x28\x2a\xd1\xa5\x2a\x9d\x8a\xfd\x76\xd8\x8d\xbc\x67\x65\xc7\xb8\x03\x45\xec\xa3\xb0\x37\x8a\x70\x4c\x68\x91\x51\x8e\x58\x80\xed\x4a\xf3\x81\x62\xca\x96\xbb\xf1\x52\xcd\x80\xfb\xe4\x4a\x5d\x6c\xdf\x6e\x20\x4b\x80\x30\x8e\x28\x93\xf9\xe9\x8d\x8a\x6d\xd5\x59\x65\x7b\xaa\x44\x9e\xc0\xc2\xd1\x7c\x40\x26\xd6\x1a\xce\xf9\xc5\x69\x7b\x6c\xec\xc8\x71\x7b\xe5\x21\x2e\xd3\xe5\x65\x93\x91\x53\x0b\x7b\x3a\xc7\xfa\x17\x6a\x01\xa7\x33\xd0\xf4\x40\x0f\x39\x87\xda\xe4\x54\x87\x3a\xd5\xe3\xc7\xa6\x8e\x20\xd4\x11\xb2\x4e\xb1\xe9\x14\x9b\x4e\xb1\xe9\x14\x9b\xfe\x15\x63\xd3\x47\xf5\xff\x97\x38\xe9\xcf\x14\xf8\x76\x82\x49\x13\x4c\xaa\x7d\xcd\x6c\x62\x42\x49\x87\x43\x49\x19\x33\x6f\xe3\x44\x6e\x9b\xab\x8a\x3e\x86\xaa\x99\x52\x1b\x5b\x59\x33\x02\x09\xa0\x21\xa1\x6b\x84\x6b\x66\xbb\xdc\x16\x0c\xd3\x68\xab\xec\x36\x4b\xd8\x60\x8a\x40\x31\x85\x6e\x14\x57\x13\xc2\xfb\x92\x10\xde\xbf\x88\xdc\xbc\x53\x5e\x7f\x82\x7a\x13\xd4\x9b\xa0\xde\x04\xf5\x90\x01\xf5\x94\xcb\x7b\x83\x25\x9e\xd0\xde\x84\xf6\x6a\x5f\x4b\xb3\x98\x00\xdf\x04\xf8\x6c\xbc\x7f\x19\x80\xaf\xf1\x71\x45\x22\x98\x40\xe0\x04\x02\x27\x10\xd8\x29\xf5\x04\x02\xff\x4a\x20\x30\xc1\x72\xf3\x65\x02\x40\xd7\xc1\xd1\xe2\x6b\xf1\xa9\x7b\xfb\xe4\x20\xc0\x68\x9d\xd4\xb4\xd3\x96\xb5\xa6\xd1\x41\x20\xe6\x89\xc3\x48\x65\x58\x13\x84\x9c\x56\x56\x3b\x0c\xe0\x6b\x83\x5c\x13\xd2\x9a\x90\xd6\x84\xb4\x26\xa4\x85\x0c\xa4\x45\x19\xfd\xff\x63\x6c\x52\xb5\x1f\x1e\x19\x74\x3a\xcd\xb9\x69\xce\xa6\x3a\x0f\x7a\x2d\x19\xc7\x81\x14\x5d\xcb\xd5\x03\xc9\x39\xd0\xb0\xd1\xb3\xcd\xfb\x7a\x2d\x5d\x3a\x48\xe1\xfa\x2e\xe6\x81\x42\x18\x86\xd6\xc1\xbe\xb1\x23\xd3\xf7\x34\xed\x19\x0a\x0b\xc4\x48\x44\xfd\x22\x50\xb6\x42\x58\xbb\xe5\x3d\xa7\x73\xd4\x8b\xc4\x8c\x70\x61\xec\x73\xee\xc3\x81\x8b\xf5\xe2\xd7\x52\x3e\xcf\xeb\xeb\x17\x3b\x71\x16\xda\x7d\xb8\xde\xf0\x7a\x8f\x06\x2d\xa7\x40\x7b\xc1\x9d\x41\x4d\xb6\x61\xa2\x4e\x9f\x3d\xa0\xc5\xae\xe3\x1c\x1d\x40\x6c\x48\x8b\x63\xa0\xb5\x01\xed\x8e\x02\xe9\x86\xc8\x3b\x06\xee\xdb\x4b\xde\xbd\xc0\xa1\x6f\xcb\xda\xfc\xc2\x44\x16\x87\x9c\x17\x31\xd3\x30\x20\x39\x42\xcb\x6f\xf2\xf1\xf4\x72\x10\xf8\x1c\xa0\xf3\xbd\x10\xea\x21\x35\x7d\xe8\x86\xdb\x15\xed\x81\x81\x07\x28\xbb\x13\x28\xc7\xf8\xce\x7d\x8d\xc2\x31\xb4\x7e\x94\xd6\xdb\x55\xef\x4a\xfb\xed\xc3\x40\x3e\xeb\x9f\xe9\x99\x0f\xdf\x08\x65\x88\x27\x73\x86\x31\x9d\x47\xdf\x55\x19\xba\x3d\xee\x15\x0a\xcd\x8c\xaa\x5e\xb9\xf6\x57\x33\x73\x5a\xa1\x89\x7b\x3b\xa0\xb2\xa4\xc2\xf6\xc1\x53\xb5\x00\xca\x23\xe5\xf4\x60\x6a\xb4\x2d\x74\xea\x4e\xed\x3b\xe3\x47\xfb\xed\x82\x3d\x19\xd4\x3b\x6b\xaf\xae\x2b\x2f\x57\xb3\x82\x68\xcb\xed\x88\x2e\xe1\x5c\xd7\x26\xfa\x0a\x65\xe7\xce\x11\x33\xb4\xdd\x66\xe3\x37\xf6\xfa\x70\xd6\x4f\xa1\x21\x51\xd8\x3c\x26\x14\x4b\xc6\x87\x44\x27\x1c\x70\xf8\x9e\x46\xce\xab\x21\x07\x5f\xc1\x76\x17\x1b\x77\xb4\xda\x75\xa0\x0a\x3a\x30\xe1\xf8\x97\x32\x16\x2b\x00\x75\x85\xee\x62\x46\xef\xd3\x85\xb5\x6b\x60\xbe\xf2\x30\x7a\x8c\x0b\x4b\xa6\xd0\xf9\x64\x42\xe7\x07\x41\x41\xe3\x2c\x5d\xf9\x6d\xe9\x39\x98\x3b\x3b\x5d\x67\xd4\x5c\xed\xf2\xf0\x48\x7b\xbd\x2d\x31\xdd\x3f\x34\xad\x44\x76\x51\x9a\x56\x22\xa7\x95\xc8\x69\x25\xf2\xe1\x56\x22\x1f\x00\x32\x6a\x73\x92\xed\xe1\xc6\x7d\x9f\x49\x2c\x69\x7e\xc8\x31\x4c\x0c\xb4\xf2\x54\x3b\x79\x3b\x9e\x4d\xb4\xd1\x18\x3e\x5f\x9a\x93\xa2\x11\xc3\xda\x27\x0b\xaf\x37\x2e\x5c\x37\xfb\xeb\x9a\xd6\xc3\xac\xc3\xcc\xf8\x1e\x5b\x9d\xac\x22\x64\xb7\xed\x26\xb8\xf3\xb9\x3c\xbb\x1f\xe2\xb0\x22\x77\x43\x6a\x62\x29\x39\x59\xa6\xe6\xe5\xcd\x7b\x83\xc0\x5b\x8e\x93\x64\xac\xeb\xca\x4f\x65\xac\x4a\xbc\x1e\xcd\x82\xfa\x3c\x70\x36\xb6\xb5\xed\x79\xef\xec\x68\x00\xff\x54\xfa\xb5\xe3\xf1\xdb\xe1\xbe\xce\x76\x17\xaf\x57\xb6\x6b\x89\x05\x09\xce\x52\xb9\x01\x2a\x49\xbe\xd9\xf4\xd2\xb8\x7a\xbf\x91\x02\xf3\x22\x8c\x13\xf2\x77\xd8\x8e\x43\x8b\xe1\x54\x6e\x5e\x9d\xc7\x49\x44\x02\x22\xc7\xa4\x79\x81\x85\xb8\x65\x3c\x1c\x93\xe6\x59\xa2\xf8\x1c\x51\x95\x05\xd9\x20\x00\x21\x7e\x60\x21\x58\xa9\x56\xff\xbe\xb6\x5a\x5e\x5b\x3f\x1f\xd6\xd3\x3c\xc4\x4d\xba\x99\xb4\x63\x6e\x7d\x3e\x3d\x57\xd2\x18\x5f\x47\xe8\xc3\x06\x8a\x68\x6c\x7f\x3b\x72\x0f\xe7\xe2\x77\x77\xf1\xd0\x99\xab\xdf\x2e\xfe\xd6\xbb\xcd\x1a\xb9\x90\xd1\xaf\xf2\x38\x3d\xdb\x74\xf8\xeb\xe3\xda\xe8\x2a\x62\xb7\xda\x1b\x07\xa9\xdc\x30\x5e\xbc\x68\xfb\x6b\x9f\x97\xf1\xc6\xb1\xd8\x5c\x29\x1e\x49\x30\xc5\xf7\xde\xad\x91\x42\xf9\xdd\xed\x89\x80\x25\xbe\x37\xd7\xe7\x32\x5c\xe6\x35\xac\xd4\x0c\x2d\xf7\x90\xc4\xe3\xf5\xe3\x2f\x7f\x54\x18\x88\xe3\x61\x47\x85\x64\x7f\xc0\xd7\x3f\x1a\x92\x42\xe9\xc7\x1e\x0d\x95\x76\xa7\x51\xa0\x8f\x02\x1b\x46\x9e\x06\x42\xd1\xf2\x01\x07\x02\xde\xe9\x7d\x1a\x0b\xa7\x32\x16\xcc\xc0\xee\xc4\x90\xd2\x5f\x6f\x98\x54\x5d\xf2\x95\xe1\xa7\x69\x10\x3a\x06\xe1\x65\xb3\x17\x47\x58\x78\xd0\x45\xd6\x5b\xd5\x5f\x25\x1d\x71\x49\xa6\x7a\x64\xda\xd0\x6f\xc7\x3a\x4c\xe3\x09\xc0\x6e\x96\x2c\xa7\xa7\x77\x34\x10\x05\x08\x21\x44\x92\x65\x77\xdf\x20\x5c\xbc\xe7\x97\x3f\xf4\x1a\x45\xd6\xe7\x27\x4a\xde\x74\x27\x66\x11\x7d\x70\xba\xd3\x78\xf9\x1e\x0d\xca\xc8\x39\xde\x7c\xb3\xa6\xe1\xbc\xd7\xc1\x6a\x6f\xb3\x0e\x52\xbe\xe4\x98\x8a\x15\x70\x94\x70\x26\x59\xc0\xa2\xf2\x1c\xfb\xd9\xc5\xf9\xbc\xd5\x92\x9c\xa3\xdf\xe6\x1e\xb3\x0d\x49\xba\x87\x50\x5f\x84\xfe\xe9\xd6\xf8\xbb\xe6\xf0\x7a\xeb\xa6\x65\x3b\x86\x8b\x79\x93\xf5\x59\x20\x6e\xb4\xa7\x44\xf4\x3f\xa5\xfe\x67\x42\x12\xdb\xd3\xe7\xbb\xa5\xa3\x8c\x5c\x2b\x97\xbb\xbb\x7f\x8e\xc5\x6e\xed\x43\x5c\xbf\x74\xc8\x8f\xff\xe6\xd6\xbe\x91\xb6\xf5\x95\xe4\xed\x93\xc4\xa8\x5b\xf9\x76\x4d\x35\xb7\xd8\x8c\xb6\x7d\xaf\x72\xe0\xb6\xbd\x01\x63\x9e\x76\xab\x1a\x32\x76\xe4\x8c\x76\xc2\xad\x6c\xa2\x65\xf7\xcf\xf8\xa7\xda\x2a\xb9\x8c\x3d\x3c\xa3\x9d\x64\x33\xe5\x1a\xb5\x2d\xfb\x86\xa2\x5a\x7f\x19\x5b\x7f\xc6\x3f\xd1\x53\xd3\xe2\x41\x5b\xd3\x4f\xf0\xec\xb0\x42\x73\x43\xd2\x68\x27\xd3\x6a\x6a\x34\xf6\x4e\x1e\x52\x8b\x87\x6c\xcc\xae\x44\xfb\x9e\xa7\x51\x4f\x9d\x55\x03\x81\x8e\x67\xfc\xb4\x69\xf0\x3a\x18\xf2\x40\xd0\xf6\xa8\x34\xe3\xc9\x98\xaf\xf6\xda\x24\xd3\xeb\x60\xb9\x0e\xd3\x1f\xa9\xff\xee\x1f\xfd\x37\x00\x00\xff\xff\x69\x5d\x0a\x6a\x39\x9d\x00\x00") - -func v2SchemaJSONBytes() ([]byte, error) { - return bindataRead( - _v2SchemaJSON, - "v2/schema.json", - ) -} - -func v2SchemaJSON() (*asset, error) { - bytes, err := v2SchemaJSONBytes() - if err != nil { - return nil, err - } - - info := bindataFileInfo{name: "v2/schema.json", size: 40249, mode: os.FileMode(420), modTime: time.Unix(1482389892, 0)} - a := &asset{bytes: bytes, info: info} - return a, nil -} - -// Asset loads and returns the asset for the given name. -// It returns an error if the asset could not be found or -// could not be loaded. -func Asset(name string) ([]byte, error) { - cannonicalName := strings.Replace(name, "\\", "/", -1) - if f, ok := _bindata[cannonicalName]; ok { - a, err := f() - if err != nil { - return nil, fmt.Errorf("Asset %s can't read by error: %v", name, err) - } - return a.bytes, nil - } - return nil, fmt.Errorf("Asset %s not found", name) -} - -// MustAsset is like Asset but panics when Asset would return an error. -// It simplifies safe initialization of global variables. -func MustAsset(name string) []byte { - a, err := Asset(name) - if err != nil { - panic("asset: Asset(" + name + "): " + err.Error()) - } - - return a -} - -// AssetInfo loads and returns the asset info for the given name. -// It returns an error if the asset could not be found or -// could not be loaded. -func AssetInfo(name string) (os.FileInfo, error) { - cannonicalName := strings.Replace(name, "\\", "/", -1) - if f, ok := _bindata[cannonicalName]; ok { - a, err := f() - if err != nil { - return nil, fmt.Errorf("AssetInfo %s can't read by error: %v", name, err) - } - return a.info, nil - } - return nil, fmt.Errorf("AssetInfo %s not found", name) -} - -// AssetNames returns the names of the assets. -func AssetNames() []string { - names := make([]string, 0, len(_bindata)) - for name := range _bindata { - names = append(names, name) - } - return names -} - -// _bindata is a table, holding each asset generator, mapped to its name. -var _bindata = map[string]func() (*asset, error){ - "jsonschema-draft-04.json": jsonschemaDraft04JSON, - "v2/schema.json": v2SchemaJSON, -} - -// AssetDir returns the file names below a certain -// directory embedded in the file by go-bindata. -// For example if you run go-bindata on data/... and data contains the -// following hierarchy: -// data/ -// foo.txt -// img/ -// a.png -// b.png -// then AssetDir("data") would return []string{"foo.txt", "img"} -// AssetDir("data/img") would return []string{"a.png", "b.png"} -// AssetDir("foo.txt") and AssetDir("notexist") would return an error -// AssetDir("") will return []string{"data"}. -func AssetDir(name string) ([]string, error) { - node := _bintree - if len(name) != 0 { - cannonicalName := strings.Replace(name, "\\", "/", -1) - pathList := strings.Split(cannonicalName, "/") - for _, p := range pathList { - node = node.Children[p] - if node == nil { - return nil, fmt.Errorf("Asset %s not found", name) - } - } - } - if node.Func != nil { - return nil, fmt.Errorf("Asset %s not found", name) - } - rv := make([]string, 0, len(node.Children)) - for childName := range node.Children { - rv = append(rv, childName) - } - return rv, nil -} - -type bintree struct { - Func func() (*asset, error) - Children map[string]*bintree -} -var _bintree = &bintree{nil, map[string]*bintree{ - "jsonschema-draft-04.json": &bintree{jsonschemaDraft04JSON, map[string]*bintree{}}, - "v2": &bintree{nil, map[string]*bintree{ - "schema.json": &bintree{v2SchemaJSON, map[string]*bintree{}}, - }}, -}} - -// RestoreAsset restores an asset under the given directory -func RestoreAsset(dir, name string) error { - data, err := Asset(name) - if err != nil { - return err - } - info, err := AssetInfo(name) - if err != nil { - return err - } - err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) - if err != nil { - return err - } - err = ioutil.WriteFile(_filePath(dir, name), data, info.Mode()) - if err != nil { - return err - } - err = os.Chtimes(_filePath(dir, name), info.ModTime(), info.ModTime()) - if err != nil { - return err - } - return nil -} - -// RestoreAssets restores an asset under the given directory recursively -func RestoreAssets(dir, name string) error { - children, err := AssetDir(name) - // File - if err != nil { - return RestoreAsset(dir, name) - } - // Dir - for _, child := range children { - err = RestoreAssets(dir, filepath.Join(name, child)) - if err != nil { - return err - } - } - return nil -} - -func _filePath(dir, name string) string { - cannonicalName := strings.Replace(name, "\\", "/", -1) - return filepath.Join(append([]string{dir}, strings.Split(cannonicalName, "/")...)...) -} - diff --git a/vendor/github.com/go-openapi/spec/contact_info.go b/vendor/github.com/go-openapi/spec/contact_info.go deleted file mode 100644 index f285970aa1..0000000000 --- a/vendor/github.com/go-openapi/spec/contact_info.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -// ContactInfo contact information for the exposed API. -// -// For more information: http://goo.gl/8us55a#contactObject -type ContactInfo struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` - Email string `json:"email,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/expander.go b/vendor/github.com/go-openapi/spec/expander.go deleted file mode 100644 index b4429a21c8..0000000000 --- a/vendor/github.com/go-openapi/spec/expander.go +++ /dev/null @@ -1,900 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "fmt" - "log" - "net/url" - "os" - "path/filepath" - "reflect" - "strings" - "sync" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -var ( - // Debug enables logging when SWAGGER_DEBUG env var is not empty - Debug = os.Getenv("SWAGGER_DEBUG") != "" -) - -// ExpandOptions provides options for expand. -type ExpandOptions struct { - RelativeBase string - SkipSchemas bool - ContinueOnError bool -} - -// ResolutionCache a cache for resolving urls -type ResolutionCache interface { - Get(string) (interface{}, bool) - Set(string, interface{}) -} - -type simpleCache struct { - lock sync.Mutex - store map[string]interface{} -} - -var resCache ResolutionCache - -func init() { - resCache = initResolutionCache() -} - -func initResolutionCache() ResolutionCache { - return &simpleCache{store: map[string]interface{}{ - "http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(), - "http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(), - }} -} - -func (s *simpleCache) Get(uri string) (interface{}, bool) { - debugLog("getting %q from resolution cache", uri) - s.lock.Lock() - v, ok := s.store[uri] - debugLog("got %q from resolution cache: %t", uri, ok) - - s.lock.Unlock() - return v, ok -} - -func (s *simpleCache) Set(uri string, data interface{}) { - s.lock.Lock() - s.store[uri] = data - s.lock.Unlock() -} - -// ResolveRefWithBase resolves a reference against a context root with preservation of base path -func ResolveRefWithBase(root interface{}, ref *Ref, opts *ExpandOptions) (*Schema, error) { - resolver, err := defaultSchemaLoader(root, nil, opts, nil) - if err != nil { - return nil, err - } - - result := new(Schema) - if err := resolver.Resolve(ref, result); err != nil { - return nil, err - } - return result, nil -} - -// ResolveRef resolves a reference against a context root -func ResolveRef(root interface{}, ref *Ref) (*Schema, error) { - return ResolveRefWithBase(root, ref, nil) -} - -// ResolveParameter resolves a paramter reference against a context root -func ResolveParameter(root interface{}, ref Ref) (*Parameter, error) { - return ResolveParameterWithBase(root, ref, nil) -} - -// ResolveParameterWithBase resolves a paramter reference against a context root and base path -func ResolveParameterWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Parameter, error) { - resolver, err := defaultSchemaLoader(root, nil, opts, nil) - if err != nil { - return nil, err - } - - result := new(Parameter) - if err := resolver.Resolve(&ref, result); err != nil { - return nil, err - } - return result, nil -} - -// ResolveResponse resolves response a reference against a context root -func ResolveResponse(root interface{}, ref Ref) (*Response, error) { - return ResolveResponseWithBase(root, ref, nil) -} - -// ResolveResponseWithBase resolves response a reference against a context root and base path -func ResolveResponseWithBase(root interface{}, ref Ref, opts *ExpandOptions) (*Response, error) { - resolver, err := defaultSchemaLoader(root, nil, opts, nil) - if err != nil { - return nil, err - } - - result := new(Response) - if err := resolver.Resolve(&ref, result); err != nil { - return nil, err - } - return result, nil -} - -// ResolveItems resolves header and parameter items reference against a context root and base path -func ResolveItems(root interface{}, ref Ref, opts *ExpandOptions) (*Items, error) { - resolver, err := defaultSchemaLoader(root, nil, opts, nil) - if err != nil { - return nil, err - } - - result := new(Items) - if err := resolver.Resolve(&ref, result); err != nil { - return nil, err - } - return result, nil -} - -// ResolvePathItem resolves response a path item against a context root and base path -func ResolvePathItem(root interface{}, ref Ref, opts *ExpandOptions) (*PathItem, error) { - resolver, err := defaultSchemaLoader(root, nil, opts, nil) - if err != nil { - return nil, err - } - - result := new(PathItem) - if err := resolver.Resolve(&ref, result); err != nil { - return nil, err - } - return result, nil -} - -type schemaLoader struct { - loadingRef *Ref - startingRef *Ref - currentRef *Ref - root interface{} - options *ExpandOptions - cache ResolutionCache - loadDoc func(string) (json.RawMessage, error) -} - -var idPtr, _ = jsonpointer.New("/id") -var refPtr, _ = jsonpointer.New("/$ref") - -// PathLoader function to use when loading remote refs -var PathLoader func(string) (json.RawMessage, error) - -func init() { - PathLoader = func(path string) (json.RawMessage, error) { - data, err := swag.LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - return json.RawMessage(data), nil - } -} - -func defaultSchemaLoader( - root interface{}, - ref *Ref, - expandOptions *ExpandOptions, - cache ResolutionCache) (*schemaLoader, error) { - - if cache == nil { - cache = resCache - } - if expandOptions == nil { - expandOptions = &ExpandOptions{} - } - - var ptr *jsonpointer.Pointer - if ref != nil { - ptr = ref.GetPointer() - } - - currentRef := nextRef(root, ref, ptr) - - return &schemaLoader{ - loadingRef: ref, - startingRef: ref, - currentRef: currentRef, - root: root, - options: expandOptions, - cache: cache, - loadDoc: func(path string) (json.RawMessage, error) { - debugLog("fetching document at %q", path) - return PathLoader(path) - }, - }, nil -} - -func idFromNode(node interface{}) (*Ref, error) { - if idValue, _, err := idPtr.Get(node); err == nil { - if refStr, ok := idValue.(string); ok && refStr != "" { - idRef, err := NewRef(refStr) - if err != nil { - return nil, err - } - return &idRef, nil - } - } - return nil, nil -} - -func nextRef(startingNode interface{}, startingRef *Ref, ptr *jsonpointer.Pointer) *Ref { - if startingRef == nil { - return nil - } - - if ptr == nil { - return startingRef - } - - ret := startingRef - var idRef *Ref - node := startingNode - - for _, tok := range ptr.DecodedTokens() { - node, _, _ = jsonpointer.GetForToken(node, tok) - if node == nil { - break - } - - idRef, _ = idFromNode(node) - if idRef != nil { - nw, err := ret.Inherits(*idRef) - if err != nil { - break - } - ret = nw - } - - refRef, _, _ := refPtr.Get(node) - if refRef != nil { - var rf Ref - switch value := refRef.(type) { - case string: - rf, _ = NewRef(value) - } - nw, err := ret.Inherits(rf) - if err != nil { - break - } - nwURL := nw.GetURL() - if nwURL.Scheme == "file" || (nwURL.Scheme == "" && nwURL.Host == "") { - nwpt := filepath.ToSlash(nwURL.Path) - if filepath.IsAbs(nwpt) { - _, err := os.Stat(nwpt) - if err != nil { - nwURL.Path = filepath.Join(".", nwpt) - } - } - } - - ret = nw - } - - } - - return ret -} - -func debugLog(msg string, args ...interface{}) { - if Debug { - log.Printf(msg, args...) - } -} - -func normalizeFileRef(ref *Ref, relativeBase string) *Ref { - refURL := ref.GetURL() - debugLog("normalizing %s against %s (%s)", ref.String(), relativeBase, refURL.String()) - if strings.HasPrefix(refURL.String(), "#") { - return ref - } - - if refURL.Scheme == "file" || (refURL.Scheme == "" && refURL.Host == "") { - filePath := refURL.Path - debugLog("normalizing file path: %s", filePath) - - if !filepath.IsAbs(filepath.FromSlash(filePath)) && len(relativeBase) != 0 { - debugLog("joining %s with %s", relativeBase, filePath) - if fi, err := os.Stat(filepath.FromSlash(relativeBase)); err == nil { - if !fi.IsDir() { - relativeBase = filepath.Dir(filepath.FromSlash(relativeBase)) - } - } - filePath = filepath.Join(filepath.FromSlash(relativeBase), filepath.FromSlash(filePath)) - } - if !filepath.IsAbs(filepath.FromSlash(filePath)) { - pwd, err := os.Getwd() - if err == nil { - debugLog("joining cwd %s with %s", pwd, filePath) - filePath = filepath.Join(pwd, filepath.FromSlash(filePath)) - } - } - - debugLog("cleaning %s", filePath) - filePath = filepath.Clean(filepath.FromSlash(filePath)) - _, err := os.Stat(filepath.FromSlash(filePath)) - if err == nil { - debugLog("rewriting url %s to scheme \"\" path %s", refURL.String(), filePath) - slp := filepath.FromSlash(filePath) - if filepath.IsAbs(slp) && filepath.Separator == '\\' && len(slp) > 1 && slp[1] == ':' && ('a' <= slp[0] && slp[0] <= 'z' || 'A' <= slp[0] && slp[0] <= 'Z') { - slp = slp[2:] - } - refURL.Scheme = "" - refURL.Path = filepath.ToSlash(slp) - debugLog("new url with joined filepath: %s", refURL.String()) - *ref = MustCreateRef(refURL.String()) - } - } - - debugLog("refurl: %s", ref.GetURL().String()) - return ref -} - -func (r *schemaLoader) resolveRef(currentRef, ref *Ref, node, target interface{}) error { - - tgt := reflect.ValueOf(target) - if tgt.Kind() != reflect.Ptr { - return fmt.Errorf("resolve ref: target needs to be a pointer") - } - - oldRef := currentRef - - if currentRef != nil { - debugLog("resolve ref current %s new %s", currentRef.String(), ref.String()) - nextRef := nextRef(node, ref, currentRef.GetPointer()) - if nextRef == nil || nextRef.GetURL() == nil { - return nil - } - var err error - currentRef, err = currentRef.Inherits(*nextRef) - debugLog("resolved ref current %s", currentRef.String()) - if err != nil { - return err - } - } - - if currentRef == nil { - currentRef = ref - } - - refURL := currentRef.GetURL() - if refURL == nil { - return nil - } - if currentRef.IsRoot() { - nv := reflect.ValueOf(node) - reflect.Indirect(tgt).Set(reflect.Indirect(nv)) - return nil - } - - if strings.HasPrefix(refURL.String(), "#") { - res, _, err := ref.GetPointer().Get(node) - if err != nil { - res, _, err = ref.GetPointer().Get(r.root) - if err != nil { - return err - } - } - rv := reflect.Indirect(reflect.ValueOf(res)) - tgtType := reflect.Indirect(tgt).Type() - if rv.Type().AssignableTo(tgtType) { - reflect.Indirect(tgt).Set(reflect.Indirect(reflect.ValueOf(res))) - } else { - if err := swag.DynamicJSONToStruct(rv.Interface(), target); err != nil { - return err - } - } - - return nil - } - - relativeBase := "" - if r.options != nil && r.options.RelativeBase != "" { - relativeBase = r.options.RelativeBase - } - normalizeFileRef(currentRef, relativeBase) - debugLog("current ref normalized file: %s", currentRef.String()) - normalizeFileRef(ref, relativeBase) - debugLog("ref normalized file: %s", currentRef.String()) - - data, _, _, err := r.load(currentRef.GetURL()) - if err != nil { - return err - } - - if ((oldRef == nil && currentRef != nil) || - (oldRef != nil && currentRef == nil) || - oldRef.String() != currentRef.String()) && - ((oldRef == nil && ref != nil) || - (oldRef != nil && ref == nil) || - (oldRef.String() != ref.String())) { - - return r.resolveRef(currentRef, ref, data, target) - } - - var res interface{} - if currentRef.String() != "" { - res, _, err = currentRef.GetPointer().Get(data) - if err != nil { - if strings.HasPrefix(ref.String(), "#") { - if r.loadingRef != nil { - rr, er := r.loadingRef.Inherits(*ref) - if er != nil { - return er - } - refURL = rr.GetURL() - - data, _, _, err = r.load(refURL) - if err != nil { - return err - } - } else { - data = r.root - } - } - - res, _, err = ref.GetPointer().Get(data) - if err != nil { - return err - } - } - } else { - res = data - } - - if err := swag.DynamicJSONToStruct(res, target); err != nil { - return err - } - - r.currentRef = currentRef - - return nil -} - -func (r *schemaLoader) load(refURL *url.URL) (interface{}, url.URL, bool, error) { - debugLog("loading schema from url: %s", refURL) - toFetch := *refURL - toFetch.Fragment = "" - - data, fromCache := r.cache.Get(toFetch.String()) - if !fromCache { - b, err := r.loadDoc(toFetch.String()) - if err != nil { - return nil, url.URL{}, false, err - } - - if err := json.Unmarshal(b, &data); err != nil { - return nil, url.URL{}, false, err - } - r.cache.Set(toFetch.String(), data) - } - - return data, toFetch, fromCache, nil -} - -func (r *schemaLoader) Resolve(ref *Ref, target interface{}) error { - return r.resolveRef(r.currentRef, ref, r.root, target) -} - -func (r *schemaLoader) reset() { - ref := r.startingRef - - var ptr *jsonpointer.Pointer - if ref != nil { - ptr = ref.GetPointer() - } - - r.currentRef = nextRef(r.root, ref, ptr) -} - -// ExpandSpec expands the references in a swagger spec -func ExpandSpec(spec *Swagger, options *ExpandOptions) error { - resolver, err := defaultSchemaLoader(spec, nil, options, nil) - // Just in case this ever returns an error. - if shouldStopOnError(err, resolver.options) { - return err - } - - if options == nil || !options.SkipSchemas { - for key, definition := range spec.Definitions { - var def *Schema - var err error - if def, err = expandSchema(definition, []string{"#/definitions/" + key}, resolver); shouldStopOnError(err, resolver.options) { - return err - } - resolver.reset() - spec.Definitions[key] = *def - } - } - - for key, parameter := range spec.Parameters { - if err := expandParameter(¶meter, resolver); shouldStopOnError(err, resolver.options) { - return err - } - spec.Parameters[key] = parameter - } - - for key, response := range spec.Responses { - if err := expandResponse(&response, resolver); shouldStopOnError(err, resolver.options) { - return err - } - spec.Responses[key] = response - } - - if spec.Paths != nil { - for key, path := range spec.Paths.Paths { - if err := expandPathItem(&path, resolver); shouldStopOnError(err, resolver.options) { - return err - } - spec.Paths.Paths[key] = path - } - } - - return nil -} - -func shouldStopOnError(err error, opts *ExpandOptions) bool { - if err != nil && !opts.ContinueOnError { - return true - } - - if err != nil { - log.Println(err) - } - - return false -} - -// ExpandSchema expands the refs in the schema object -func ExpandSchema(schema *Schema, root interface{}, cache ResolutionCache) error { - return ExpandSchemaWithBasePath(schema, root, cache, nil) -} - -// ExpandSchemaWithBasePath expands the refs in the schema object, base path configured through expand options -func ExpandSchemaWithBasePath(schema *Schema, root interface{}, cache ResolutionCache, opts *ExpandOptions) error { - if schema == nil { - return nil - } - if root == nil { - root = schema - } - - nrr, _ := NewRef(schema.ID) - var rrr *Ref - if nrr.String() != "" { - switch rt := root.(type) { - case *Schema: - rid, _ := NewRef(rt.ID) - rrr, _ = rid.Inherits(nrr) - case *Swagger: - rid, _ := NewRef(rt.ID) - rrr, _ = rid.Inherits(nrr) - } - } - - resolver, err := defaultSchemaLoader(root, rrr, opts, cache) - if err != nil { - return err - } - - refs := []string{""} - if rrr != nil { - refs[0] = rrr.String() - } - var s *Schema - if s, err = expandSchema(*schema, refs, resolver); err != nil { - return err - } - *schema = *s - return nil -} - -func expandItems(target Schema, parentRefs []string, resolver *schemaLoader) (*Schema, error) { - if target.Items != nil { - if target.Items.Schema != nil { - t, err := expandSchema(*target.Items.Schema, parentRefs, resolver) - if err != nil { - if target.Items.Schema.ID == "" { - target.Items.Schema.ID = target.ID - if err != nil { - t, err = expandSchema(*target.Items.Schema, parentRefs, resolver) - if err != nil { - return nil, err - } - } - } - } - *target.Items.Schema = *t - } - for i := range target.Items.Schemas { - t, err := expandSchema(target.Items.Schemas[i], parentRefs, resolver) - if err != nil { - return nil, err - } - target.Items.Schemas[i] = *t - } - } - return &target, nil -} - -func expandSchema(target Schema, parentRefs []string, resolver *schemaLoader) (*Schema, error) { - if target.Ref.String() == "" && target.Ref.IsRoot() { - debugLog("skipping expand schema for no ref and root: %v", resolver.root) - - return resolver.root.(*Schema), nil - } - - // t is the new expanded schema - var t *Schema - - for target.Ref.String() != "" { - if swag.ContainsStringsCI(parentRefs, target.Ref.String()) { - return &target, nil - } - - if err := resolver.Resolve(&target.Ref, &t); shouldStopOnError(err, resolver.options) { - return &target, err - } - - if swag.ContainsStringsCI(parentRefs, target.Ref.String()) { - debugLog("ref already exists in parent") - return &target, nil - } - parentRefs = append(parentRefs, target.Ref.String()) - if t != nil { - target = *t - } - } - - t, err := expandItems(target, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target = *t - } - - for i := range target.AllOf { - t, err := expandSchema(target.AllOf[i], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.AllOf[i] = *t - } - } - for i := range target.AnyOf { - t, err := expandSchema(target.AnyOf[i], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - target.AnyOf[i] = *t - } - for i := range target.OneOf { - t, err := expandSchema(target.OneOf[i], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.OneOf[i] = *t - } - } - if target.Not != nil { - t, err := expandSchema(*target.Not, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.Not = *t - } - } - for k := range target.Properties { - t, err := expandSchema(target.Properties[k], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.Properties[k] = *t - } - } - if target.AdditionalProperties != nil && target.AdditionalProperties.Schema != nil { - t, err := expandSchema(*target.AdditionalProperties.Schema, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.AdditionalProperties.Schema = *t - } - } - for k := range target.PatternProperties { - t, err := expandSchema(target.PatternProperties[k], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.PatternProperties[k] = *t - } - } - for k := range target.Dependencies { - if target.Dependencies[k].Schema != nil { - t, err := expandSchema(*target.Dependencies[k].Schema, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.Dependencies[k].Schema = *t - } - } - } - if target.AdditionalItems != nil && target.AdditionalItems.Schema != nil { - t, err := expandSchema(*target.AdditionalItems.Schema, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - *target.AdditionalItems.Schema = *t - } - } - for k := range target.Definitions { - t, err := expandSchema(target.Definitions[k], parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return &target, err - } - if t != nil { - target.Definitions[k] = *t - } - } - return &target, nil -} - -func expandPathItem(pathItem *PathItem, resolver *schemaLoader) error { - if pathItem == nil { - return nil - } - - if pathItem.Ref.String() != "" { - if err := resolver.Resolve(&pathItem.Ref, &pathItem); err != nil { - return err - } - resolver.reset() - pathItem.Ref = Ref{} - } - - for idx := range pathItem.Parameters { - if err := expandParameter(&(pathItem.Parameters[idx]), resolver); shouldStopOnError(err, resolver.options) { - return err - } - } - if err := expandOperation(pathItem.Get, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Head, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Options, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Put, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Post, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Patch, resolver); shouldStopOnError(err, resolver.options) { - return err - } - if err := expandOperation(pathItem.Delete, resolver); shouldStopOnError(err, resolver.options) { - return err - } - return nil -} - -func expandOperation(op *Operation, resolver *schemaLoader) error { - if op == nil { - return nil - } - - for i, param := range op.Parameters { - if err := expandParameter(¶m, resolver); shouldStopOnError(err, resolver.options) { - return err - } - op.Parameters[i] = param - } - - if op.Responses != nil { - responses := op.Responses - if err := expandResponse(responses.Default, resolver); shouldStopOnError(err, resolver.options) { - return err - } - for code, response := range responses.StatusCodeResponses { - if err := expandResponse(&response, resolver); shouldStopOnError(err, resolver.options) { - return err - } - responses.StatusCodeResponses[code] = response - } - } - return nil -} - -func expandResponse(response *Response, resolver *schemaLoader) error { - if response == nil { - return nil - } - - var parentRefs []string - - if response.Ref.String() != "" { - parentRefs = append(parentRefs, response.Ref.String()) - if err := resolver.Resolve(&response.Ref, response); shouldStopOnError(err, resolver.options) { - return err - } - resolver.reset() - response.Ref = Ref{} - } - - if !resolver.options.SkipSchemas && response.Schema != nil { - parentRefs = append(parentRefs, response.Schema.Ref.String()) - debugLog("response ref: %s", response.Schema.Ref) - if err := resolver.Resolve(&response.Schema.Ref, &response.Schema); shouldStopOnError(err, resolver.options) { - return err - } - s, err := expandSchema(*response.Schema, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return err - } - resolver.reset() - *response.Schema = *s - } - return nil -} - -func expandParameter(parameter *Parameter, resolver *schemaLoader) error { - if parameter == nil { - return nil - } - - var parentRefs []string - - if parameter.Ref.String() != "" { - parentRefs = append(parentRefs, parameter.Ref.String()) - if err := resolver.Resolve(¶meter.Ref, parameter); shouldStopOnError(err, resolver.options) { - return err - } - resolver.reset() - parameter.Ref = Ref{} - } - if !resolver.options.SkipSchemas && parameter.Schema != nil { - parentRefs = append(parentRefs, parameter.Schema.Ref.String()) - if err := resolver.Resolve(¶meter.Schema.Ref, ¶meter.Schema); shouldStopOnError(err, resolver.options) { - return err - } - s, err := expandSchema(*parameter.Schema, parentRefs, resolver) - if shouldStopOnError(err, resolver.options) { - return err - } - resolver.reset() - *parameter.Schema = *s - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/external_docs.go b/vendor/github.com/go-openapi/spec/external_docs.go deleted file mode 100644 index 88add91b2b..0000000000 --- a/vendor/github.com/go-openapi/spec/external_docs.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -// ExternalDocumentation allows referencing an external resource for -// extended documentation. -// -// For more information: http://goo.gl/8us55a#externalDocumentationObject -type ExternalDocumentation struct { - Description string `json:"description,omitempty"` - URL string `json:"url,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/header.go b/vendor/github.com/go-openapi/spec/header.go deleted file mode 100644 index 85c4d454c1..0000000000 --- a/vendor/github.com/go-openapi/spec/header.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type HeaderProps struct { - Description string `json:"description,omitempty"` -} - -// Header describes a header for a response of the API -// -// For more information: http://goo.gl/8us55a#headerObject -type Header struct { - CommonValidations - SimpleSchema - VendorExtensible - HeaderProps -} - -// ResponseHeader creates a new header instance for use in a response -func ResponseHeader() *Header { - return new(Header) -} - -// WithDescription sets the description on this response, allows for chaining -func (h *Header) WithDescription(description string) *Header { - h.Description = description - return h -} - -// Typed a fluent builder method for the type of parameter -func (h *Header) Typed(tpe, format string) *Header { - h.Type = tpe - h.Format = format - return h -} - -// CollectionOf a fluent builder method for an array item -func (h *Header) CollectionOf(items *Items, format string) *Header { - h.Type = "array" - h.Items = items - h.CollectionFormat = format - return h -} - -// WithDefault sets the default value on this item -func (h *Header) WithDefault(defaultValue interface{}) *Header { - h.Default = defaultValue - return h -} - -// WithMaxLength sets a max length value -func (h *Header) WithMaxLength(max int64) *Header { - h.MaxLength = &max - return h -} - -// WithMinLength sets a min length value -func (h *Header) WithMinLength(min int64) *Header { - h.MinLength = &min - return h -} - -// WithPattern sets a pattern value -func (h *Header) WithPattern(pattern string) *Header { - h.Pattern = pattern - return h -} - -// WithMultipleOf sets a multiple of value -func (h *Header) WithMultipleOf(number float64) *Header { - h.MultipleOf = &number - return h -} - -// WithMaximum sets a maximum number value -func (h *Header) WithMaximum(max float64, exclusive bool) *Header { - h.Maximum = &max - h.ExclusiveMaximum = exclusive - return h -} - -// WithMinimum sets a minimum number value -func (h *Header) WithMinimum(min float64, exclusive bool) *Header { - h.Minimum = &min - h.ExclusiveMinimum = exclusive - return h -} - -// WithEnum sets a the enum values (replace) -func (h *Header) WithEnum(values ...interface{}) *Header { - h.Enum = append([]interface{}{}, values...) - return h -} - -// WithMaxItems sets the max items -func (h *Header) WithMaxItems(size int64) *Header { - h.MaxItems = &size - return h -} - -// WithMinItems sets the min items -func (h *Header) WithMinItems(size int64) *Header { - h.MinItems = &size - return h -} - -// UniqueValues dictates that this array can only have unique items -func (h *Header) UniqueValues() *Header { - h.UniqueItems = true - return h -} - -// AllowDuplicates this array can have duplicates -func (h *Header) AllowDuplicates() *Header { - h.UniqueItems = false - return h -} - -// MarshalJSON marshal this to JSON -func (h Header) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(h.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(h.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(h.HeaderProps) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2, b3), nil -} - -// UnmarshalJSON marshal this from JSON -func (h *Header) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &h.CommonValidations); err != nil { - return err - } - if err := json.Unmarshal(data, &h.SimpleSchema); err != nil { - return err - } - if err := json.Unmarshal(data, &h.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &h.HeaderProps); err != nil { - return err - } - return nil -} - -// JSONLookup look up a value by the json property name -func (p Header) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.HeaderProps, token) - return r, err -} diff --git a/vendor/github.com/go-openapi/spec/info.go b/vendor/github.com/go-openapi/spec/info.go deleted file mode 100644 index fb8b7c4ac5..0000000000 --- a/vendor/github.com/go-openapi/spec/info.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// Extensions vendor specific extensions -type Extensions map[string]interface{} - -// Add adds a value to these extensions -func (e Extensions) Add(key string, value interface{}) { - realKey := strings.ToLower(key) - e[realKey] = value -} - -// GetString gets a string value from the extensions -func (e Extensions) GetString(key string) (string, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - str, ok := v.(string) - return str, ok - } - return "", false -} - -// GetBool gets a string value from the extensions -func (e Extensions) GetBool(key string) (bool, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - str, ok := v.(bool) - return str, ok - } - return false, false -} - -// GetStringSlice gets a string value from the extensions -func (e Extensions) GetStringSlice(key string) ([]string, bool) { - if v, ok := e[strings.ToLower(key)]; ok { - arr, ok := v.([]interface{}) - if !ok { - return nil, false - } - var strs []string - for _, iface := range arr { - str, ok := iface.(string) - if !ok { - return nil, false - } - strs = append(strs, str) - } - return strs, ok - } - return nil, false -} - -// VendorExtensible composition block. -type VendorExtensible struct { - Extensions Extensions -} - -// AddExtension adds an extension to this extensible object -func (v *VendorExtensible) AddExtension(key string, value interface{}) { - if value == nil { - return - } - if v.Extensions == nil { - v.Extensions = make(map[string]interface{}) - } - v.Extensions.Add(key, value) -} - -// MarshalJSON marshals the extensions to json -func (v VendorExtensible) MarshalJSON() ([]byte, error) { - toser := make(map[string]interface{}) - for k, v := range v.Extensions { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - toser[k] = v - } - } - return json.Marshal(toser) -} - -// UnmarshalJSON for this extensible object -func (v *VendorExtensible) UnmarshalJSON(data []byte) error { - var d map[string]interface{} - if err := json.Unmarshal(data, &d); err != nil { - return err - } - for k, vv := range d { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - if v.Extensions == nil { - v.Extensions = map[string]interface{}{} - } - v.Extensions[k] = vv - } - } - return nil -} - -// InfoProps the properties for an info definition -type InfoProps struct { - Description string `json:"description,omitempty"` - Title string `json:"title,omitempty"` - TermsOfService string `json:"termsOfService,omitempty"` - Contact *ContactInfo `json:"contact,omitempty"` - License *License `json:"license,omitempty"` - Version string `json:"version,omitempty"` -} - -// Info object provides metadata about the API. -// The metadata can be used by the clients if needed, and can be presented in the Swagger-UI for convenience. -// -// For more information: http://goo.gl/8us55a#infoObject -type Info struct { - VendorExtensible - InfoProps -} - -// JSONLookup look up a value by the json property name -func (i Info) JSONLookup(token string) (interface{}, error) { - if ex, ok := i.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(i.InfoProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (i Info) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(i.InfoProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(i.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (i *Info) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &i.InfoProps); err != nil { - return err - } - if err := json.Unmarshal(data, &i.VendorExtensible); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/items.go b/vendor/github.com/go-openapi/spec/items.go deleted file mode 100644 index 46944fb699..0000000000 --- a/vendor/github.com/go-openapi/spec/items.go +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type SimpleSchema struct { - Type string `json:"type,omitempty"` - Format string `json:"format,omitempty"` - Items *Items `json:"items,omitempty"` - CollectionFormat string `json:"collectionFormat,omitempty"` - Default interface{} `json:"default,omitempty"` -} - -func (s *SimpleSchema) TypeName() string { - if s.Format != "" { - return s.Format - } - return s.Type -} - -func (s *SimpleSchema) ItemsTypeName() string { - if s.Items == nil { - return "" - } - return s.Items.TypeName() -} - -type CommonValidations struct { - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` -} - -// Items a limited subset of JSON-Schema's items object. -// It is used by parameter definitions that are not located in "body". -// -// For more information: http://goo.gl/8us55a#items-object -type Items struct { - Refable - CommonValidations - SimpleSchema - VendorExtensible -} - -// NewItems creates a new instance of items -func NewItems() *Items { - return &Items{} -} - -// Typed a fluent builder method for the type of item -func (i *Items) Typed(tpe, format string) *Items { - i.Type = tpe - i.Format = format - return i -} - -// CollectionOf a fluent builder method for an array item -func (i *Items) CollectionOf(items *Items, format string) *Items { - i.Type = "array" - i.Items = items - i.CollectionFormat = format - return i -} - -// WithDefault sets the default value on this item -func (i *Items) WithDefault(defaultValue interface{}) *Items { - i.Default = defaultValue - return i -} - -// WithMaxLength sets a max length value -func (i *Items) WithMaxLength(max int64) *Items { - i.MaxLength = &max - return i -} - -// WithMinLength sets a min length value -func (i *Items) WithMinLength(min int64) *Items { - i.MinLength = &min - return i -} - -// WithPattern sets a pattern value -func (i *Items) WithPattern(pattern string) *Items { - i.Pattern = pattern - return i -} - -// WithMultipleOf sets a multiple of value -func (i *Items) WithMultipleOf(number float64) *Items { - i.MultipleOf = &number - return i -} - -// WithMaximum sets a maximum number value -func (i *Items) WithMaximum(max float64, exclusive bool) *Items { - i.Maximum = &max - i.ExclusiveMaximum = exclusive - return i -} - -// WithMinimum sets a minimum number value -func (i *Items) WithMinimum(min float64, exclusive bool) *Items { - i.Minimum = &min - i.ExclusiveMinimum = exclusive - return i -} - -// WithEnum sets a the enum values (replace) -func (i *Items) WithEnum(values ...interface{}) *Items { - i.Enum = append([]interface{}{}, values...) - return i -} - -// WithMaxItems sets the max items -func (i *Items) WithMaxItems(size int64) *Items { - i.MaxItems = &size - return i -} - -// WithMinItems sets the min items -func (i *Items) WithMinItems(size int64) *Items { - i.MinItems = &size - return i -} - -// UniqueValues dictates that this array can only have unique items -func (i *Items) UniqueValues() *Items { - i.UniqueItems = true - return i -} - -// AllowDuplicates this array can have duplicates -func (i *Items) AllowDuplicates() *Items { - i.UniqueItems = false - return i -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (i *Items) UnmarshalJSON(data []byte) error { - var validations CommonValidations - if err := json.Unmarshal(data, &validations); err != nil { - return err - } - var ref Refable - if err := json.Unmarshal(data, &ref); err != nil { - return err - } - var simpleSchema SimpleSchema - if err := json.Unmarshal(data, &simpleSchema); err != nil { - return err - } - i.Refable = ref - i.CommonValidations = validations - i.SimpleSchema = simpleSchema - return nil -} - -// MarshalJSON converts this items object to JSON -func (i Items) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(i.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(i.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(i.Refable) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b3, b1, b2), nil -} - -// JSONLookup look up a value by the json property name -func (p Items) JSONLookup(token string) (interface{}, error) { - if token == "$ref" { - return &p.Ref, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - return r, err -} diff --git a/vendor/github.com/go-openapi/spec/license.go b/vendor/github.com/go-openapi/spec/license.go deleted file mode 100644 index f20961b4fd..0000000000 --- a/vendor/github.com/go-openapi/spec/license.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -// License information for the exposed API. -// -// For more information: http://goo.gl/8us55a#licenseObject -type License struct { - Name string `json:"name,omitempty"` - URL string `json:"url,omitempty"` -} diff --git a/vendor/github.com/go-openapi/spec/operation.go b/vendor/github.com/go-openapi/spec/operation.go deleted file mode 100644 index de1db6f020..0000000000 --- a/vendor/github.com/go-openapi/spec/operation.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type OperationProps struct { - Description string `json:"description,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] - Tags []string `json:"tags,omitempty"` - Summary string `json:"summary,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - ID string `json:"operationId,omitempty"` - Deprecated bool `json:"deprecated,omitempty"` - Security []map[string][]string `json:"security,omitempty"` - Parameters []Parameter `json:"parameters,omitempty"` - Responses *Responses `json:"responses,omitempty"` -} - -// Operation describes a single API operation on a path. -// -// For more information: http://goo.gl/8us55a#operationObject -type Operation struct { - VendorExtensible - OperationProps -} - -// SuccessResponse gets a success response model -func (o *Operation) SuccessResponse() (*Response, int, bool) { - if o.Responses == nil { - return nil, 0, false - } - - for k, v := range o.Responses.StatusCodeResponses { - if k/100 == 2 { - return &v, k, true - } - } - - return o.Responses.Default, 0, false -} - -// JSONLookup look up a value by the json property name -func (o Operation) JSONLookup(token string) (interface{}, error) { - if ex, ok := o.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(o.OperationProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (o *Operation) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &o.OperationProps); err != nil { - return err - } - if err := json.Unmarshal(data, &o.VendorExtensible); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (o Operation) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(o.OperationProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(o.VendorExtensible) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} - -// NewOperation creates a new operation instance. -// It expects an ID as parameter but not passing an ID is also valid. -func NewOperation(id string) *Operation { - op := new(Operation) - op.ID = id - return op -} - -// WithID sets the ID property on this operation, allows for chaining. -func (o *Operation) WithID(id string) *Operation { - o.ID = id - return o -} - -// WithDescription sets the description on this operation, allows for chaining -func (o *Operation) WithDescription(description string) *Operation { - o.Description = description - return o -} - -// WithSummary sets the summary on this operation, allows for chaining -func (o *Operation) WithSummary(summary string) *Operation { - o.Summary = summary - return o -} - -// WithExternalDocs sets/removes the external docs for/from this operation. -// When you pass empty strings as params the external documents will be removed. -// When you pass non-empty string as one value then those values will be used on the external docs object. -// So when you pass a non-empty description, you should also pass the url and vice versa. -func (o *Operation) WithExternalDocs(description, url string) *Operation { - if description == "" && url == "" { - o.ExternalDocs = nil - return o - } - - if o.ExternalDocs == nil { - o.ExternalDocs = &ExternalDocumentation{} - } - o.ExternalDocs.Description = description - o.ExternalDocs.URL = url - return o -} - -// Deprecate marks the operation as deprecated -func (o *Operation) Deprecate() *Operation { - o.Deprecated = true - return o -} - -// Undeprecate marks the operation as not deprected -func (o *Operation) Undeprecate() *Operation { - o.Deprecated = false - return o -} - -// WithConsumes adds media types for incoming body values -func (o *Operation) WithConsumes(mediaTypes ...string) *Operation { - o.Consumes = append(o.Consumes, mediaTypes...) - return o -} - -// WithProduces adds media types for outgoing body values -func (o *Operation) WithProduces(mediaTypes ...string) *Operation { - o.Produces = append(o.Produces, mediaTypes...) - return o -} - -// WithTags adds tags for this operation -func (o *Operation) WithTags(tags ...string) *Operation { - o.Tags = append(o.Tags, tags...) - return o -} - -// AddParam adds a parameter to this operation, when a parameter for that location -// and with that name already exists it will be replaced -func (o *Operation) AddParam(param *Parameter) *Operation { - if param == nil { - return o - } - - for i, p := range o.Parameters { - if p.Name == param.Name && p.In == param.In { - params := append(o.Parameters[:i], *param) - params = append(params, o.Parameters[i+1:]...) - o.Parameters = params - return o - } - } - - o.Parameters = append(o.Parameters, *param) - return o -} - -// RemoveParam removes a parameter from the operation -func (o *Operation) RemoveParam(name, in string) *Operation { - for i, p := range o.Parameters { - if p.Name == name && p.In == name { - o.Parameters = append(o.Parameters[:i], o.Parameters[i+1:]...) - return o - } - } - return o -} - -// SecuredWith adds a security scope to this operation. -func (o *Operation) SecuredWith(name string, scopes ...string) *Operation { - o.Security = append(o.Security, map[string][]string{name: scopes}) - return o -} - -// WithDefaultResponse adds a default response to the operation. -// Passing a nil value will remove the response -func (o *Operation) WithDefaultResponse(response *Response) *Operation { - return o.RespondsWith(0, response) -} - -// RespondsWith adds a status code response to the operation. -// When the code is 0 the value of the response will be used as default response value. -// When the value of the response is nil it will be removed from the operation -func (o *Operation) RespondsWith(code int, response *Response) *Operation { - if o.Responses == nil { - o.Responses = new(Responses) - } - if code == 0 { - o.Responses.Default = response - return o - } - if response == nil { - delete(o.Responses.StatusCodeResponses, code) - return o - } - if o.Responses.StatusCodeResponses == nil { - o.Responses.StatusCodeResponses = make(map[int]Response) - } - o.Responses.StatusCodeResponses[code] = *response - return o -} diff --git a/vendor/github.com/go-openapi/spec/parameter.go b/vendor/github.com/go-openapi/spec/parameter.go deleted file mode 100644 index 71aee1e806..0000000000 --- a/vendor/github.com/go-openapi/spec/parameter.go +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// QueryParam creates a query parameter -func QueryParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "query"}} -} - -// HeaderParam creates a header parameter, this is always required by default -func HeaderParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "header", Required: true}} -} - -// PathParam creates a path parameter, this is always required -func PathParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "path", Required: true}} -} - -// BodyParam creates a body parameter -func BodyParam(name string, schema *Schema) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "body", Schema: schema}, SimpleSchema: SimpleSchema{Type: "object"}} -} - -// FormDataParam creates a body parameter -func FormDataParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}} -} - -// FileParam creates a body parameter -func FileParam(name string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name, In: "formData"}, SimpleSchema: SimpleSchema{Type: "file"}} -} - -// SimpleArrayParam creates a param for a simple array (string, int, date etc) -func SimpleArrayParam(name, tpe, fmt string) *Parameter { - return &Parameter{ParamProps: ParamProps{Name: name}, SimpleSchema: SimpleSchema{Type: "array", CollectionFormat: "csv", Items: &Items{SimpleSchema: SimpleSchema{Type: "string", Format: fmt}}}} -} - -// ParamRef creates a parameter that's a json reference -func ParamRef(uri string) *Parameter { - p := new(Parameter) - p.Ref = MustCreateRef(uri) - return p -} - -type ParamProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - In string `json:"in,omitempty"` - Required bool `json:"required,omitempty"` - Schema *Schema `json:"schema,omitempty"` // when in == "body" - AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // when in == "query" || "formData" -} - -// Parameter a unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). -// -// There are five possible parameter types. -// * Path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. -// * Query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. -// * Header - Custom headers that are expected as part of the request. -// * Body - The payload that's appended to the HTTP request. Since there can only be one payload, there can only be *one* body parameter. The name of the body parameter has no effect on the parameter itself and is used for documentation purposes only. Since Form parameters are also in the payload, body and form parameters cannot exist together for the same operation. -// * Form - Used to describe the payload of an HTTP request when either `application/x-www-form-urlencoded` or `multipart/form-data` are used as the content type of the request (in Swagger's definition, the [`consumes`](#operationConsumes) property of an operation). This is the only parameter type that can be used to send files, thus supporting the `file` type. Since form parameters are sent in the payload, they cannot be declared together with a body parameter for the same operation. Form parameters have a different format based on the content-type used (for further details, consult http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4): -// * `application/x-www-form-urlencoded` - Similar to the format of Query parameters but as a payload. For example, `foo=1&bar=swagger` - both `foo` and `bar` are form parameters. This is normally used for simple parameters that are being transferred. -// * `multipart/form-data` - each parameter takes a section in the payload with an internal header. For example, for the header `Content-Disposition: form-data; name="submit-name"` the name of the parameter is `submit-name`. This type of form parameters is more commonly used for file transfers. -// -// For more information: http://goo.gl/8us55a#parameterObject -type Parameter struct { - Refable - CommonValidations - SimpleSchema - VendorExtensible - ParamProps -} - -// JSONLookup look up a value by the json property name -func (p Parameter) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - - r, _, err := jsonpointer.GetForToken(p.CommonValidations, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.SimpleSchema, token) - if err != nil && !strings.HasPrefix(err.Error(), "object has no field") { - return nil, err - } - if r != nil { - return r, nil - } - r, _, err = jsonpointer.GetForToken(p.ParamProps, token) - return r, err -} - -// WithDescription a fluent builder method for the description of the parameter -func (p *Parameter) WithDescription(description string) *Parameter { - p.Description = description - return p -} - -// Named a fluent builder method to override the name of the parameter -func (p *Parameter) Named(name string) *Parameter { - p.Name = name - return p -} - -// WithLocation a fluent builder method to override the location of the parameter -func (p *Parameter) WithLocation(in string) *Parameter { - p.In = in - return p -} - -// Typed a fluent builder method for the type of the parameter value -func (p *Parameter) Typed(tpe, format string) *Parameter { - p.Type = tpe - p.Format = format - return p -} - -// CollectionOf a fluent builder method for an array parameter -func (p *Parameter) CollectionOf(items *Items, format string) *Parameter { - p.Type = "array" - p.Items = items - p.CollectionFormat = format - return p -} - -// WithDefault sets the default value on this parameter -func (p *Parameter) WithDefault(defaultValue interface{}) *Parameter { - p.AsOptional() // with default implies optional - p.Default = defaultValue - return p -} - -// AllowsEmptyValues flags this parameter as being ok with empty values -func (p *Parameter) AllowsEmptyValues() *Parameter { - p.AllowEmptyValue = true - return p -} - -// NoEmptyValues flags this parameter as not liking empty values -func (p *Parameter) NoEmptyValues() *Parameter { - p.AllowEmptyValue = false - return p -} - -// AsOptional flags this parameter as optional -func (p *Parameter) AsOptional() *Parameter { - p.Required = false - return p -} - -// AsRequired flags this parameter as required -func (p *Parameter) AsRequired() *Parameter { - if p.Default != nil { // with a default required makes no sense - return p - } - p.Required = true - return p -} - -// WithMaxLength sets a max length value -func (p *Parameter) WithMaxLength(max int64) *Parameter { - p.MaxLength = &max - return p -} - -// WithMinLength sets a min length value -func (p *Parameter) WithMinLength(min int64) *Parameter { - p.MinLength = &min - return p -} - -// WithPattern sets a pattern value -func (p *Parameter) WithPattern(pattern string) *Parameter { - p.Pattern = pattern - return p -} - -// WithMultipleOf sets a multiple of value -func (p *Parameter) WithMultipleOf(number float64) *Parameter { - p.MultipleOf = &number - return p -} - -// WithMaximum sets a maximum number value -func (p *Parameter) WithMaximum(max float64, exclusive bool) *Parameter { - p.Maximum = &max - p.ExclusiveMaximum = exclusive - return p -} - -// WithMinimum sets a minimum number value -func (p *Parameter) WithMinimum(min float64, exclusive bool) *Parameter { - p.Minimum = &min - p.ExclusiveMinimum = exclusive - return p -} - -// WithEnum sets a the enum values (replace) -func (p *Parameter) WithEnum(values ...interface{}) *Parameter { - p.Enum = append([]interface{}{}, values...) - return p -} - -// WithMaxItems sets the max items -func (p *Parameter) WithMaxItems(size int64) *Parameter { - p.MaxItems = &size - return p -} - -// WithMinItems sets the min items -func (p *Parameter) WithMinItems(size int64) *Parameter { - p.MinItems = &size - return p -} - -// UniqueValues dictates that this array can only have unique items -func (p *Parameter) UniqueValues() *Parameter { - p.UniqueItems = true - return p -} - -// AllowDuplicates this array can have duplicates -func (p *Parameter) AllowDuplicates() *Parameter { - p.UniqueItems = false - return p -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *Parameter) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &p.CommonValidations); err != nil { - return err - } - if err := json.Unmarshal(data, &p.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &p.SimpleSchema); err != nil { - return err - } - if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &p.ParamProps); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p Parameter) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(p.CommonValidations) - if err != nil { - return nil, err - } - b2, err := json.Marshal(p.SimpleSchema) - if err != nil { - return nil, err - } - b3, err := json.Marshal(p.Refable) - if err != nil { - return nil, err - } - b4, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - b5, err := json.Marshal(p.ParamProps) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b3, b1, b2, b4, b5), nil -} diff --git a/vendor/github.com/go-openapi/spec/path_item.go b/vendor/github.com/go-openapi/spec/path_item.go deleted file mode 100644 index 9ab3ec5383..0000000000 --- a/vendor/github.com/go-openapi/spec/path_item.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// pathItemProps the path item specific properties -type PathItemProps struct { - Get *Operation `json:"get,omitempty"` - Put *Operation `json:"put,omitempty"` - Post *Operation `json:"post,omitempty"` - Delete *Operation `json:"delete,omitempty"` - Options *Operation `json:"options,omitempty"` - Head *Operation `json:"head,omitempty"` - Patch *Operation `json:"patch,omitempty"` - Parameters []Parameter `json:"parameters,omitempty"` -} - -// PathItem describes the operations available on a single path. -// A Path Item may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). -// The path itself is still exposed to the documentation viewer but they will -// not know which operations and parameters are available. -// -// For more information: http://goo.gl/8us55a#pathItemObject -type PathItem struct { - Refable - VendorExtensible - PathItemProps -} - -// JSONLookup look up a value by the json property name -func (p PathItem) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - r, _, err := jsonpointer.GetForToken(p.PathItemProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *PathItem) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &p.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &p.VendorExtensible); err != nil { - return err - } - if err := json.Unmarshal(data, &p.PathItemProps); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p PathItem) MarshalJSON() ([]byte, error) { - b3, err := json.Marshal(p.Refable) - if err != nil { - return nil, err - } - b4, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - b5, err := json.Marshal(p.PathItemProps) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b3, b4, b5) - return concated, nil -} diff --git a/vendor/github.com/go-openapi/spec/paths.go b/vendor/github.com/go-openapi/spec/paths.go deleted file mode 100644 index 9dc82a2901..0000000000 --- a/vendor/github.com/go-openapi/spec/paths.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "fmt" - "strings" - - "github.com/go-openapi/swag" -) - -// Paths holds the relative paths to the individual endpoints. -// The path is appended to the [`basePath`](http://goo.gl/8us55a#swaggerBasePath) in order -// to construct the full URL. -// The Paths may be empty, due to [ACL constraints](http://goo.gl/8us55a#securityFiltering). -// -// For more information: http://goo.gl/8us55a#pathsObject -type Paths struct { - VendorExtensible - Paths map[string]PathItem `json:"-"` // custom serializer to flatten this, each entry must start with "/" -} - -// JSONLookup look up a value by the json property name -func (p Paths) JSONLookup(token string) (interface{}, error) { - if pi, ok := p.Paths[token]; ok { - return &pi, nil - } - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - return nil, fmt.Errorf("object has no field %q", token) -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (p *Paths) UnmarshalJSON(data []byte) error { - var res map[string]json.RawMessage - if err := json.Unmarshal(data, &res); err != nil { - return err - } - for k, v := range res { - if strings.HasPrefix(strings.ToLower(k), "x-") { - if p.Extensions == nil { - p.Extensions = make(map[string]interface{}) - } - var d interface{} - if err := json.Unmarshal(v, &d); err != nil { - return err - } - p.Extensions[k] = d - } - if strings.HasPrefix(k, "/") { - if p.Paths == nil { - p.Paths = make(map[string]PathItem) - } - var pi PathItem - if err := json.Unmarshal(v, &pi); err != nil { - return err - } - p.Paths[k] = pi - } - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (p Paths) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(p.VendorExtensible) - if err != nil { - return nil, err - } - - pths := make(map[string]PathItem) - for k, v := range p.Paths { - if strings.HasPrefix(k, "/") { - pths[k] = v - } - } - b2, err := json.Marshal(pths) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} diff --git a/vendor/github.com/go-openapi/spec/ref.go b/vendor/github.com/go-openapi/spec/ref.go deleted file mode 100644 index 4833b87e2f..0000000000 --- a/vendor/github.com/go-openapi/spec/ref.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "net/http" - "os" - "path/filepath" - - "github.com/go-openapi/jsonreference" -) - -// Refable is a struct for things that accept a $ref property -type Refable struct { - Ref Ref -} - -// MarshalJSON marshals the ref to json -func (r Refable) MarshalJSON() ([]byte, error) { - return r.Ref.MarshalJSON() -} - -// UnmarshalJSON unmarshalss the ref from json -func (r *Refable) UnmarshalJSON(d []byte) error { - return json.Unmarshal(d, &r.Ref) -} - -// Ref represents a json reference that is potentially resolved -type Ref struct { - jsonreference.Ref -} - -// RemoteURI gets the remote uri part of the ref -func (r *Ref) RemoteURI() string { - if r.String() == "" { - return r.String() - } - - u := *r.GetURL() - u.Fragment = "" - return u.String() -} - -// IsValidURI returns true when the url the ref points to can be found -func (r *Ref) IsValidURI(basepaths ...string) bool { - if r.String() == "" { - return true - } - - v := r.RemoteURI() - if v == "" { - return true - } - - if r.HasFullURL { - rr, err := http.Get(v) - if err != nil { - return false - } - - return rr.StatusCode/100 == 2 - } - - if !(r.HasFileScheme || r.HasFullFilePath || r.HasURLPathOnly) { - return false - } - - // check for local file - pth := v - if r.HasURLPathOnly { - base := "." - if len(basepaths) > 0 { - base = filepath.Dir(filepath.Join(basepaths...)) - } - p, e := filepath.Abs(filepath.ToSlash(filepath.Join(base, pth))) - if e != nil { - return false - } - pth = p - } - - fi, err := os.Stat(filepath.ToSlash(pth)) - if err != nil { - return false - } - - return !fi.IsDir() -} - -// Inherits creates a new reference from a parent and a child -// If the child cannot inherit from the parent, an error is returned -func (r *Ref) Inherits(child Ref) (*Ref, error) { - ref, err := r.Ref.Inherits(child.Ref) - if err != nil { - return nil, err - } - return &Ref{Ref: *ref}, nil -} - -// NewRef creates a new instance of a ref object -// returns an error when the reference uri is an invalid uri -func NewRef(refURI string) (Ref, error) { - ref, err := jsonreference.New(refURI) - if err != nil { - return Ref{}, err - } - return Ref{Ref: ref}, nil -} - -// MustCreateRef creates a ref object but panics when refURI is invalid. -// Use the NewRef method for a version that returns an error. -func MustCreateRef(refURI string) Ref { - return Ref{Ref: jsonreference.MustCreateRef(refURI)} -} - -// MarshalJSON marshals this ref into a JSON object -func (r Ref) MarshalJSON() ([]byte, error) { - str := r.String() - if str == "" { - if r.IsRoot() { - return []byte(`{"$ref":""}`), nil - } - return []byte("{}"), nil - } - v := map[string]interface{}{"$ref": str} - return json.Marshal(v) -} - -// UnmarshalJSON unmarshals this ref from a JSON object -func (r *Ref) UnmarshalJSON(d []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(d, &v); err != nil { - return err - } - - if v == nil { - return nil - } - - if vv, ok := v["$ref"]; ok { - if str, ok := vv.(string); ok { - ref, err := jsonreference.New(str) - if err != nil { - return err - } - *r = Ref{Ref: ref} - } - } - - return nil -} diff --git a/vendor/github.com/go-openapi/spec/response.go b/vendor/github.com/go-openapi/spec/response.go deleted file mode 100644 index a32b039eaf..0000000000 --- a/vendor/github.com/go-openapi/spec/response.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// ResponseProps properties specific to a response -type ResponseProps struct { - Description string `json:"description,omitempty"` - Schema *Schema `json:"schema,omitempty"` - Headers map[string]Header `json:"headers,omitempty"` - Examples map[string]interface{} `json:"examples,omitempty"` -} - -// Response describes a single response from an API Operation. -// -// For more information: http://goo.gl/8us55a#responseObject -type Response struct { - Refable - ResponseProps - VendorExtensible -} - -// JSONLookup look up a value by the json property name -func (p Response) JSONLookup(token string) (interface{}, error) { - if ex, ok := p.Extensions[token]; ok { - return &ex, nil - } - if token == "$ref" { - return &p.Ref, nil - } - r, _, err := jsonpointer.GetForToken(p.ResponseProps, token) - return r, err -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (r *Response) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &r.ResponseProps); err != nil { - return err - } - if err := json.Unmarshal(data, &r.Refable); err != nil { - return err - } - if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { - return err - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (r Response) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(r.ResponseProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(r.Refable) - if err != nil { - return nil, err - } - b3, err := json.Marshal(r.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2, b3), nil -} - -// NewResponse creates a new response instance -func NewResponse() *Response { - return new(Response) -} - -// ResponseRef creates a response as a json reference -func ResponseRef(url string) *Response { - resp := NewResponse() - resp.Ref = MustCreateRef(url) - return resp -} - -// WithDescription sets the description on this response, allows for chaining -func (r *Response) WithDescription(description string) *Response { - r.Description = description - return r -} - -// WithSchema sets the schema on this response, allows for chaining. -// Passing a nil argument removes the schema from this response -func (r *Response) WithSchema(schema *Schema) *Response { - r.Schema = schema - return r -} - -// AddHeader adds a header to this response -func (r *Response) AddHeader(name string, header *Header) *Response { - if header == nil { - return r.RemoveHeader(name) - } - if r.Headers == nil { - r.Headers = make(map[string]Header) - } - r.Headers[name] = *header - return r -} - -// RemoveHeader removes a header from this response -func (r *Response) RemoveHeader(name string) *Response { - delete(r.Headers, name) - return r -} - -// AddExample adds an example to this response -func (r *Response) AddExample(mediaType string, example interface{}) *Response { - if r.Examples == nil { - r.Examples = make(map[string]interface{}) - } - r.Examples[mediaType] = example - return r -} diff --git a/vendor/github.com/go-openapi/spec/responses.go b/vendor/github.com/go-openapi/spec/responses.go deleted file mode 100644 index 3ab06697f2..0000000000 --- a/vendor/github.com/go-openapi/spec/responses.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "fmt" - "reflect" - "strconv" - - "github.com/go-openapi/swag" -) - -// Responses is a container for the expected responses of an operation. -// The container maps a HTTP response code to the expected response. -// It is not expected from the documentation to necessarily cover all possible HTTP response codes, -// since they may not be known in advance. However, it is expected from the documentation to cover -// a successful operation response and any known errors. -// -// The `default` can be used a default response object for all HTTP codes that are not covered -// individually by the specification. -// -// The `Responses Object` MUST contain at least one response code, and it SHOULD be the response -// for a successful operation call. -// -// For more information: http://goo.gl/8us55a#responsesObject -type Responses struct { - VendorExtensible - ResponsesProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (r Responses) JSONLookup(token string) (interface{}, error) { - if token == "default" { - return r.Default, nil - } - if ex, ok := r.Extensions[token]; ok { - return &ex, nil - } - if i, err := strconv.Atoi(token); err == nil { - if scr, ok := r.StatusCodeResponses[i]; ok { - return scr, nil - } - } - return nil, fmt.Errorf("object has no field %q", token) -} - -// UnmarshalJSON hydrates this items instance with the data from JSON -func (r *Responses) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &r.ResponsesProps); err != nil { - return err - } - if err := json.Unmarshal(data, &r.VendorExtensible); err != nil { - return err - } - if reflect.DeepEqual(ResponsesProps{}, r.ResponsesProps) { - r.ResponsesProps = ResponsesProps{} - } - return nil -} - -// MarshalJSON converts this items object to JSON -func (r Responses) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(r.ResponsesProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(r.VendorExtensible) - if err != nil { - return nil, err - } - concated := swag.ConcatJSON(b1, b2) - return concated, nil -} - -type ResponsesProps struct { - Default *Response - StatusCodeResponses map[int]Response -} - -func (r ResponsesProps) MarshalJSON() ([]byte, error) { - toser := map[string]Response{} - if r.Default != nil { - toser["default"] = *r.Default - } - for k, v := range r.StatusCodeResponses { - toser[strconv.Itoa(k)] = v - } - return json.Marshal(toser) -} - -func (r *ResponsesProps) UnmarshalJSON(data []byte) error { - var res map[string]Response - if err := json.Unmarshal(data, &res); err != nil { - return nil - } - if v, ok := res["default"]; ok { - r.Default = &v - delete(res, "default") - } - for k, v := range res { - if nk, err := strconv.Atoi(k); err == nil { - if r.StatusCodeResponses == nil { - r.StatusCodeResponses = map[int]Response{} - } - r.StatusCodeResponses[nk] = v - } - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/schema.go b/vendor/github.com/go-openapi/spec/schema.go deleted file mode 100644 index 1cdcc163f1..0000000000 --- a/vendor/github.com/go-openapi/spec/schema.go +++ /dev/null @@ -1,628 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "fmt" - "net/url" - "strings" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// BooleanProperty creates a boolean property -func BooleanProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} -} - -// BoolProperty creates a boolean property -func BoolProperty() *Schema { return BooleanProperty() } - -// StringProperty creates a string property -func StringProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} -} - -// CharProperty creates a string property -func CharProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} -} - -// Float64Property creates a float64/double property -func Float64Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} -} - -// Float32Property creates a float32/float property -func Float32Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} -} - -// Int8Property creates an int8 property -func Int8Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} -} - -// Int16Property creates an int16 property -func Int16Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} -} - -// Int32Property creates an int32 property -func Int32Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} -} - -// Int64Property creates an int64 property -func Int64Property() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} -} - -// StrFmtProperty creates a property for the named string format -func StrFmtProperty(format string) *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} -} - -// DateProperty creates a date property -func DateProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} -} - -// DateTimeProperty creates a date time property -func DateTimeProperty() *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} -} - -// MapProperty creates a map property -func MapProperty(property *Schema) *Schema { - return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} -} - -// RefProperty creates a ref property -func RefProperty(name string) *Schema { - return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} -} - -// RefSchema creates a ref property -func RefSchema(name string) *Schema { - return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} -} - -// ArrayProperty creates an array property -func ArrayProperty(items *Schema) *Schema { - if items == nil { - return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} - } - return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} -} - -// ComposedSchema creates a schema with allOf -func ComposedSchema(schemas ...Schema) *Schema { - s := new(Schema) - s.AllOf = schemas - return s -} - -// SchemaURL represents a schema url -type SchemaURL string - -// MarshalJSON marshal this to JSON -func (r SchemaURL) MarshalJSON() ([]byte, error) { - if r == "" { - return []byte("{}"), nil - } - v := map[string]interface{}{"$schema": string(r)} - return json.Marshal(v) -} - -// UnmarshalJSON unmarshal this from JSON -func (r *SchemaURL) UnmarshalJSON(data []byte) error { - var v map[string]interface{} - if err := json.Unmarshal(data, &v); err != nil { - return err - } - if v == nil { - return nil - } - if vv, ok := v["$schema"]; ok { - if str, ok := vv.(string); ok { - u, err := url.Parse(str) - if err != nil { - return err - } - - *r = SchemaURL(u.String()) - } - } - return nil -} - -// type ExtraSchemaProps map[string]interface{} - -// // JSONSchema represents a structure that is a json schema draft 04 -// type JSONSchema struct { -// SchemaProps -// ExtraSchemaProps -// } - -// // MarshalJSON marshal this to JSON -// func (s JSONSchema) MarshalJSON() ([]byte, error) { -// b1, err := json.Marshal(s.SchemaProps) -// if err != nil { -// return nil, err -// } -// b2, err := s.Ref.MarshalJSON() -// if err != nil { -// return nil, err -// } -// b3, err := s.Schema.MarshalJSON() -// if err != nil { -// return nil, err -// } -// b4, err := json.Marshal(s.ExtraSchemaProps) -// if err != nil { -// return nil, err -// } -// return swag.ConcatJSON(b1, b2, b3, b4), nil -// } - -// // UnmarshalJSON marshal this from JSON -// func (s *JSONSchema) UnmarshalJSON(data []byte) error { -// var sch JSONSchema -// if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.Ref); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.Schema); err != nil { -// return err -// } -// if err := json.Unmarshal(data, &sch.ExtraSchemaProps); err != nil { -// return err -// } -// *s = sch -// return nil -// } - -type SchemaProps struct { - ID string `json:"id,omitempty"` - Ref Ref `json:"-"` - Schema SchemaURL `json:"-"` - Description string `json:"description,omitempty"` - Type StringOrArray `json:"type,omitempty"` - Format string `json:"format,omitempty"` - Title string `json:"title,omitempty"` - Default interface{} `json:"default,omitempty"` - Maximum *float64 `json:"maximum,omitempty"` - ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` - Minimum *float64 `json:"minimum,omitempty"` - ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` - MaxLength *int64 `json:"maxLength,omitempty"` - MinLength *int64 `json:"minLength,omitempty"` - Pattern string `json:"pattern,omitempty"` - MaxItems *int64 `json:"maxItems,omitempty"` - MinItems *int64 `json:"minItems,omitempty"` - UniqueItems bool `json:"uniqueItems,omitempty"` - MultipleOf *float64 `json:"multipleOf,omitempty"` - Enum []interface{} `json:"enum,omitempty"` - MaxProperties *int64 `json:"maxProperties,omitempty"` - MinProperties *int64 `json:"minProperties,omitempty"` - Required []string `json:"required,omitempty"` - Items *SchemaOrArray `json:"items,omitempty"` - AllOf []Schema `json:"allOf,omitempty"` - OneOf []Schema `json:"oneOf,omitempty"` - AnyOf []Schema `json:"anyOf,omitempty"` - Not *Schema `json:"not,omitempty"` - Properties map[string]Schema `json:"properties,omitempty"` - AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` - PatternProperties map[string]Schema `json:"patternProperties,omitempty"` - Dependencies Dependencies `json:"dependencies,omitempty"` - AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` - Definitions Definitions `json:"definitions,omitempty"` -} - -type SwaggerSchemaProps struct { - Discriminator string `json:"discriminator,omitempty"` - ReadOnly bool `json:"readOnly,omitempty"` - XML *XMLObject `json:"xml,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` - Example interface{} `json:"example,omitempty"` -} - -// Schema the schema object allows the definition of input and output data types. -// These types can be objects, but also primitives and arrays. -// This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) -// and uses a predefined subset of it. -// On top of this subset, there are extensions provided by this specification to allow for more complete documentation. -// -// For more information: http://goo.gl/8us55a#schemaObject -type Schema struct { - VendorExtensible - SchemaProps - SwaggerSchemaProps - ExtraProps map[string]interface{} `json:"-"` -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s Schema) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - - if ex, ok := s.ExtraProps[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) - if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { - return r, err - } - r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) - return r, err -} - -// WithID sets the id for this schema, allows for chaining -func (s *Schema) WithID(id string) *Schema { - s.ID = id - return s -} - -// WithTitle sets the title for this schema, allows for chaining -func (s *Schema) WithTitle(title string) *Schema { - s.Title = title - return s -} - -// WithDescription sets the description for this schema, allows for chaining -func (s *Schema) WithDescription(description string) *Schema { - s.Description = description - return s -} - -// WithProperties sets the properties for this schema -func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { - s.Properties = schemas - return s -} - -// SetProperty sets a property on this schema -func (s *Schema) SetProperty(name string, schema Schema) *Schema { - if s.Properties == nil { - s.Properties = make(map[string]Schema) - } - s.Properties[name] = schema - return s -} - -// WithAllOf sets the all of property -func (s *Schema) WithAllOf(schemas ...Schema) *Schema { - s.AllOf = schemas - return s -} - -// WithMaxProperties sets the max number of properties an object can have -func (s *Schema) WithMaxProperties(max int64) *Schema { - s.MaxProperties = &max - return s -} - -// WithMinProperties sets the min number of properties an object must have -func (s *Schema) WithMinProperties(min int64) *Schema { - s.MinProperties = &min - return s -} - -// Typed sets the type of this schema for a single value item -func (s *Schema) Typed(tpe, format string) *Schema { - s.Type = []string{tpe} - s.Format = format - return s -} - -// AddType adds a type with potential format to the types for this schema -func (s *Schema) AddType(tpe, format string) *Schema { - s.Type = append(s.Type, tpe) - if format != "" { - s.Format = format - } - return s -} - -// CollectionOf a fluent builder method for an array parameter -func (s *Schema) CollectionOf(items Schema) *Schema { - s.Type = []string{"array"} - s.Items = &SchemaOrArray{Schema: &items} - return s -} - -// WithDefault sets the default value on this parameter -func (s *Schema) WithDefault(defaultValue interface{}) *Schema { - s.Default = defaultValue - return s -} - -// WithRequired flags this parameter as required -func (s *Schema) WithRequired(items ...string) *Schema { - s.Required = items - return s -} - -// AddRequired adds field names to the required properties array -func (s *Schema) AddRequired(items ...string) *Schema { - s.Required = append(s.Required, items...) - return s -} - -// WithMaxLength sets a max length value -func (s *Schema) WithMaxLength(max int64) *Schema { - s.MaxLength = &max - return s -} - -// WithMinLength sets a min length value -func (s *Schema) WithMinLength(min int64) *Schema { - s.MinLength = &min - return s -} - -// WithPattern sets a pattern value -func (s *Schema) WithPattern(pattern string) *Schema { - s.Pattern = pattern - return s -} - -// WithMultipleOf sets a multiple of value -func (s *Schema) WithMultipleOf(number float64) *Schema { - s.MultipleOf = &number - return s -} - -// WithMaximum sets a maximum number value -func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { - s.Maximum = &max - s.ExclusiveMaximum = exclusive - return s -} - -// WithMinimum sets a minimum number value -func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { - s.Minimum = &min - s.ExclusiveMinimum = exclusive - return s -} - -// WithEnum sets a the enum values (replace) -func (s *Schema) WithEnum(values ...interface{}) *Schema { - s.Enum = append([]interface{}{}, values...) - return s -} - -// WithMaxItems sets the max items -func (s *Schema) WithMaxItems(size int64) *Schema { - s.MaxItems = &size - return s -} - -// WithMinItems sets the min items -func (s *Schema) WithMinItems(size int64) *Schema { - s.MinItems = &size - return s -} - -// UniqueValues dictates that this array can only have unique items -func (s *Schema) UniqueValues() *Schema { - s.UniqueItems = true - return s -} - -// AllowDuplicates this array can have duplicates -func (s *Schema) AllowDuplicates() *Schema { - s.UniqueItems = false - return s -} - -// AddToAllOf adds a schema to the allOf property -func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { - s.AllOf = append(s.AllOf, schemas...) - return s -} - -// WithDiscriminator sets the name of the discriminator field -func (s *Schema) WithDiscriminator(discriminator string) *Schema { - s.Discriminator = discriminator - return s -} - -// AsReadOnly flags this schema as readonly -func (s *Schema) AsReadOnly() *Schema { - s.ReadOnly = true - return s -} - -// AsWritable flags this schema as writeable (not read-only) -func (s *Schema) AsWritable() *Schema { - s.ReadOnly = false - return s -} - -// WithExample sets the example for this schema -func (s *Schema) WithExample(example interface{}) *Schema { - s.Example = example - return s -} - -// WithExternalDocs sets/removes the external docs for/from this schema. -// When you pass empty strings as params the external documents will be removed. -// When you pass non-empty string as one value then those values will be used on the external docs object. -// So when you pass a non-empty description, you should also pass the url and vice versa. -func (s *Schema) WithExternalDocs(description, url string) *Schema { - if description == "" && url == "" { - s.ExternalDocs = nil - return s - } - - if s.ExternalDocs == nil { - s.ExternalDocs = &ExternalDocumentation{} - } - s.ExternalDocs.Description = description - s.ExternalDocs.URL = url - return s -} - -// WithXMLName sets the xml name for the object -func (s *Schema) WithXMLName(name string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Name = name - return s -} - -// WithXMLNamespace sets the xml namespace for the object -func (s *Schema) WithXMLNamespace(namespace string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Namespace = namespace - return s -} - -// WithXMLPrefix sets the xml prefix for the object -func (s *Schema) WithXMLPrefix(prefix string) *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Prefix = prefix - return s -} - -// AsXMLAttribute flags this object as xml attribute -func (s *Schema) AsXMLAttribute() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Attribute = true - return s -} - -// AsXMLElement flags this object as an xml node -func (s *Schema) AsXMLElement() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Attribute = false - return s -} - -// AsWrappedXML flags this object as wrapped, this is mostly useful for array types -func (s *Schema) AsWrappedXML() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Wrapped = true - return s -} - -// AsUnwrappedXML flags this object as an xml node -func (s *Schema) AsUnwrappedXML() *Schema { - if s.XML == nil { - s.XML = new(XMLObject) - } - s.XML.Wrapped = false - return s -} - -// MarshalJSON marshal this to JSON -func (s Schema) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SchemaProps) - if err != nil { - return nil, fmt.Errorf("schema props %v", err) - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, fmt.Errorf("vendor props %v", err) - } - b3, err := s.Ref.MarshalJSON() - if err != nil { - return nil, fmt.Errorf("ref prop %v", err) - } - b4, err := s.Schema.MarshalJSON() - if err != nil { - return nil, fmt.Errorf("schema prop %v", err) - } - b5, err := json.Marshal(s.SwaggerSchemaProps) - if err != nil { - return nil, fmt.Errorf("common validations %v", err) - } - var b6 []byte - if s.ExtraProps != nil { - jj, err := json.Marshal(s.ExtraProps) - if err != nil { - return nil, fmt.Errorf("extra props %v", err) - } - b6 = jj - } - return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil -} - -// UnmarshalJSON marshal this from JSON -func (s *Schema) UnmarshalJSON(data []byte) error { - var sch Schema - if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { - return err - } - if err := json.Unmarshal(data, &sch.Ref); err != nil { - return err - } - if err := json.Unmarshal(data, &sch.Schema); err != nil { - return err - } - if err := json.Unmarshal(data, &sch.SwaggerSchemaProps); err != nil { - return err - } - - var d map[string]interface{} - if err := json.Unmarshal(data, &d); err != nil { - return err - } - - delete(d, "$ref") - delete(d, "$schema") - for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { - delete(d, pn) - } - - for k, vv := range d { - lk := strings.ToLower(k) - if strings.HasPrefix(lk, "x-") { - if sch.Extensions == nil { - sch.Extensions = map[string]interface{}{} - } - sch.Extensions[k] = vv - continue - } - if sch.ExtraProps == nil { - sch.ExtraProps = map[string]interface{}{} - } - sch.ExtraProps[k] = vv - } - - *s = sch - - return nil -} diff --git a/vendor/github.com/go-openapi/spec/security_scheme.go b/vendor/github.com/go-openapi/spec/security_scheme.go deleted file mode 100644 index 22d4f10af2..0000000000 --- a/vendor/github.com/go-openapi/spec/security_scheme.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -const ( - basic = "basic" - apiKey = "apiKey" - oauth2 = "oauth2" - implicit = "implicit" - password = "password" - application = "application" - accessCode = "accessCode" -) - -// BasicAuth creates a basic auth security scheme -func BasicAuth() *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: basic}} -} - -// APIKeyAuth creates an api key auth security scheme -func APIKeyAuth(fieldName, valueSource string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{Type: apiKey, Name: fieldName, In: valueSource}} -} - -// OAuth2Implicit creates an implicit flow oauth2 security scheme -func OAuth2Implicit(authorizationURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: implicit, - AuthorizationURL: authorizationURL, - }} -} - -// OAuth2Password creates a password flow oauth2 security scheme -func OAuth2Password(tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: password, - TokenURL: tokenURL, - }} -} - -// OAuth2Application creates an application flow oauth2 security scheme -func OAuth2Application(tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: application, - TokenURL: tokenURL, - }} -} - -// OAuth2AccessToken creates an access token flow oauth2 security scheme -func OAuth2AccessToken(authorizationURL, tokenURL string) *SecurityScheme { - return &SecurityScheme{SecuritySchemeProps: SecuritySchemeProps{ - Type: oauth2, - Flow: accessCode, - AuthorizationURL: authorizationURL, - TokenURL: tokenURL, - }} -} - -type SecuritySchemeProps struct { - Description string `json:"description,omitempty"` - Type string `json:"type"` - Name string `json:"name,omitempty"` // api key - In string `json:"in,omitempty"` // api key - Flow string `json:"flow,omitempty"` // oauth2 - AuthorizationURL string `json:"authorizationUrl,omitempty"` // oauth2 - TokenURL string `json:"tokenUrl,omitempty"` // oauth2 - Scopes map[string]string `json:"scopes,omitempty"` // oauth2 -} - -// AddScope adds a scope to this security scheme -func (s *SecuritySchemeProps) AddScope(scope, description string) { - if s.Scopes == nil { - s.Scopes = make(map[string]string) - } - s.Scopes[scope] = description -} - -// SecurityScheme allows the definition of a security scheme that can be used by the operations. -// Supported schemes are basic authentication, an API key (either as a header or as a query parameter) -// and OAuth2's common flows (implicit, password, application and access code). -// -// For more information: http://goo.gl/8us55a#securitySchemeObject -type SecurityScheme struct { - VendorExtensible - SecuritySchemeProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SecurityScheme) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(s.SecuritySchemeProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (s SecurityScheme) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SecuritySchemeProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (s *SecurityScheme) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &s.SecuritySchemeProps); err != nil { - return err - } - if err := json.Unmarshal(data, &s.VendorExtensible); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-openapi/spec/spec.go b/vendor/github.com/go-openapi/spec/spec.go deleted file mode 100644 index 0bb045bc06..0000000000 --- a/vendor/github.com/go-openapi/spec/spec.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import "encoding/json" - -//go:generate curl -L --progress -o ./schemas/v2/schema.json http://swagger.io/v2/schema.json -//go:generate curl -L --progress -o ./schemas/jsonschema-draft-04.json http://json-schema.org/draft-04/schema -//go:generate go-bindata -pkg=spec -prefix=./schemas -ignore=.*\.md ./schemas/... -//go:generate perl -pi -e s,Json,JSON,g bindata.go - -const ( - // SwaggerSchemaURL the url for the swagger 2.0 schema to validate specs - SwaggerSchemaURL = "http://swagger.io/v2/schema.json#" - // JSONSchemaURL the url for the json schema schema - JSONSchemaURL = "http://json-schema.org/draft-04/schema#" -) - -var ( - jsonSchema *Schema - swaggerSchema *Schema -) - -func init() { - jsonSchema = MustLoadJSONSchemaDraft04() - swaggerSchema = MustLoadSwagger20Schema() -} - -// MustLoadJSONSchemaDraft04 panics when Swagger20Schema returns an error -func MustLoadJSONSchemaDraft04() *Schema { - d, e := JSONSchemaDraft04() - if e != nil { - panic(e) - } - return d -} - -// JSONSchemaDraft04 loads the json schema document for json shema draft04 -func JSONSchemaDraft04() (*Schema, error) { - b, err := Asset("jsonschema-draft-04.json") - if err != nil { - return nil, err - } - - schema := new(Schema) - if err := json.Unmarshal(b, schema); err != nil { - return nil, err - } - return schema, nil -} - -// MustLoadSwagger20Schema panics when Swagger20Schema returns an error -func MustLoadSwagger20Schema() *Schema { - d, e := Swagger20Schema() - if e != nil { - panic(e) - } - return d -} - -// Swagger20Schema loads the swagger 2.0 schema from the embedded assets -func Swagger20Schema() (*Schema, error) { - - b, err := Asset("v2/schema.json") - if err != nil { - return nil, err - } - - schema := new(Schema) - if err := json.Unmarshal(b, schema); err != nil { - return nil, err - } - return schema, nil -} diff --git a/vendor/github.com/go-openapi/spec/swagger.go b/vendor/github.com/go-openapi/spec/swagger.go deleted file mode 100644 index 393a316778..0000000000 --- a/vendor/github.com/go-openapi/spec/swagger.go +++ /dev/null @@ -1,317 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - "fmt" - "strconv" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -// Swagger this is the root document object for the API specification. -// It combines what previously was the Resource Listing and API Declaration (version 1.2 and earlier) together into one document. -// -// For more information: http://goo.gl/8us55a#swagger-object- -type Swagger struct { - VendorExtensible - SwaggerProps -} - -// JSONLookup look up a value by the json property name -func (s Swagger) JSONLookup(token string) (interface{}, error) { - if ex, ok := s.Extensions[token]; ok { - return &ex, nil - } - r, _, err := jsonpointer.GetForToken(s.SwaggerProps, token) - return r, err -} - -// MarshalJSON marshals this swagger structure to json -func (s Swagger) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(s.SwaggerProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(s.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON unmarshals a swagger spec from json -func (s *Swagger) UnmarshalJSON(data []byte) error { - var sw Swagger - if err := json.Unmarshal(data, &sw.SwaggerProps); err != nil { - return err - } - if err := json.Unmarshal(data, &sw.VendorExtensible); err != nil { - return err - } - *s = sw - return nil -} - -type SwaggerProps struct { - ID string `json:"id,omitempty"` - Consumes []string `json:"consumes,omitempty"` - Produces []string `json:"produces,omitempty"` - Schemes []string `json:"schemes,omitempty"` // the scheme, when present must be from [http, https, ws, wss] - Swagger string `json:"swagger,omitempty"` - Info *Info `json:"info,omitempty"` - Host string `json:"host,omitempty"` - BasePath string `json:"basePath,omitempty"` // must start with a leading "/" - Paths *Paths `json:"paths"` // required - Definitions Definitions `json:"definitions,omitempty"` - Parameters map[string]Parameter `json:"parameters,omitempty"` - Responses map[string]Response `json:"responses,omitempty"` - SecurityDefinitions SecurityDefinitions `json:"securityDefinitions,omitempty"` - Security []map[string][]string `json:"security,omitempty"` - Tags []Tag `json:"tags,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` -} - -// Dependencies represent a dependencies property -type Dependencies map[string]SchemaOrStringArray - -// SchemaOrBool represents a schema or boolean value, is biased towards true for the boolean property -type SchemaOrBool struct { - Allows bool - Schema *Schema -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrBool) JSONLookup(token string) (interface{}, error) { - if token == "allows" { - return s.Allows, nil - } - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -var jsTrue = []byte("true") -var jsFalse = []byte("false") - -// MarshalJSON convert this object to JSON -func (s SchemaOrBool) MarshalJSON() ([]byte, error) { - if s.Schema != nil { - return json.Marshal(s.Schema) - } - - if s.Schema == nil && !s.Allows { - return jsFalse, nil - } - return jsTrue, nil -} - -// UnmarshalJSON converts this bool or schema object from a JSON structure -func (s *SchemaOrBool) UnmarshalJSON(data []byte) error { - var nw SchemaOrBool - if len(data) >= 4 { - if data[0] == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - nw.Allows = !(data[0] == 'f' && data[1] == 'a' && data[2] == 'l' && data[3] == 's' && data[4] == 'e') - } - *s = nw - return nil -} - -// SchemaOrStringArray represents a schema or a string array -type SchemaOrStringArray struct { - Schema *Schema - Property []string -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrStringArray) JSONLookup(token string) (interface{}, error) { - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -// MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrStringArray) MarshalJSON() ([]byte, error) { - if len(s.Property) > 0 { - return json.Marshal(s.Property) - } - if s.Schema != nil { - return json.Marshal(s.Schema) - } - return nil, nil -} - -// UnmarshalJSON converts this schema object or array from a JSON structure -func (s *SchemaOrStringArray) UnmarshalJSON(data []byte) error { - var first byte - if len(data) > 1 { - first = data[0] - } - var nw SchemaOrStringArray - if first == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - if first == '[' { - if err := json.Unmarshal(data, &nw.Property); err != nil { - return err - } - } - *s = nw - return nil -} - -// Definitions contains the models explicitly defined in this spec -// An object to hold data types that can be consumed and produced by operations. -// These data types can be primitives, arrays or models. -// -// For more information: http://goo.gl/8us55a#definitionsObject -type Definitions map[string]Schema - -// SecurityDefinitions a declaration of the security schemes available to be used in the specification. -// This does not enforce the security schemes on the operations and only serves to provide -// the relevant details for each scheme. -// -// For more information: http://goo.gl/8us55a#securityDefinitionsObject -type SecurityDefinitions map[string]*SecurityScheme - -// StringOrArray represents a value that can either be a string -// or an array of strings. Mainly here for serialization purposes -type StringOrArray []string - -// Contains returns true when the value is contained in the slice -func (s StringOrArray) Contains(value string) bool { - for _, str := range s { - if str == value { - return true - } - } - return false -} - -// JSONLookup implements an interface to customize json pointer lookup -func (s SchemaOrArray) JSONLookup(token string) (interface{}, error) { - if _, err := strconv.Atoi(token); err == nil { - r, _, err := jsonpointer.GetForToken(s.Schemas, token) - return r, err - } - r, _, err := jsonpointer.GetForToken(s.Schema, token) - return r, err -} - -// UnmarshalJSON unmarshals this string or array object from a JSON array or JSON string -func (s *StringOrArray) UnmarshalJSON(data []byte) error { - var first byte - if len(data) > 1 { - first = data[0] - } - - if first == '[' { - var parsed []string - if err := json.Unmarshal(data, &parsed); err != nil { - return err - } - *s = StringOrArray(parsed) - return nil - } - - var single interface{} - if err := json.Unmarshal(data, &single); err != nil { - return err - } - if single == nil { - return nil - } - switch single.(type) { - case string: - *s = StringOrArray([]string{single.(string)}) - return nil - default: - return fmt.Errorf("only string or array is allowed, not %T", single) - } -} - -// MarshalJSON converts this string or array to a JSON array or JSON string -func (s StringOrArray) MarshalJSON() ([]byte, error) { - if len(s) == 1 { - return json.Marshal([]string(s)[0]) - } - return json.Marshal([]string(s)) -} - -// SchemaOrArray represents a value that can either be a Schema -// or an array of Schema. Mainly here for serialization purposes -type SchemaOrArray struct { - Schema *Schema - Schemas []Schema -} - -// Len returns the number of schemas in this property -func (s SchemaOrArray) Len() int { - if s.Schema != nil { - return 1 - } - return len(s.Schemas) -} - -// ContainsType returns true when one of the schemas is of the specified type -func (s *SchemaOrArray) ContainsType(name string) bool { - if s.Schema != nil { - return s.Schema.Type != nil && s.Schema.Type.Contains(name) - } - return false -} - -// MarshalJSON converts this schema object or array into JSON structure -func (s SchemaOrArray) MarshalJSON() ([]byte, error) { - if len(s.Schemas) > 0 { - return json.Marshal(s.Schemas) - } - return json.Marshal(s.Schema) -} - -// UnmarshalJSON converts this schema object or array from a JSON structure -func (s *SchemaOrArray) UnmarshalJSON(data []byte) error { - var nw SchemaOrArray - var first byte - if len(data) > 1 { - first = data[0] - } - if first == '{' { - var sch Schema - if err := json.Unmarshal(data, &sch); err != nil { - return err - } - nw.Schema = &sch - } - if first == '[' { - if err := json.Unmarshal(data, &nw.Schemas); err != nil { - return err - } - } - *s = nw - return nil -} - -// vim:set ft=go noet sts=2 sw=2 ts=2: diff --git a/vendor/github.com/go-openapi/spec/tag.go b/vendor/github.com/go-openapi/spec/tag.go deleted file mode 100644 index 97f555840c..0000000000 --- a/vendor/github.com/go-openapi/spec/tag.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -import ( - "encoding/json" - - "github.com/go-openapi/jsonpointer" - "github.com/go-openapi/swag" -) - -type TagProps struct { - Description string `json:"description,omitempty"` - Name string `json:"name,omitempty"` - ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` -} - -// NewTag creates a new tag -func NewTag(name, description string, externalDocs *ExternalDocumentation) Tag { - return Tag{TagProps: TagProps{description, name, externalDocs}} -} - -// Tag allows adding meta data to a single tag that is used by the [Operation Object](http://goo.gl/8us55a#operationObject). -// It is not mandatory to have a Tag Object per tag used there. -// -// For more information: http://goo.gl/8us55a#tagObject -type Tag struct { - VendorExtensible - TagProps -} - -// JSONLookup implements an interface to customize json pointer lookup -func (t Tag) JSONLookup(token string) (interface{}, error) { - if ex, ok := t.Extensions[token]; ok { - return &ex, nil - } - - r, _, err := jsonpointer.GetForToken(t.TagProps, token) - return r, err -} - -// MarshalJSON marshal this to JSON -func (t Tag) MarshalJSON() ([]byte, error) { - b1, err := json.Marshal(t.TagProps) - if err != nil { - return nil, err - } - b2, err := json.Marshal(t.VendorExtensible) - if err != nil { - return nil, err - } - return swag.ConcatJSON(b1, b2), nil -} - -// UnmarshalJSON marshal this from JSON -func (t *Tag) UnmarshalJSON(data []byte) error { - if err := json.Unmarshal(data, &t.TagProps); err != nil { - return err - } - return json.Unmarshal(data, &t.VendorExtensible) -} diff --git a/vendor/github.com/go-openapi/spec/xml_object.go b/vendor/github.com/go-openapi/spec/xml_object.go deleted file mode 100644 index 945a46703d..0000000000 --- a/vendor/github.com/go-openapi/spec/xml_object.go +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 spec - -// XMLObject a metadata object that allows for more fine-tuned XML model definitions. -// -// For more information: http://goo.gl/8us55a#xmlObject -type XMLObject struct { - Name string `json:"name,omitempty"` - Namespace string `json:"namespace,omitempty"` - Prefix string `json:"prefix,omitempty"` - Attribute bool `json:"attribute,omitempty"` - Wrapped bool `json:"wrapped,omitempty"` -} - -// WithName sets the xml name for the object -func (x *XMLObject) WithName(name string) *XMLObject { - x.Name = name - return x -} - -// WithNamespace sets the xml namespace for the object -func (x *XMLObject) WithNamespace(namespace string) *XMLObject { - x.Namespace = namespace - return x -} - -// WithPrefix sets the xml prefix for the object -func (x *XMLObject) WithPrefix(prefix string) *XMLObject { - x.Prefix = prefix - return x -} - -// AsAttribute flags this object as xml attribute -func (x *XMLObject) AsAttribute() *XMLObject { - x.Attribute = true - return x -} - -// AsElement flags this object as an xml node -func (x *XMLObject) AsElement() *XMLObject { - x.Attribute = false - return x -} - -// AsWrapped flags this object as wrapped, this is mostly useful for array types -func (x *XMLObject) AsWrapped() *XMLObject { - x.Wrapped = true - return x -} - -// AsUnwrapped flags this object as an xml node -func (x *XMLObject) AsUnwrapped() *XMLObject { - x.Wrapped = false - return x -} diff --git a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md b/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md deleted file mode 100644 index 9322b065e3..0000000000 --- a/vendor/github.com/go-openapi/swag/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -nationality, personal appearance, race, religion, or sexual identity and -orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or -advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at ivan+abuse@flanders.co.nz. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/go-openapi/swag/LICENSE b/vendor/github.com/go-openapi/swag/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/vendor/github.com/go-openapi/swag/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/vendor/github.com/go-openapi/swag/README.md b/vendor/github.com/go-openapi/swag/README.md deleted file mode 100644 index 5d43728e87..0000000000 --- a/vendor/github.com/go-openapi/swag/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Swag [![Build Status](https://travis-ci.org/go-openapi/swag.svg?branch=master)](https://travis-ci.org/go-openapi/swag) [![codecov](https://codecov.io/gh/go-openapi/swag/branch/master/graph/badge.svg)](https://codecov.io/gh/go-openapi/swag) [![Slack Status](https://slackin.goswagger.io/badge.svg)](https://slackin.goswagger.io) - -[![license](http://img.shields.io/badge/license-Apache%20v2-orange.svg)](https://raw.githubusercontent.com/go-openapi/swag/master/LICENSE) [![GoDoc](https://godoc.org/github.com/go-openapi/swag?status.svg)](http://godoc.org/github.com/go-openapi/swag) - -Contains a bunch of helper functions: - -* convert between value and pointers for builtins -* convert from string to builtin -* fast json concatenation -* search in path -* load from file or http -* name manglin \ No newline at end of file diff --git a/vendor/github.com/go-openapi/swag/convert.go b/vendor/github.com/go-openapi/swag/convert.go deleted file mode 100644 index 2bf5ecbba2..0000000000 --- a/vendor/github.com/go-openapi/swag/convert.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "math" - "strconv" - "strings" -) - -// same as ECMA Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER -const ( - maxJSONFloat = float64(1<<53 - 1) // 9007199254740991.0 2^53 - 1 - minJSONFloat = -float64(1<<53 - 1) //-9007199254740991.0 -2^53 - 1 -) - -// IsFloat64AJSONInteger allow for integers [-2^53, 2^53-1] inclusive -func IsFloat64AJSONInteger(f float64) bool { - if math.IsNaN(f) || math.IsInf(f, 0) || f < minJSONFloat || f > maxJSONFloat { - return false - } - - return f == float64(int64(f)) || f == float64(uint64(f)) -} - -var evaluatesAsTrue = map[string]struct{}{ - "true": struct{}{}, - "1": struct{}{}, - "yes": struct{}{}, - "ok": struct{}{}, - "y": struct{}{}, - "on": struct{}{}, - "selected": struct{}{}, - "checked": struct{}{}, - "t": struct{}{}, - "enabled": struct{}{}, -} - -// ConvertBool turn a string into a boolean -func ConvertBool(str string) (bool, error) { - _, ok := evaluatesAsTrue[strings.ToLower(str)] - return ok, nil -} - -// ConvertFloat32 turn a string into a float32 -func ConvertFloat32(str string) (float32, error) { - f, err := strconv.ParseFloat(str, 32) - if err != nil { - return 0, err - } - return float32(f), nil -} - -// ConvertFloat64 turn a string into a float64 -func ConvertFloat64(str string) (float64, error) { - return strconv.ParseFloat(str, 64) -} - -// ConvertInt8 turn a string into int8 boolean -func ConvertInt8(str string) (int8, error) { - i, err := strconv.ParseInt(str, 10, 8) - if err != nil { - return 0, err - } - return int8(i), nil -} - -// ConvertInt16 turn a string into a int16 -func ConvertInt16(str string) (int16, error) { - i, err := strconv.ParseInt(str, 10, 16) - if err != nil { - return 0, err - } - return int16(i), nil -} - -// ConvertInt32 turn a string into a int32 -func ConvertInt32(str string) (int32, error) { - i, err := strconv.ParseInt(str, 10, 32) - if err != nil { - return 0, err - } - return int32(i), nil -} - -// ConvertInt64 turn a string into a int64 -func ConvertInt64(str string) (int64, error) { - return strconv.ParseInt(str, 10, 64) -} - -// ConvertUint8 turn a string into a uint8 -func ConvertUint8(str string) (uint8, error) { - i, err := strconv.ParseUint(str, 10, 8) - if err != nil { - return 0, err - } - return uint8(i), nil -} - -// ConvertUint16 turn a string into a uint16 -func ConvertUint16(str string) (uint16, error) { - i, err := strconv.ParseUint(str, 10, 16) - if err != nil { - return 0, err - } - return uint16(i), nil -} - -// ConvertUint32 turn a string into a uint32 -func ConvertUint32(str string) (uint32, error) { - i, err := strconv.ParseUint(str, 10, 32) - if err != nil { - return 0, err - } - return uint32(i), nil -} - -// ConvertUint64 turn a string into a uint64 -func ConvertUint64(str string) (uint64, error) { - return strconv.ParseUint(str, 10, 64) -} - -// FormatBool turns a boolean into a string -func FormatBool(value bool) string { - return strconv.FormatBool(value) -} - -// FormatFloat32 turns a float32 into a string -func FormatFloat32(value float32) string { - return strconv.FormatFloat(float64(value), 'f', -1, 32) -} - -// FormatFloat64 turns a float64 into a string -func FormatFloat64(value float64) string { - return strconv.FormatFloat(value, 'f', -1, 64) -} - -// FormatInt8 turns an int8 into a string -func FormatInt8(value int8) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt16 turns an int16 into a string -func FormatInt16(value int16) string { - return strconv.FormatInt(int64(value), 10) -} - -// FormatInt32 turns an int32 into a string -func FormatInt32(value int32) string { - return strconv.Itoa(int(value)) -} - -// FormatInt64 turns an int64 into a string -func FormatInt64(value int64) string { - return strconv.FormatInt(value, 10) -} - -// FormatUint8 turns an uint8 into a string -func FormatUint8(value uint8) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint16 turns an uint16 into a string -func FormatUint16(value uint16) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint32 turns an uint32 into a string -func FormatUint32(value uint32) string { - return strconv.FormatUint(uint64(value), 10) -} - -// FormatUint64 turns an uint64 into a string -func FormatUint64(value uint64) string { - return strconv.FormatUint(value, 10) -} diff --git a/vendor/github.com/go-openapi/swag/convert_types.go b/vendor/github.com/go-openapi/swag/convert_types.go deleted file mode 100644 index c95e4e78bd..0000000000 --- a/vendor/github.com/go-openapi/swag/convert_types.go +++ /dev/null @@ -1,595 +0,0 @@ -package swag - -import "time" - -// This file was taken from the aws go sdk - -// String returns a pointer to of the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to of the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to of the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int32 returns a pointer to of the int64 value passed in. -func Int32(v int32) *int32 { - return &v -} - -// Int32Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int32Value(v *int32) int32 { - if v != nil { - return *v - } - return 0 -} - -// Int32Slice converts a slice of int64 values into a slice of -// int32 pointers -func Int32Slice(src []int32) []*int32 { - dst := make([]*int32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int32ValueSlice converts a slice of int32 pointers into a slice of -// int32 values -func Int32ValueSlice(src []*int32) []int32 { - dst := make([]int32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int32Map converts a string map of int32 values into a string -// map of int32 pointers -func Int32Map(src map[string]int32) map[string]*int32 { - dst := make(map[string]*int32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int32ValueMap converts a string map of int32 pointers into a string -// map of int32 values -func Int32ValueMap(src map[string]*int32) map[string]int32 { - dst := make(map[string]int32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to of the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint returns a pouinter to of the uint value passed in. -func Uint(v uint) *uint { - return &v -} - -// UintValue returns the value of the uint pouinter passed in or -// 0 if the pouinter is nil. -func UintValue(v *uint) uint { - if v != nil { - return *v - } - return 0 -} - -// UintSlice converts a slice of uint values uinto a slice of -// uint pouinters -func UintSlice(src []uint) []*uint { - dst := make([]*uint, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// UintValueSlice converts a slice of uint pouinters uinto a slice of -// uint values -func UintValueSlice(src []*uint) []uint { - dst := make([]uint, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// UintMap converts a string map of uint values uinto a string -// map of uint pouinters -func UintMap(src map[string]uint) map[string]*uint { - dst := make(map[string]*uint) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// UintValueMap converts a string map of uint pouinters uinto a string -// map of uint values -func UintValueMap(src map[string]*uint) map[string]uint { - dst := make(map[string]uint) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint32 returns a pouinter to of the uint64 value passed in. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint32Value returns the value of the uint64 pouinter passed in or -// 0 if the pouinter is nil. -func Uint32Value(v *uint32) uint32 { - if v != nil { - return *v - } - return 0 -} - -// Uint32Slice converts a slice of uint64 values uinto a slice of -// uint32 pouinters -func Uint32Slice(src []uint32) []*uint32 { - dst := make([]*uint32, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint32ValueSlice converts a slice of uint32 pouinters uinto a slice of -// uint32 values -func Uint32ValueSlice(src []*uint32) []uint32 { - dst := make([]uint32, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint32Map converts a string map of uint32 values uinto a string -// map of uint32 pouinters -func Uint32Map(src map[string]uint32) map[string]*uint32 { - dst := make(map[string]*uint32) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint32ValueMap converts a string map of uint32 pouinters uinto a string -// map of uint32 values -func Uint32ValueMap(src map[string]*uint32) map[string]uint32 { - dst := make(map[string]uint32) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Uint64 returns a pouinter to of the uint64 value passed in. -func Uint64(v uint64) *uint64 { - return &v -} - -// Uint64Value returns the value of the uint64 pouinter passed in or -// 0 if the pouinter is nil. -func Uint64Value(v *uint64) uint64 { - if v != nil { - return *v - } - return 0 -} - -// Uint64Slice converts a slice of uint64 values uinto a slice of -// uint64 pouinters -func Uint64Slice(src []uint64) []*uint64 { - dst := make([]*uint64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Uint64ValueSlice converts a slice of uint64 pouinters uinto a slice of -// uint64 values -func Uint64ValueSlice(src []*uint64) []uint64 { - dst := make([]uint64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Uint64Map converts a string map of uint64 values uinto a string -// map of uint64 pouinters -func Uint64Map(src map[string]uint64) map[string]*uint64 { - dst := make(map[string]*uint64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Uint64ValueMap converts a string map of uint64 pouinters uinto a string -// map of uint64 values -func Uint64ValueMap(src map[string]*uint64) map[string]uint64 { - dst := make(map[string]uint64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float64 returns a pointer to of the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to of the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/go-openapi/swag/json.go b/vendor/github.com/go-openapi/swag/json.go deleted file mode 100644 index cb20a6a0f7..0000000000 --- a/vendor/github.com/go-openapi/swag/json.go +++ /dev/null @@ -1,295 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "bytes" - "encoding/json" - "log" - "reflect" - "strings" - "sync" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" -) - -// DefaultJSONNameProvider the default cache for types -var DefaultJSONNameProvider = NewNameProvider() - -const comma = byte(',') - -var closers = map[byte]byte{ - '{': '}', - '[': ']', -} - -type ejMarshaler interface { - MarshalEasyJSON(w *jwriter.Writer) -} - -type ejUnmarshaler interface { - UnmarshalEasyJSON(w *jlexer.Lexer) -} - -// WriteJSON writes json data, prefers finding an appropriate interface to short-circuit the marshaller -// so it takes the fastest option available. -func WriteJSON(data interface{}) ([]byte, error) { - if d, ok := data.(ejMarshaler); ok { - jw := new(jwriter.Writer) - d.MarshalEasyJSON(jw) - return jw.BuildBytes() - } - if d, ok := data.(json.Marshaler); ok { - return d.MarshalJSON() - } - return json.Marshal(data) -} - -// ReadJSON reads json data, prefers finding an appropriate interface to short-circuit the unmarshaller -// so it takes the fastes option available -func ReadJSON(data []byte, value interface{}) error { - if d, ok := value.(ejUnmarshaler); ok { - jl := &jlexer.Lexer{Data: data} - d.UnmarshalEasyJSON(jl) - return jl.Error() - } - if d, ok := value.(json.Unmarshaler); ok { - return d.UnmarshalJSON(data) - } - return json.Unmarshal(data, value) -} - -// DynamicJSONToStruct converts an untyped json structure into a struct -func DynamicJSONToStruct(data interface{}, target interface{}) error { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := WriteJSON(data) - if err != nil { - return err - } - if err := ReadJSON(b, target); err != nil { - return err - } - return nil -} - -// ConcatJSON concatenates multiple json objects efficiently -func ConcatJSON(blobs ...[]byte) []byte { - if len(blobs) == 0 { - return nil - } - if len(blobs) == 1 { - return blobs[0] - } - - last := len(blobs) - 1 - var opening, closing byte - a := 0 - idx := 0 - buf := bytes.NewBuffer(nil) - - for i, b := range blobs { - if len(b) > 0 && opening == 0 { // is this an array or an object? - opening, closing = b[0], closers[b[0]] - } - - if opening != '{' && opening != '[' { - continue // don't know how to concatenate non container objects - } - - if len(b) < 3 { // yep empty but also the last one, so closing this thing - if i == last && a > 0 { - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - continue - } - - idx = 0 - if a > 0 { // we need to join with a comma for everything beyond the first non-empty item - if err := buf.WriteByte(comma); err != nil { - log.Println(err) - } - idx = 1 // this is not the first or the last so we want to drop the leading bracket - } - - if i != last { // not the last one, strip brackets - if _, err := buf.Write(b[idx : len(b)-1]); err != nil { - log.Println(err) - } - } else { // last one, strip only the leading bracket - if _, err := buf.Write(b[idx:]); err != nil { - log.Println(err) - } - } - a++ - } - // somehow it ended up being empty, so provide a default value - if buf.Len() == 0 { - if err := buf.WriteByte(opening); err != nil { - log.Println(err) - } - if err := buf.WriteByte(closing); err != nil { - log.Println(err) - } - } - return buf.Bytes() -} - -// ToDynamicJSON turns an object into a properly JSON typed structure -func ToDynamicJSON(data interface{}) interface{} { - // TODO: convert straight to a json typed map (mergo + iterate?) - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - var res interface{} - if err := json.Unmarshal(b, &res); err != nil { - log.Println(err) - } - return res -} - -// FromDynamicJSON turns an object into a properly JSON typed structure -func FromDynamicJSON(data, target interface{}) error { - b, err := json.Marshal(data) - if err != nil { - log.Println(err) - } - return json.Unmarshal(b, target) -} - -// NameProvider represents an object capabale of translating from go property names -// to json property names -// This type is thread-safe. -type NameProvider struct { - lock *sync.Mutex - index map[reflect.Type]nameIndex -} - -type nameIndex struct { - jsonNames map[string]string - goNames map[string]string -} - -// NewNameProvider creates a new name provider -func NewNameProvider() *NameProvider { - return &NameProvider{ - lock: &sync.Mutex{}, - index: make(map[reflect.Type]nameIndex), - } -} - -func buildnameIndex(tpe reflect.Type, idx, reverseIdx map[string]string) { - for i := 0; i < tpe.NumField(); i++ { - targetDes := tpe.Field(i) - - if targetDes.PkgPath != "" { // unexported - continue - } - - if targetDes.Anonymous { // walk embedded structures tree down first - buildnameIndex(targetDes.Type, idx, reverseIdx) - continue - } - - if tag := targetDes.Tag.Get("json"); tag != "" { - - parts := strings.Split(tag, ",") - if len(parts) == 0 { - continue - } - - nm := parts[0] - if nm == "-" { - continue - } - if nm == "" { // empty string means we want to use the Go name - nm = targetDes.Name - } - - idx[nm] = targetDes.Name - reverseIdx[targetDes.Name] = nm - } - } -} - -func newNameIndex(tpe reflect.Type) nameIndex { - var idx = make(map[string]string, tpe.NumField()) - var reverseIdx = make(map[string]string, tpe.NumField()) - - buildnameIndex(tpe, idx, reverseIdx) - return nameIndex{jsonNames: idx, goNames: reverseIdx} -} - -// GetJSONNames gets all the json property names for a type -func (n *NameProvider) GetJSONNames(subject interface{}) []string { - n.lock.Lock() - defer n.lock.Unlock() - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - - var res []string - for k := range names.jsonNames { - res = append(res, k) - } - return res -} - -// GetJSONName gets the json name for a go property name -func (n *NameProvider) GetJSONName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetJSONNameForType(tpe, name) -} - -// GetJSONNameForType gets the json name for a go property name on a given type -func (n *NameProvider) GetJSONNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.goNames[name] - return nme, ok -} - -func (n *NameProvider) makeNameIndex(tpe reflect.Type) nameIndex { - names := newNameIndex(tpe) - n.index[tpe] = names - return names -} - -// GetGoName gets the go name for a json property name -func (n *NameProvider) GetGoName(subject interface{}, name string) (string, bool) { - tpe := reflect.Indirect(reflect.ValueOf(subject)).Type() - return n.GetGoNameForType(tpe, name) -} - -// GetGoNameForType gets the go name for a given type for a json property name -func (n *NameProvider) GetGoNameForType(tpe reflect.Type, name string) (string, bool) { - n.lock.Lock() - defer n.lock.Unlock() - names, ok := n.index[tpe] - if !ok { - names = n.makeNameIndex(tpe) - } - nme, ok := names.jsonNames[name] - return nme, ok -} diff --git a/vendor/github.com/go-openapi/swag/loading.go b/vendor/github.com/go-openapi/swag/loading.go deleted file mode 100644 index 62ed1e80ab..0000000000 --- a/vendor/github.com/go-openapi/swag/loading.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" - "path/filepath" - "strings" - "time" -) - -// LoadHTTPTimeout the default timeout for load requests -var LoadHTTPTimeout = 30 * time.Second - -// LoadFromFileOrHTTP loads the bytes from a file or a remote http server based on the path passed in -func LoadFromFileOrHTTP(path string) ([]byte, error) { - return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(LoadHTTPTimeout))(path) -} - -// LoadFromFileOrHTTPWithTimeout loads the bytes from a file or a remote http server based on the path passed in -// timeout arg allows for per request overriding of the request timeout -func LoadFromFileOrHTTPWithTimeout(path string, timeout time.Duration) ([]byte, error) { - return LoadStrategy(path, ioutil.ReadFile, loadHTTPBytes(timeout))(path) -} - -// LoadStrategy returns a loader function for a given path or uri -func LoadStrategy(path string, local, remote func(string) ([]byte, error)) func(string) ([]byte, error) { - if strings.HasPrefix(path, "http") { - return remote - } - return func(pth string) ([]byte, error) { return local(filepath.FromSlash(pth)) } -} - -func loadHTTPBytes(timeout time.Duration) func(path string) ([]byte, error) { - return func(path string) ([]byte, error) { - client := &http.Client{Timeout: timeout} - req, err := http.NewRequest("GET", path, nil) - if err != nil { - return nil, err - } - resp, err := client.Do(req) - defer func() { - if resp != nil { - if e := resp.Body.Close(); e != nil { - log.Println(e) - } - } - }() - if err != nil { - return nil, err - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("could not access document at %q [%s] ", path, resp.Status) - } - - return ioutil.ReadAll(resp.Body) - } -} diff --git a/vendor/github.com/go-openapi/swag/net.go b/vendor/github.com/go-openapi/swag/net.go deleted file mode 100644 index 8323fa37b6..0000000000 --- a/vendor/github.com/go-openapi/swag/net.go +++ /dev/null @@ -1,24 +0,0 @@ -package swag - -import ( - "net" - "strconv" -) - -// SplitHostPort splits a network address into a host and a port. -// The port is -1 when there is no port to be found -func SplitHostPort(addr string) (host string, port int, err error) { - h, p, err := net.SplitHostPort(addr) - if err != nil { - return "", -1, err - } - if p == "" { - return "", -1, &net.AddrError{Err: "missing port in address", Addr: addr} - } - - pi, err := strconv.Atoi(p) - if err != nil { - return "", -1, err - } - return h, pi, nil -} diff --git a/vendor/github.com/go-openapi/swag/path.go b/vendor/github.com/go-openapi/swag/path.go deleted file mode 100644 index 941bd0176b..0000000000 --- a/vendor/github.com/go-openapi/swag/path.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "os" - "path/filepath" - "runtime" - "strings" -) - -const ( - // GOPATHKey represents the env key for gopath - GOPATHKey = "GOPATH" -) - -// FindInSearchPath finds a package in a provided lists of paths -func FindInSearchPath(searchPath, pkg string) string { - pathsList := filepath.SplitList(searchPath) - for _, path := range pathsList { - if evaluatedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", pkg)); err == nil { - if _, err := os.Stat(evaluatedPath); err == nil { - return evaluatedPath - } - } - } - return "" -} - -// FindInGoSearchPath finds a package in the $GOPATH:$GOROOT -func FindInGoSearchPath(pkg string) string { - return FindInSearchPath(FullGoSearchPath(), pkg) -} - -// FullGoSearchPath gets the search paths for finding packages -func FullGoSearchPath() string { - allPaths := os.Getenv(GOPATHKey) - if allPaths == "" { - allPaths = filepath.Join(os.Getenv("HOME"), "go") - } - if allPaths != "" { - allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":") - } else { - allPaths = runtime.GOROOT() - } - return allPaths -} diff --git a/vendor/github.com/go-openapi/swag/util.go b/vendor/github.com/go-openapi/swag/util.go deleted file mode 100644 index 40751aab44..0000000000 --- a/vendor/github.com/go-openapi/swag/util.go +++ /dev/null @@ -1,336 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "math" - "reflect" - "regexp" - "sort" - "strings" - "unicode" -) - -// Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769 -var commonInitialisms = map[string]bool{ - "ACL": true, - "API": true, - "ASCII": true, - "CPU": true, - "CSS": true, - "DNS": true, - "EOF": true, - "GUID": true, - "HTML": true, - "HTTPS": true, - "HTTP": true, - "ID": true, - "IP": true, - "JSON": true, - "LHS": true, - "QPS": true, - "RAM": true, - "RHS": true, - "RPC": true, - "SLA": true, - "SMTP": true, - "SQL": true, - "SSH": true, - "TCP": true, - "TLS": true, - "TTL": true, - "UDP": true, - "UI": true, - "UID": true, - "UUID": true, - "URI": true, - "URL": true, - "UTF8": true, - "VM": true, - "XML": true, - "XMPP": true, - "XSRF": true, - "XSS": true, -} -var initialisms []string - -func init() { - for k := range commonInitialisms { - initialisms = append(initialisms, k) - } - sort.Sort(sort.Reverse(byLength(initialisms))) -} - -// JoinByFormat joins a string array by a known format: -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func JoinByFormat(data []string, format string) []string { - if len(data) == 0 { - return data - } - var sep string - switch format { - case "ssv": - sep = " " - case "tsv": - sep = "\t" - case "pipes": - sep = "|" - case "multi": - return data - default: - sep = "," - } - return []string{strings.Join(data, sep)} -} - -// SplitByFormat splits a string by a known format: -// ssv: space separated value -// tsv: tab separated value -// pipes: pipe (|) separated value -// csv: comma separated value (default) -func SplitByFormat(data, format string) []string { - if data == "" { - return nil - } - var sep string - switch format { - case "ssv": - sep = " " - case "tsv": - sep = "\t" - case "pipes": - sep = "|" - case "multi": - return nil - default: - sep = "," - } - var result []string - for _, s := range strings.Split(data, sep) { - if ts := strings.TrimSpace(s); ts != "" { - result = append(result, ts) - } - } - return result -} - -type byLength []string - -func (s byLength) Len() int { - return len(s) -} -func (s byLength) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s byLength) Less(i, j int) bool { - return len(s[i]) < len(s[j]) -} - -// Prepares strings by splitting by caps, spaces, dashes, and underscore -func split(str string) (words []string) { - repl := strings.NewReplacer( - "@", "At ", - "&", "And ", - "|", "Pipe ", - "$", "Dollar ", - "!", "Bang ", - "-", " ", - "_", " ", - ) - - rex1 := regexp.MustCompile(`(\p{Lu})`) - rex2 := regexp.MustCompile(`(\pL|\pM|\pN|\p{Pc})+`) - - str = trim(str) - - // Convert dash and underscore to spaces - str = repl.Replace(str) - - // Split when uppercase is found (needed for Snake) - str = rex1.ReplaceAllString(str, " $1") - // check if consecutive single char things make up an initialism - - for _, k := range initialisms { - str = strings.Replace(str, rex1.ReplaceAllString(k, " $1"), " "+k, -1) - } - // Get the final list of words - words = rex2.FindAllString(str, -1) - - return -} - -// Removes leading whitespaces -func trim(str string) string { - return strings.Trim(str, " ") -} - -// Shortcut to strings.ToUpper() -func upper(str string) string { - return strings.ToUpper(trim(str)) -} - -// Shortcut to strings.ToLower() -func lower(str string) string { - return strings.ToLower(trim(str)) -} - -// ToFileName lowercases and underscores a go type name -func ToFileName(name string) string { - var out []string - for _, w := range split(name) { - out = append(out, lower(w)) - } - return strings.Join(out, "_") -} - -// ToCommandName lowercases and underscores a go type name -func ToCommandName(name string) string { - var out []string - for _, w := range split(name) { - out = append(out, lower(w)) - } - return strings.Join(out, "-") -} - -// ToHumanNameLower represents a code name as a human series of words -func ToHumanNameLower(name string) string { - var out []string - for _, w := range split(name) { - if !commonInitialisms[upper(w)] { - out = append(out, lower(w)) - } else { - out = append(out, w) - } - } - return strings.Join(out, " ") -} - -// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized -func ToHumanNameTitle(name string) string { - var out []string - for _, w := range split(name) { - uw := upper(w) - if !commonInitialisms[uw] { - out = append(out, upper(w[:1])+lower(w[1:])) - } else { - out = append(out, w) - } - } - return strings.Join(out, " ") -} - -// ToJSONName camelcases a name which can be underscored or pascal cased -func ToJSONName(name string) string { - var out []string - for i, w := range split(name) { - if i == 0 { - out = append(out, lower(w)) - continue - } - out = append(out, upper(w[:1])+lower(w[1:])) - } - return strings.Join(out, "") -} - -// ToVarName camelcases a name which can be underscored or pascal cased -func ToVarName(name string) string { - res := ToGoName(name) - if _, ok := commonInitialisms[res]; ok { - return lower(res) - } - if len(res) <= 1 { - return lower(res) - } - return lower(res[:1]) + res[1:] -} - -// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes -func ToGoName(name string) string { - var out []string - for _, w := range split(name) { - uw := upper(w) - mod := int(math.Min(float64(len(uw)), 2)) - if !commonInitialisms[uw] && !commonInitialisms[uw[:len(uw)-mod]] { - uw = upper(w[:1]) + lower(w[1:]) - } - out = append(out, uw) - } - - result := strings.Join(out, "") - if len(result) > 0 { - ud := upper(result[:1]) - ru := []rune(ud) - if unicode.IsUpper(ru[0]) { - result = ud + result[1:] - } else { - result = "X" + ud + result[1:] - } - } - return result -} - -// ContainsStringsCI searches a slice of strings for a case-insensitive match -func ContainsStringsCI(coll []string, item string) bool { - for _, a := range coll { - if strings.EqualFold(a, item) { - return true - } - } - return false -} - -type zeroable interface { - IsZero() bool -} - -// IsZero returns true when the value passed into the function is a zero value. -// This allows for safer checking of interface values. -func IsZero(data interface{}) bool { - // check for things that have an IsZero method instead - if vv, ok := data.(zeroable); ok { - return vv.IsZero() - } - // continue with slightly more complex reflection - v := reflect.ValueOf(data) - switch v.Kind() { - case reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - case reflect.Struct, reflect.Array: - return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface()) - case reflect.Invalid: - return true - } - return false -} - -// CommandLineOptionsGroup represents a group of user-defined command line options -type CommandLineOptionsGroup struct { - ShortDescription string - LongDescription string - Options interface{} -} diff --git a/vendor/github.com/go-openapi/swag/yaml.go b/vendor/github.com/go-openapi/swag/yaml.go deleted file mode 100644 index 26502f21d5..0000000000 --- a/vendor/github.com/go-openapi/swag/yaml.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright 2015 go-swagger maintainers -// -// 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 swag - -import ( - "encoding/json" - "fmt" - "path/filepath" - "strconv" - - "github.com/mailru/easyjson/jlexer" - "github.com/mailru/easyjson/jwriter" - - yaml "gopkg.in/yaml.v2" -) - -// YAMLMatcher matches yaml -func YAMLMatcher(path string) bool { - ext := filepath.Ext(path) - return ext == ".yaml" || ext == ".yml" -} - -// YAMLToJSON converts YAML unmarshaled data into json compatible data -func YAMLToJSON(data interface{}) (json.RawMessage, error) { - jm, err := transformData(data) - if err != nil { - return nil, err - } - b, err := WriteJSON(jm) - return json.RawMessage(b), err -} - -func BytesToYAMLDoc(data []byte) (interface{}, error) { - var canary map[interface{}]interface{} // validate this is an object and not a different type - if err := yaml.Unmarshal(data, &canary); err != nil { - return nil, err - } - - var document yaml.MapSlice // preserve order that is present in the document - if err := yaml.Unmarshal(data, &document); err != nil { - return nil, err - } - return document, nil -} - -type JSONMapSlice []JSONMapItem - -func (s JSONMapSlice) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -func (s JSONMapSlice) MarshalEasyJSON(w *jwriter.Writer) { - w.RawByte('{') - - ln := len(s) - last := ln - 1 - for i := 0; i < ln; i++ { - s[i].MarshalEasyJSON(w) - if i != last { // last item - w.RawByte(',') - } - } - - w.RawByte('}') -} - -func (s *JSONMapSlice) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} -func (s *JSONMapSlice) UnmarshalEasyJSON(in *jlexer.Lexer) { - if in.IsNull() { - in.Skip() - return - } - - var result JSONMapSlice - in.Delim('{') - for !in.IsDelim('}') { - var mi JSONMapItem - mi.UnmarshalEasyJSON(in) - result = append(result, mi) - } - *s = result -} - -type JSONMapItem struct { - Key string - Value interface{} -} - -func (s JSONMapItem) MarshalJSON() ([]byte, error) { - w := &jwriter.Writer{Flags: jwriter.NilMapAsEmpty | jwriter.NilSliceAsEmpty} - s.MarshalEasyJSON(w) - return w.BuildBytes() -} - -func (s JSONMapItem) MarshalEasyJSON(w *jwriter.Writer) { - w.String(s.Key) - w.RawByte(':') - w.Raw(WriteJSON(s.Value)) -} - -func (s *JSONMapItem) UnmarshalEasyJSON(in *jlexer.Lexer) { - key := in.UnsafeString() - in.WantColon() - value := in.Interface() - in.WantComma() - s.Key = key - s.Value = value -} -func (s *JSONMapItem) UnmarshalJSON(data []byte) error { - l := jlexer.Lexer{Data: data} - s.UnmarshalEasyJSON(&l) - return l.Error() -} - -func transformData(input interface{}) (out interface{}, err error) { - switch in := input.(type) { - case yaml.MapSlice: - - o := make(JSONMapSlice, len(in)) - for i, mi := range in { - var nmi JSONMapItem - switch k := mi.Key.(type) { - case string: - nmi.Key = k - case int: - nmi.Key = strconv.Itoa(k) - default: - return nil, fmt.Errorf("types don't match expect map key string or int got: %T", mi.Key) - } - - v, err := transformData(mi.Value) - if err != nil { - return nil, err - } - nmi.Value = v - o[i] = nmi - } - return o, nil - case map[interface{}]interface{}: - o := make(JSONMapSlice, 0, len(in)) - for ke, va := range in { - var nmi JSONMapItem - switch k := ke.(type) { - case string: - nmi.Key = k - case int: - nmi.Key = strconv.Itoa(k) - default: - return nil, fmt.Errorf("types don't match expect map key string or int got: %T", ke) - } - - v, err := transformData(va) - if err != nil { - return nil, err - } - nmi.Value = v - o = append(o, nmi) - } - return o, nil - case []interface{}: - len1 := len(in) - o := make([]interface{}, len1) - for i := 0; i < len1; i++ { - o[i], err = transformData(in[i]) - if err != nil { - return nil, err - } - } - return o, nil - } - return input, nil -} - -// YAMLDoc loads a yaml document from either http or a file and converts it to json -func YAMLDoc(path string) (json.RawMessage, error) { - yamlDoc, err := YAMLData(path) - if err != nil { - return nil, err - } - - data, err := YAMLToJSON(yamlDoc) - if err != nil { - return nil, err - } - - return json.RawMessage(data), nil -} - -// YAMLData loads a yaml document from either http or a file -func YAMLData(path string) (interface{}, error) { - data, err := LoadFromFileOrHTTP(path) - if err != nil { - return nil, err - } - - return BytesToYAMLDoc(data) -} diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 1b1b1921ef..0000000000 --- a/vendor/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,31 +0,0 @@ -Go support for Protocol Buffers - Google's data interchange format - -Copyright 2010 The Go Authors. All rights reserved. -https://github.com/golang/protobuf - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index e2e0651a93..0000000000 --- a/vendor/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto - make diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index e392575b35..0000000000 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,229 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - - out := reflect.New(in.Type().Elem()) - // out is empty so a merge is a deep copy. - mergeStruct(out.Elem(), in.Elem()) - return out.Interface().(Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - // Explicit test prior to mergeStruct so that mistyped nils will fail - panic("proto: type mismatch") - } - if in.IsNil() { - // Merging nil into non-nil is a quiet no-op - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -func mergeStruct(out, in reflect.Value) { - sprop := GetProperties(in.Type()) - for i := 0; i < in.NumField(); i++ { - f := in.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) - } - - if emIn, ok := extendable(in.Addr().Interface()); ok { - emOut, _ := extendable(out.Addr().Interface()) - mIn, muIn := emIn.extensionsRead() - if mIn != nil { - mOut := emOut.extensionsWrite() - muIn.Lock() - mergeExtension(mOut, mIn) - muIn.Unlock() - } - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// mergeAny performs a merge between two values of the same type. -// viaPtr indicates whether the values were indirected through a pointer (implying proto2). -// prop is set if this is a struct field (it may be nil). -func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { - if in.Type() == protoMessageType { - if !in.IsNil() { - if out.IsNil() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - switch in.Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - if !viaPtr && isProto3Zero(in) { - return - } - out.Set(in) - case reflect.Interface: - // Probably a oneof field; copy non-nil values. - if in.IsNil() { - return - } - // Allocate destination if it is not set, or set to a different type. - // Otherwise we will merge as normal. - if out.IsNil() || out.Elem().Type() != in.Elem().Type() { - out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) - } - mergeAny(out.Elem(), in.Elem(), false, nil) - case reflect.Map: - if in.Len() == 0 { - return - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - mergeAny(out.Elem(), in.Elem(), true, nil) - case reflect.Slice: - if in.IsNil() { - return - } - if in.Type().Elem().Kind() == reflect.Uint8 { - // []byte is a scalar bytes field, not a repeated field. - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value, and should not - // be merged. - if prop != nil && prop.proto3 && in.Len() == 0 { - return - } - - // Make a deep copy. - // Append to []byte{} instead of []byte(nil) so that we never end up - // with a nil result. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index aa207298f9..0000000000 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,970 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" - "os" - "reflect" -) - -// errOverflow is returned when an integer is too large to be represented. -var errOverflow = errors.New("proto: integer overflow") - -// ErrInternalBadWireType is returned by generated code when an incorrect -// wire type is encountered. It does not get returned to user code. -var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof") - -// The fundamental decoders that interpret bytes on the wire. -// Those that take integer types all return uint64 and are -// therefore of type valueDecoder. - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func DecodeVarint(buf []byte) (x uint64, n int) { - for shift := uint(0); shift < 64; shift += 7 { - if n >= len(buf) { - return 0, 0 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - return 0, 0 -} - -func (p *Buffer) decodeVarintSlow() (x uint64, err error) { - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - i := p.index - buf := p.buf - - if i >= len(buf) { - return 0, io.ErrUnexpectedEOF - } else if buf[i] < 0x80 { - p.index++ - return uint64(buf[i]), nil - } else if len(buf)-i < 10 { - return p.decodeVarintSlow() - } - - var b uint64 - // we already checked the first byte - x = uint64(buf[i]) - 0x80 - i++ - - b = uint64(buf[i]) - i++ - x += b << 7 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 7 - - b = uint64(buf[i]) - i++ - x += b << 14 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 14 - - b = uint64(buf[i]) - i++ - x += b << 21 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 21 - - b = uint64(buf[i]) - i++ - x += b << 28 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 28 - - b = uint64(buf[i]) - i++ - x += b << 35 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 35 - - b = uint64(buf[i]) - i++ - x += b << 42 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 42 - - b = uint64(buf[i]) - i++ - x += b << 49 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 49 - - b = uint64(buf[i]) - i++ - x += b << 56 - if b&0x80 == 0 { - goto done - } - x -= 0x80 << 56 - - b = uint64(buf[i]) - i++ - x += b << 63 - if b&0x80 == 0 { - goto done - } - // x -= 0x80 << 63 // Always zero. - - return 0, errOverflow - -done: - p.index = i - return x, nil -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// These are not ValueDecoders: they produce an array of bytes or a string. -// bytes, embedded messages - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -// If the protocol buffer has extensions, and the field matches, add it as an extension. -// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. -func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { - oi := o.index - - err := o.skip(t, tag, wire) - if err != nil { - return err - } - - if !unrecField.IsValid() { - return nil - } - - ptr := structPointer_Bytes(base, unrecField) - - // Add the skipped field to struct field - obuf := o.buf - - o.buf = *ptr - o.EncodeVarint(uint64(tag<<3 | wire)) - *ptr = append(o.buf, obuf[oi:o.index]...) - - o.buf = obuf - - return nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -func (o *Buffer) skip(t reflect.Type, tag, wire int) error { - - var u uint64 - var err error - - switch wire { - case WireVarint: - _, err = o.DecodeVarint() - case WireFixed64: - _, err = o.DecodeFixed64() - case WireBytes: - _, err = o.DecodeRawBytes(false) - case WireFixed32: - _, err = o.DecodeFixed32() - case WireStartGroup: - for { - u, err = o.DecodeVarint() - if err != nil { - break - } - fwire := int(u & 0x7) - if fwire == WireEndGroup { - break - } - ftag := int(u >> 3) - err = o.skip(t, ftag, fwire) - if err != nil { - break - } - } - default: - err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) - } - return err -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The method should reset the receiver before -// decoding starts. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - return UnmarshalMerge(buf, pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - return NewBuffer(buf).Unmarshal(pb) -} - -// DecodeMessage reads a count-delimited message from the Buffer. -func (p *Buffer) DecodeMessage(pb Message) error { - enc, err := p.DecodeRawBytes(false) - if err != nil { - return err - } - return NewBuffer(enc).Unmarshal(pb) -} - -// DecodeGroup reads a tag-delimited group from the Buffer. -func (p *Buffer) DecodeGroup(pb Message) error { - typ, base, err := getbase(pb) - if err != nil { - return err - } - return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base) -} - -// Unmarshal parses the protocol buffer representation in the -// Buffer and places the decoded result in pb. If the struct -// underlying pb does not match the data in the buffer, the results can be -// unpredictable. -// -// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - typ, base, err := getbase(pb) - if err != nil { - return err - } - - err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) - - if collectStats { - stats.Decode++ - } - - return err -} - -// unmarshalType does the work of unmarshaling a structure. -func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { - var state errorState - required, reqFields := prop.reqCount, uint64(0) - - var err error - for err == nil && o.index < len(o.buf) { - oi := o.index - var u uint64 - u, err = o.DecodeVarint() - if err != nil { - break - } - wire := int(u & 0x7) - if wire == WireEndGroup { - if is_group { - if required > 0 { - // Not enough information to determine the exact field. - // (See below.) - return &RequiredNotSetError{"{Unknown}"} - } - return nil // input is satisfied - } - return fmt.Errorf("proto: %s: wiretype end group for non-group", st) - } - tag := int(u >> 3) - if tag <= 0 { - return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) - } - fieldnum, ok := prop.decoderTags.get(tag) - if !ok { - // Maybe it's an extension? - if prop.extendable { - if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - extmap := e.extensionsWrite() - ext := extmap[int32(tag)] // may be missing - ext.enc = append(ext.enc, o.buf[oi:o.index]...) - extmap[int32(tag)] = ext - } - continue - } - } - // Maybe it's a oneof? - if prop.oneofUnmarshaler != nil { - m := structPointer_Interface(base, st).(Message) - // First return value indicates whether tag is a oneof field. - ok, err = prop.oneofUnmarshaler(m, tag, wire, o) - if err == ErrInternalBadWireType { - // Map the error to something more descriptive. - // Do the formatting here to save generated code space. - err = fmt.Errorf("bad wiretype for oneof field in %T", m) - } - if ok { - continue - } - } - err = o.skipAndSave(st, tag, wire, base, prop.unrecField) - continue - } - p := prop.Prop[fieldnum] - - if p.dec == nil { - fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) - continue - } - dec := p.dec - if wire != WireStartGroup && wire != p.WireType { - if wire == WireBytes && p.packedDec != nil { - // a packable field - dec = p.packedDec - } else { - err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) - continue - } - } - decErr := dec(o, p, base) - if decErr != nil && !state.shouldContinue(decErr, p) { - err = decErr - } - if err == nil && p.Required { - // Successfully decoded a required field. - if tag <= 64 { - // use bitmap for fields 1-64 to catch field reuse. - var mask uint64 = 1 << uint64(tag-1) - if reqFields&mask == 0 { - // new required field - reqFields |= mask - required-- - } - } else { - // This is imprecise. It can be fooled by a required field - // with a tag > 64 that is encoded twice; that's very rare. - // A fully correct implementation would require allocating - // a data structure, which we would like to avoid. - required-- - } - } - } - if err == nil { - if is_group { - return io.ErrUnexpectedEOF - } - if state.err != nil { - return state.err - } - if required > 0 { - // Not enough information to determine the exact field. If we use extra - // CPU, we could determine the field only if the missing required field - // has a tag <= 64 and we check reqFields. - return &RequiredNotSetError{"{Unknown}"} - } - } - return err -} - -// Individual type decoders -// For each, -// u is the decoded value, -// v is a pointer to the field (pointer) in the struct - -// Sizes of the pools to allocate inside the Buffer. -// The goal is modest amortization and allocation -// on at least 16-byte boundaries. -const ( - boolPoolSize = 16 - uint32PoolSize = 8 - uint64PoolSize = 4 -) - -// Decode a bool. -func (o *Buffer) dec_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - if len(o.bools) == 0 { - o.bools = make([]bool, boolPoolSize) - } - o.bools[0] = u != 0 - *structPointer_Bool(base, p.field) = &o.bools[0] - o.bools = o.bools[1:] - return nil -} - -func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - *structPointer_BoolVal(base, p.field) = u != 0 - return nil -} - -// Decode an int32. -func (o *Buffer) dec_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) - return nil -} - -func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) - return nil -} - -// Decode an int64. -func (o *Buffer) dec_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, u) - return nil -} - -func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, u) - return nil -} - -// Decode a string. -func (o *Buffer) dec_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_String(base, p.field) = &s - return nil -} - -func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_StringVal(base, p.field) = s - return nil -} - -// Decode a slice of bytes ([]byte). -func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - *structPointer_Bytes(base, p.field) = b - return nil -} - -// Decode a slice of bools ([]bool). -func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - v := structPointer_BoolSlice(base, p.field) - *v = append(*v, u != 0) - return nil -} - -// Decode a slice of bools ([]bool) in packed format. -func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { - v := structPointer_BoolSlice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded bools - fin := o.index + nb - if fin < o.index { - return errOverflow - } - - y := *v - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - y = append(y, u != 0) - } - - *v = y - return nil -} - -// Decode a slice of int32s ([]int32). -func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - structPointer_Word32Slice(base, p.field).Append(uint32(u)) - return nil -} - -// Decode a slice of int32s ([]int32) in packed format. -func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int32s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(uint32(u)) - } - return nil -} - -// Decode a slice of int64s ([]int64). -func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - - structPointer_Word64Slice(base, p.field).Append(u) - return nil -} - -// Decode a slice of int64s ([]int64) in packed format. -func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int64s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(u) - } - return nil -} - -// Decode a slice of strings ([]string). -func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - v := structPointer_StringSlice(base, p.field) - *v = append(*v, s) - return nil -} - -// Decode a slice of slice of bytes ([][]byte). -func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - v := structPointer_BytesSlice(base, p.field) - *v = append(*v, b) - return nil -} - -// Decode a map field. -func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - oi := o.index // index at the end of this map entry - o.index -= len(raw) // move buffer back to start of map entry - - mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V - if mptr.Elem().IsNil() { - mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) - } - v := mptr.Elem() // map[K]V - - // Prepare addressable doubly-indirect placeholders for the key and value types. - // See enc_new_map for why. - keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K - keybase := toStructPointer(keyptr.Addr()) // **K - - var valbase structPointer - var valptr reflect.Value - switch p.mtype.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valptr = reflect.ValueOf(&dummy) // *[]byte - valbase = toStructPointer(valptr) // *[]byte - case reflect.Ptr: - // message; valptr is **Msg; need to allocate the intermediate pointer - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valptr.Set(reflect.New(valptr.Type().Elem())) - valbase = toStructPointer(valptr) - default: - // everything else - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valbase = toStructPointer(valptr.Addr()) // **V - } - - // Decode. - // This parses a restricted wire format, namely the encoding of a message - // with two fields. See enc_new_map for the format. - for o.index < oi { - // tagcode for key and value properties are always a single byte - // because they have tags 1 and 2. - tagcode := o.buf[o.index] - o.index++ - switch tagcode { - case p.mkeyprop.tagcode[0]: - if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { - return err - } - case p.mvalprop.tagcode[0]: - if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { - return err - } - default: - // TODO: Should we silently skip this instead? - return fmt.Errorf("proto: bad map data tag %d", raw[0]) - } - } - keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() { - keyelem = reflect.Zero(p.mtype.Key()) - } - if !valelem.IsValid() { - valelem = reflect.Zero(p.mtype.Elem()) - } - - v.SetMapIndex(keyelem, valelem) - return nil -} - -// Decode a group. -func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - return o.unmarshalType(p.stype, p.sprop, true, bas) -} - -// Decode an embedded message. -func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := structPointer_Interface(bas, p.stype) - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of embedded messages. -func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, false, base) -} - -// Decode a slice of embedded groups. -func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, true, base) -} - -// Decode a slice of structs ([]*struct). -func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { - v := reflect.New(p.stype) - bas := toStructPointer(v) - structPointer_StructPointerSlice(base, p.field).Append(bas) - - if is_group { - err := o.unmarshalType(p.stype, p.sprop, is_group, bas) - return err - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := v.Interface() - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, bas) - - o.buf = obuf - o.index = oi - - return err -} diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index 8b84d1b22d..0000000000 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,1362 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "fmt" - "reflect" - "sort" -) - -// RequiredNotSetError is the error returned if Marshal is called with -// a protocol buffer struct whose required fields have not -// all been initialized. It is also the error returned if Unmarshal is -// called with an encoded protocol buffer that does not include all the -// required fields. -// -// When printed, RequiredNotSetError reports the first unset required field in a -// message. If the field cannot be precisely determined, it is reported as -// "{Unknown}". -type RequiredNotSetError struct { - field string -} - -func (e *RequiredNotSetError) Error() string { - return fmt.Sprintf("proto: required field %q not set", e.field) -} - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") - - // ErrTooLarge is the error returned if Marshal is called with a - // message that encodes to >2GB. - ErrTooLarge = errors.New("proto: message encodes to over 2 GB") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// maxMarshalSize is the largest allowed size of an encoded protobuf, -// since C++ and Java use signed int32s for the size. -const maxMarshalSize = 1<<31 - 1 - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - return nil -} - -// SizeVarint returns the varint encoding size of an integer. -func SizeVarint(x uint64) int { - return sizeVarint(x) -} - -func sizeVarint(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -func sizeFixed64(x uint64) int { - return 8 -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -func sizeFixed32(x uint64) int { - return 4 -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) EncodeZigzag64(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) -} - -func sizeZigzag64(x uint64) int { - return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -func sizeZigzag32(x uint64) int { - return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -func sizeRawBytes(b []byte) int { - return sizeVarint(uint64(len(b))) + - len(b) -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -func sizeStringBytes(s string) int { - return sizeVarint(uint64(len(s))) + - len(s) -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, returning the data. -func Marshal(pb Message) ([]byte, error) { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - return m.Marshal() - } - p := NewBuffer(nil) - err := p.Marshal(pb) - if p.buf == nil && err == nil { - // Return a non-nil slice on success. - return []byte{}, nil - } - return p.buf, err -} - -// EncodeMessage writes the protocol buffer to the Buffer, -// prefixed by a varint-encoded length. -func (p *Buffer) EncodeMessage(pb Message) error { - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - var state errorState - err = p.enc_len_struct(GetProperties(t.Elem()), base, &state) - } - return err -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, writing the result to the -// Buffer. -func (p *Buffer) Marshal(pb Message) error { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - data, err := m.Marshal() - p.buf = append(p.buf, data...) - return err - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - err = p.enc_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Encode++ // Parens are to work around a goimports bug. - } - - if len(p.buf) > maxMarshalSize { - return ErrTooLarge - } - return err -} - -// Size returns the encoded size of a protocol buffer. -func Size(pb Message) (n int) { - // Can the object marshal itself? If so, Size is slow. - // TODO: add Size to Marshaler, or add a Sizer interface. - if m, ok := pb.(Marshaler); ok { - b, _ := m.Marshal() - return len(b) - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return 0 - } - if err == nil { - n = size_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - (stats).Size++ // Parens are to work around a goimports bug. - } - - return -} - -// Individual type encoders. - -// Encode a bool. -func (o *Buffer) enc_bool(p *Properties, base structPointer) error { - v := *structPointer_Bool(base, p.field) - if v == nil { - return ErrNil - } - x := 0 - if *v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - if !v { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, 1) - return nil -} - -func size_bool(p *Properties, base structPointer) int { - v := *structPointer_Bool(base, p.field) - if v == nil { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -func size_proto3_bool(p *Properties, base structPointer) int { - v := *structPointer_BoolVal(base, p.field) - if !v && !p.oneof { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode an int32. -func (o *Buffer) enc_int32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a uint32. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := word32_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := word32_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode an int64. -func (o *Buffer) enc_int64(p *Properties, base structPointer) error { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return ErrNil - } - x := word64_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return 0 - } - x := word64_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -func size_proto3_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a string. -func (o *Buffer) enc_string(p *Properties, base structPointer) error { - v := *structPointer_String(base, p.field) - if v == nil { - return ErrNil - } - x := *v - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(x) - return nil -} - -func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_string(p *Properties, base structPointer) (n int) { - v := *structPointer_String(base, p.field) - if v == nil { - return 0 - } - x := *v - n += len(p.tagcode) - n += sizeStringBytes(x) - return -} - -func size_proto3_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - if v == "" && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeStringBytes(v) - return -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} - -// Encode a message struct. -func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return state.err - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -func size_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a group struct. -func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { - var state errorState - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return ErrNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - err := o.enc_struct(p.sprop, b) - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return state.err -} - -func size_struct_group(p *Properties, base structPointer) (n int) { - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return 0 - } - - n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) - n += size_struct(p.sprop, b) - n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return -} - -// Encode a slice of bools ([]bool). -func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - for _, x := range s { - o.buf = append(o.buf, p.tagcode...) - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_bool(p *Properties, base structPointer) int { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - return l * (len(p.tagcode) + 1) // each bool takes exactly one byte -} - -// Encode a slice of bools ([]bool) in packed format. -func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(l)) // each bool takes exactly one byte - for _, x := range s { - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_packed_bool(p *Properties, base structPointer) (n int) { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeVarint(uint64(l)) - n += l // each bool takes exactly one byte - return -} - -// Encode a slice of bytes ([]byte). -func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func size_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -// Encode a slice of int32s ([]int32). -func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of int32s ([]int32) in packed format. -func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(buf, uint64(x)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - bufSize += p.valSize(uint64(x)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of uint32s ([]uint32). -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := s.Index(i) - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := s.Index(i) - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of uint32s ([]uint32) in packed format. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, uint64(s.Index(i))) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(uint64(s.Index(i))) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of int64s ([]int64). -func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, s.Index(i)) - } - return nil -} - -func size_slice_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - n += p.valSize(s.Index(i)) - } - return -} - -// Encode a slice of int64s ([]int64) in packed format. -func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, s.Index(i)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(s.Index(i)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of slice of bytes ([][]byte). -func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(ss[i]) - } - return nil -} - -func size_slice_slice_byte(p *Properties, base structPointer) (n int) { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return 0 - } - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeRawBytes(ss[i]) - } - return -} - -// Encode a slice of strings ([]string). -func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(ss[i]) - } - return nil -} - -func size_slice_string(p *Properties, base structPointer) (n int) { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeStringBytes(ss[i]) - } - return -} - -// Encode a slice of message structs ([]*struct). -func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - } - return state.err -} - -func size_slice_struct_message(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -// Encode a slice of group structs ([]*struct). -func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return errRepeatedHasNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - - err := o.enc_struct(p.sprop, b) - - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - } - return state.err -} - -func size_slice_struct_group(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) - n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return // return size up to this point - } - - n += size_struct(p.sprop, b) - } - return -} - -// Encode an extension map. -func (o *Buffer) enc_map(p *Properties, base structPointer) error { - exts := structPointer_ExtMap(base, p.field) - if err := encodeExtensionsMap(*exts); err != nil { - return err - } - - return o.enc_map_body(*exts) -} - -func (o *Buffer) enc_exts(p *Properties, base structPointer) error { - exts := structPointer_Extensions(base, p.field) - - v, mu := exts.extensionsRead() - if v == nil { - return nil - } - - mu.Lock() - defer mu.Unlock() - if err := encodeExtensionsMap(v); err != nil { - return err - } - - return o.enc_map_body(v) -} - -func (o *Buffer) enc_map_body(v map[int32]Extension) error { - // Fast-path for common cases: zero or one extensions. - if len(v) <= 1 { - for _, e := range v { - o.buf = append(o.buf, e.enc...) - } - return nil - } - - // Sort keys to provide a deterministic encoding. - keys := make([]int, 0, len(v)) - for k := range v { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - o.buf = append(o.buf, v[int32(k)].enc...) - } - return nil -} - -func size_map(p *Properties, base structPointer) int { - v := structPointer_ExtMap(base, p.field) - return extensionsMapSize(*v) -} - -func size_exts(p *Properties, base structPointer) int { - v := structPointer_Extensions(base, p.field) - return extensionsSize(v) -} - -// Encode a map field. -func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { - var state errorState // XXX: or do we need to plumb this through? - - /* - A map defined as - map map_field = N; - is encoded in the same way as - message MapFieldEntry { - key_type key = 1; - value_type value = 2; - } - repeated MapFieldEntry map_field = N; - */ - - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - if v.Len() == 0 { - return nil - } - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - enc := func() error { - if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { - return err - } - if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { - return err - } - return nil - } - - // Don't sort map keys. It is not required by the spec, and C++ doesn't do it. - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - - keycopy.Set(key) - valcopy.Set(val) - - o.buf = append(o.buf, p.tagcode...) - if err := o.enc_len_thing(enc, &state); err != nil { - return err - } - } - return nil -} - -func size_new_map(p *Properties, base structPointer) int { - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - n := 0 - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - keycopy.Set(key) - valcopy.Set(val) - - // Tag codes for key and val are the responsibility of the sub-sizer. - keysize := p.mkeyprop.size(p.mkeyprop, keybase) - valsize := p.mvalprop.size(p.mvalprop, valbase) - entry := keysize + valsize - // Add on tag code and length of map entry itself. - n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry - } - return n -} - -// mapEncodeScratch returns a new reflect.Value matching the map's value type, -// and a structPointer suitable for passing to an encoder or sizer. -func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { - // Prepare addressable doubly-indirect placeholders for the key and value types. - // This is needed because the element-type encoders expect **T, but the map iteration produces T. - - keycopy = reflect.New(mapType.Key()).Elem() // addressable K - keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K - keyptr.Set(keycopy.Addr()) // - keybase = toStructPointer(keyptr.Addr()) // **K - - // Value types are more varied and require special handling. - switch mapType.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte - valbase = toStructPointer(valcopy.Addr()) - case reflect.Ptr: - // message; the generated field type is map[K]*Msg (so V is *Msg), - // so we only need one level of indirection. - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valbase = toStructPointer(valcopy.Addr()) - default: - // everything else - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V - valptr.Set(valcopy.Addr()) // - valbase = toStructPointer(valptr.Addr()) // **V - } - return -} - -// Encode a struct. -func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { - var state errorState - // Encode fields in tag order so that decoders may use optimizations - // that depend on the ordering. - // https://developers.google.com/protocol-buffers/docs/encoding#order - for _, i := range prop.order { - p := prop.Prop[i] - if p.enc != nil { - err := p.enc(o, p, base) - if err != nil { - if err == ErrNil { - if p.Required && state.err == nil { - state.err = &RequiredNotSetError{p.Name} - } - } else if err == errRepeatedHasNil { - // Give more context to nil values in repeated fields. - return errors.New("repeated field " + p.OrigName + " has nil element") - } else if !state.shouldContinue(err, p) { - return err - } - } - if len(o.buf) > maxMarshalSize { - return ErrTooLarge - } - } - } - - // Do oneof fields. - if prop.oneofMarshaler != nil { - m := structPointer_Interface(base, prop.stype).(Message) - if err := prop.oneofMarshaler(m, o); err == ErrNil { - return errOneofHasNil - } else if err != nil { - return err - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - if len(o.buf)+len(v) > maxMarshalSize { - return ErrTooLarge - } - if len(v) > 0 { - o.buf = append(o.buf, v...) - } - } - - return state.err -} - -func size_struct(prop *StructProperties, base structPointer) (n int) { - for _, i := range prop.order { - p := prop.Prop[i] - if p.size != nil { - n += p.size(p, base) - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - n += len(v) - } - - // Factor in any oneof fields. - if prop.oneofSizer != nil { - m := structPointer_Interface(base, prop.stype).(Message) - n += prop.oneofSizer(m) - } - - return -} - -var zeroes [20]byte // longer than any conceivable sizeVarint - -// Encode a struct, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { - return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) -} - -// Encode something, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { - iLen := len(o.buf) - o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length - iMsg := len(o.buf) - err := enc() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - lMsg := len(o.buf) - iMsg - lLen := sizeVarint(uint64(lMsg)) - switch x := lLen - (iMsg - iLen); { - case x > 0: // actual length is x bytes larger than the space we reserved - // Move msg x bytes right. - o.buf = append(o.buf, zeroes[:x]...) - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - case x < 0: // actual length is x bytes smaller than the space we reserved - // Move msg x bytes left. - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - o.buf = o.buf[:len(o.buf)+x] // x is negative - } - // Encode the length in the reserved space. - o.buf = o.buf[:iLen] - o.EncodeVarint(uint64(lMsg)) - o.buf = o.buf[:len(o.buf)+lMsg] - return state.err -} - -// errorState maintains the first error that occurs and updates that error -// with additional context. -type errorState struct { - err error -} - -// shouldContinue reports whether encoding should continue upon encountering the -// given error. If the error is RequiredNotSetError, shouldContinue returns true -// and, if this is the first appearance of that error, remembers it for future -// reporting. -// -// If prop is not nil, it may update any error with additional context about the -// field with the error. -func (s *errorState) shouldContinue(err error, prop *Properties) bool { - // Ignore unset required fields. - reqNotSet, ok := err.(*RequiredNotSetError) - if !ok { - return false - } - if s.err == nil { - if prop != nil { - err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} - } - s.err = err - } - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index 2ed1cf5966..0000000000 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,300 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2011 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal. Note a "bytes" field, - although represented by []byte, is not a repeated field and the - rule for the scalar fields described above applies. - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Two map fields are equal iff their lengths are the same, - and they contain the same set of elements. Zero-length map - fields are equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - b1, ok := f1.Interface().(raw) - if ok { - b2 := f2.Interface().(raw) - // RawMessage - if !bytes.Equal(b1.Bytes(), b2.Bytes()) { - return false - } - continue - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_InternalExtensions") - if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - if !bytes.Equal(u1, u2) { - return false - } - - return true -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - // Maps may have nil values in them, so check for nil. - if v1.IsNil() && v2.IsNil() { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// x1 and x2 are InternalExtensions. -func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { - em1, _ := x1.extensionsRead() - em2, _ := x2.extensionsRead() - return equalExtMap(base, em1, em2) -} - -func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - continue - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index eaad218312..0000000000 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,587 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer generated by the current -// proto compiler that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - extensionsWrite() map[int32]Extension - extensionsRead() (map[int32]Extension, sync.Locker) -} - -// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous -// version of the proto compiler that may be extended. -type extendableProtoV1 interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. -type extensionAdapter struct { - extendableProtoV1 -} - -func (e extensionAdapter) extensionsWrite() map[int32]Extension { - return e.ExtensionMap() -} - -func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { - return e.ExtensionMap(), notLocker{} -} - -// notLocker is a sync.Locker whose Lock and Unlock methods are nops. -type notLocker struct{} - -func (n notLocker) Lock() {} -func (n notLocker) Unlock() {} - -// extendable returns the extendableProto interface for the given generated proto message. -// If the proto message has the old extension format, it returns a wrapper that implements -// the extendableProto interface. -func extendable(p interface{}) (extendableProto, bool) { - if ep, ok := p.(extendableProto); ok { - return ep, ok - } - if ep, ok := p.(extendableProtoV1); ok { - return extensionAdapter{ep}, ok - } - return nil, false -} - -// XXX_InternalExtensions is an internal representation of proto extensions. -// -// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, -// thus gaining the unexported 'extensions' method, which can be called only from the proto package. -// -// The methods of XXX_InternalExtensions are not concurrency safe in general, -// but calls to logically read-only methods such as has and get may be executed concurrently. -type XXX_InternalExtensions struct { - // The struct must be indirect so that if a user inadvertently copies a - // generated message and its embedded XXX_InternalExtensions, they - // avoid the mayhem of a copied mutex. - // - // The mutex serializes all logically read-only operations to p.extensionMap. - // It is up to the client to ensure that write operations to p.extensionMap are - // mutually exclusive with other accesses. - p *struct { - mu sync.Mutex - extensionMap map[int32]Extension - } -} - -// extensionsWrite returns the extension map, creating it on first use. -func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { - if e.p == nil { - e.p = new(struct { - mu sync.Mutex - extensionMap map[int32]Extension - }) - e.p.extensionMap = make(map[int32]Extension) - } - return e.p.extensionMap -} - -// extensionsRead returns the extensions map for read-only use. It may be nil. -// The caller must hold the returned mutex's lock when accessing Elements within the map. -func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { - if e.p == nil { - return nil, nil - } - return e.p.extensionMap, &e.p.mu -} - -var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() -var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem() - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style - Filename string // name of the file in which the extension is defined -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base Message, id int32, b []byte) { - epb, ok := extendable(base) - if !ok { - return - } - extmap := epb.extensionsWrite() - extmap[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - var pbi interface{} = pb - // Check the extended type. - if ea, ok := pbi.(extensionAdapter); ok { - pbi = ea.extendableProtoV1 - } - if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { - return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// encode encodes any unmarshaled (unencoded) extensions in e. -func encodeExtensions(e *XXX_InternalExtensions) error { - m, mu := e.extensionsRead() - if m == nil { - return nil // fast path - } - mu.Lock() - defer mu.Unlock() - return encodeExtensionsMap(m) -} - -// encode encodes any unmarshaled (unencoded) extensions in e. -func encodeExtensionsMap(m map[int32]Extension) error { - for k, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - p := NewBuffer(nil) - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { - return err - } - e.enc = p.buf - m[k] = e - } - return nil -} - -func extensionsSize(e *XXX_InternalExtensions) (n int) { - m, mu := e.extensionsRead() - if m == nil { - return 0 - } - mu.Lock() - defer mu.Unlock() - return extensionsMapSize(m) -} - -func extensionsMapSize(m map[int32]Extension) (n int) { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - n += props.size(props, toStructPointer(x)) - } - return -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb Message, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - epb, ok := extendable(pb) - if !ok { - return false - } - extmap, mu := epb.extensionsRead() - if extmap == nil { - return false - } - mu.Lock() - _, ok = extmap[extension.Field] - mu.Unlock() - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb Message, extension *ExtensionDesc) { - epb, ok := extendable(pb) - if !ok { - return - } - // TODO: Check types, field numbers, etc.? - extmap := epb.extensionsWrite() - delete(extmap, extension.Field) -} - -// GetExtension parses and returns the given extension of pb. -// If the extension is not present and has no default value it returns ErrMissingExtension. -func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { - epb, ok := extendable(pb) - if !ok { - return nil, errors.New("proto: not an extendable proto") - } - - if err := checkExtensionTypes(epb, extension); err != nil { - return nil, err - } - - emap, mu := epb.extensionsRead() - if emap == nil { - return defaultExtensionValue(extension) - } - mu.Lock() - defer mu.Unlock() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = v - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return e.value, nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - o := NewBuffer(b) - - t := reflect.TypeOf(extension.ExtensionType) - - props := extensionProperties(extension) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate a "field" to store the pointer/slice itself; the - // pointer/slice will be stored here. We pass - // the address of this field to props.dec. - // This passes a zero field and a *t and lets props.dec - // interpret it as a *struct{ x t }. - value := reflect.New(t).Elem() - - for { - // Discard wire type and field number varint. It isn't needed. - if _, err := o.DecodeVarint(); err != nil { - return nil, err - } - - if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { - return nil, err - } - - if o.index >= len(o.buf) { - break - } - } - return value.Interface(), nil -} - -// GetExtensions returns a slice of the extensions present in pb that are also listed in es. -// The returned slice has the same length as es; missing extensions will appear as nil elements. -func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, ok := extendable(pb) - if !ok { - return nil, errors.New("proto: not an extendable proto") - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. -// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing -// just the Field field, which defines the extension's field number. -func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { - epb, ok := extendable(pb) - if !ok { - return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) - } - registeredExtensions := RegisteredExtensions(pb) - - emap, mu := epb.extensionsRead() - if emap == nil { - return nil, nil - } - mu.Lock() - defer mu.Unlock() - extensions := make([]*ExtensionDesc, 0, len(emap)) - for extid, e := range emap { - desc := e.desc - if desc == nil { - desc = registeredExtensions[extid] - if desc == nil { - desc = &ExtensionDesc{Field: extid} - } - } - - extensions = append(extensions, desc) - } - return extensions, nil -} - -// SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { - epb, ok := extendable(pb) - if !ok { - return errors.New("proto: not an extendable proto") - } - if err := checkExtensionTypes(epb, extension); err != nil { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - extmap := epb.extensionsWrite() - extmap[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// ClearAllExtensions clears all extensions from pb. -func ClearAllExtensions(pb Message) { - epb, ok := extendable(pb) - if !ok { - return - } - m := epb.extensionsWrite() - for k := range m { - delete(m, k) - } -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 1c225504a0..0000000000 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,897 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto converts data structures to and from the wire format of -protocol buffers. It works in concert with the Go source code generated -for .proto files by the protocol compiler. - -A summary of the properties of the protocol buffer interface -for a protocol buffer variable v: - - - Names are turned from camel_case to CamelCase for export. - - There are no methods on v to set fields; just treat - them as structure fields. - - There are getters that return a field's value if set, - and return the field's default value if unset. - The getters work even if the receiver is a nil message. - - The zero value for a struct is its correct initialization state. - All desired fields must be set before marshaling. - - A Reset() method will restore a protobuf struct to its zero state. - - Non-repeated fields are pointers to the values; nil means unset. - That is, optional or required field int32 f becomes F *int32. - - Repeated fields are slices. - - Helper functions are available to aid the setting of fields. - msg.Foo = proto.String("hello") // set field - - Constants are defined to hold the default values of all fields that - have them. They have the form Default_StructName_FieldName. - Because the getter methods handle defaulted values, - direct use of these constants should be rare. - - Enums are given type names and maps from names to values. - Enum values are prefixed by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, groups and enums have type names prefixed with the name of - the surrounding message type. - - Extensions are given descriptor names that start with E_, - followed by an underscore-delimited list of the nested messages - that contain it (if any) followed by the CamelCased name of the - extension field itself. HasExtension, ClearExtension, GetExtension - and SetExtension are functions for manipulating extensions. - - Oneof field sets are given a single field in their message, - with distinguished wrapper types for each possible field value. - - Marshal and Unmarshal are functions to encode and decode the wire format. - -When the .proto file specifies `syntax="proto3"`, there are some differences: - - - Non-repeated fields of non-message type are values instead of pointers. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - package example; - - enum FOO { X = 17; } - - message Test { - required string label = 1; - optional int32 type = 2 [default=77]; - repeated int64 reps = 3; - optional group OptionalGroup = 4 { - required string RequiredField = 5; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - func (x FOO) Enum() *FOO { - p := new(FOO) - *p = x - return p - } - func (x FOO) String() string { - return proto.EnumName(FOO_name, int32(x)) - } - func (x *FOO) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(FOO_value, data) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - type Test struct { - Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"` - Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"` - Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"` - Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"` - // Types that are valid to be assigned to Union: - // *Test_Number - // *Test_Name - Union isTest_Union `protobuf_oneof:"union"` - XXX_unrecognized []byte `json:"-"` - } - func (m *Test) Reset() { *m = Test{} } - func (m *Test) String() string { return proto.CompactTextString(m) } - func (*Test) ProtoMessage() {} - - type isTest_Union interface { - isTest_Union() - } - - type Test_Number struct { - Number int32 `protobuf:"varint,6,opt,name=number"` - } - type Test_Name struct { - Name string `protobuf:"bytes,7,opt,name=name"` - } - - func (*Test_Number) isTest_Union() {} - func (*Test_Name) isTest_Union() {} - - func (m *Test) GetUnion() isTest_Union { - if m != nil { - return m.Union - } - return nil - } - const Default_Test_Type int32 = 77 - - func (m *Test) GetLabel() string { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - return "" - } - - func (m *Test) GetNumber() int32 { - if x, ok := m.GetUnion().(*Test_Number); ok { - return x.Number - } - return 0 - } - - func (m *Test) GetName() string { - if x, ok := m.GetUnion().(*Test_Name); ok { - return x.Name - } - return "" - } - - func init() { - proto.RegisterEnum("example.FOO", FOO_name, FOO_value) - } - -To create and play with a Test object: - - package main - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func main() { - test := &pb.Test{ - Label: proto.String("hello"), - Type: proto.Int32(17), - Reps: []int64{1, 2, 3}, - Optionalgroup: &pb.Test_OptionalGroup{ - RequiredField: proto.String("good bye"), - }, - Union: &pb.Test_Name{"fred"}, - } - data, err := proto.Marshal(test) - if err != nil { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.Test{} - err = proto.Unmarshal(data, newTest) - if err != nil { - log.Fatal("unmarshaling error: ", err) - } - // Now test and newTest contain the same data. - if test.GetLabel() != newTest.GetLabel() { - log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) - } - // Use a type switch to determine which oneof was set. - switch u := test.Union.(type) { - case *pb.Test_Number: // u.Number contains the number. - case *pb.Test_Name: // u.Name contains the string. - } - // etc. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // read point - - // pools of basic types to amortize allocation. - bools []bool - uint32s []uint32 - uint64s []uint64 - - // extra pools, only used with pointer_reflect.go - int32s []int32 - int64s []int64 - float32s []float32 - float64s []float64 -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// Map fields may have key types of non-float scalars, strings and enums. -// The easiest way to sort them in some deterministic order is to use fmt. -// If this turns out to be inefficient we can always consider other options, -// such as doing a Schwartzian transform. - -func mapKeys(vs []reflect.Value) sort.Interface { - s := mapKeySorter{ - vs: vs, - // default Less function: textual comparison - less: func(a, b reflect.Value) bool { - return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface()) - }, - } - - // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps; - // numeric keys are sorted numerically. - if len(vs) == 0 { - return s - } - switch vs[0].Kind() { - case reflect.Int32, reflect.Int64: - s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() } - case reflect.Uint32, reflect.Uint64: - s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() } - } - - return s -} - -type mapKeySorter struct { - vs []reflect.Value - less func(a, b reflect.Value) bool -} - -func (s mapKeySorter) Len() int { return len(s.vs) } -func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] } -func (s mapKeySorter) Less(i, j int) bool { - return s.less(s.vs[i], s.vs[j]) -} - -// isProto3Zero reports whether v is a zero proto3 value. -func isProto3Zero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return !v.Bool() - case reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint32, reflect.Uint64: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.String: - return v.String() == "" - } - return false -} - -// ProtoPackageIsVersion2 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion2 = true - -// ProtoPackageIsVersion1 is referenced from generated protocol buffer files -// to assert that that code is compatible with this version of the proto package. -const ProtoPackageIsVersion1 = true diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index fd982decd6..0000000000 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,311 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" -) - -// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. -// A message type ID is required for storing a protocol buffer in a message set. -var errNoMessageTypeID = errors.New("proto does not have a message type ID") - -// The first two types (_MessageSet_Item and messageSet) -// model what the protocol compiler produces for the following protocol message: -// message MessageSet { -// repeated group Item = 1 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// That is the MessageSet wire format. We can't use a proto to generate these -// because that would introduce a circular dependency between it and this package. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -type messageSet struct { - Item []*_MessageSet_Item `protobuf:"group,1,rep"` - XXX_unrecognized []byte - // TODO: caching? -} - -// Make sure messageSet is a Message. -var _ Message = (*messageSet)(nil) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - if ms.find(pb) != nil { - return true - } - return false -} - -func (ms *messageSet) Unmarshal(pb Message) error { - if item := ms.find(pb); item != nil { - return Unmarshal(item.Message, pb) - } - if _, ok := pb.(messageTypeIder); !ok { - return errNoMessageTypeID - } - return nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -func (ms *messageSet) Reset() { *ms = messageSet{} } -func (ms *messageSet) String() string { return CompactTextString(ms) } -func (*messageSet) ProtoMessage() {} - -// Support for the message_set_wire_format message option. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// MarshalMessageSet encodes the extension map represented by m in the message set wire format. -// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - if err := encodeExtensions(exts); err != nil { - return nil, err - } - m, _ = exts.extensionsRead() - case map[int32]Extension: - if err := encodeExtensionsMap(exts); err != nil { - return nil, err - } - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - - // Sort extension IDs to provide a deterministic encoding. - // See also enc_map in encode.go. - ids := make([]int, 0, len(m)) - for id := range m { - ids = append(ids, int(id)) - } - sort.Ints(ids) - - ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))} - for _, id := range ids { - e := m[int32(id)] - // Remove the wire type and field number varint, as well as the length varint. - msg := skipVarint(skipVarint(e.enc)) - - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: Int32(int32(id)), - Message: msg, - }) - } - return Marshal(ms) -} - -// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. -// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, exts interface{}) error { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m = exts.extensionsWrite() - case map[int32]Extension: - m = exts - default: - return errors.New("proto: not an extension map") - } - - ms := new(messageSet) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// MarshalMessageSetJSON encodes the extension map represented by m in JSON format. -// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { - var m map[int32]Extension - switch exts := exts.(type) { - case *XXX_InternalExtensions: - m, _ = exts.extensionsRead() - case map[int32]Extension: - m = exts - default: - return nil, errors.New("proto: not an extension map") - } - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - if i > 0 { - b.WriteByte(',') - } - - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. -// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index fb512e2e16..0000000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,484 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build appengine js - -// This file contains an implementation of proto field accesses using package reflect. -// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can -// be used on App Engine. - -package proto - -import ( - "math" - "reflect" -) - -// A structPointer is a pointer to a struct. -type structPointer struct { - v reflect.Value -} - -// toStructPointer returns a structPointer equivalent to the given reflect value. -// The reflect value must itself be a pointer to a struct. -func toStructPointer(v reflect.Value) structPointer { - return structPointer{v} -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p.v.IsNil() -} - -// Interface returns the struct pointer as an interface value. -func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { - return p.v.Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// field returns the given field in the struct as a reflect value. -func structPointer_field(p structPointer, f field) reflect.Value { - // Special case: an extension map entry with a value of type T - // passes a *T to the struct-handling code with a zero field, - // expecting that it will be treated as equivalent to *struct{ X T }, - // which has the same memory layout. We have to handle that case - // specially, because reflect will panic if we call FieldByIndex on a - // non-struct. - if f == nil { - return p.v.Elem() - } - - return p.v.Elem().FieldByIndex(f) -} - -// ifield returns the given field in the struct as an interface value. -func structPointer_ifield(p structPointer, f field) interface{} { - return structPointer_field(p, f).Addr().Interface() -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return structPointer_ifield(p, f).(*[]byte) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return structPointer_ifield(p, f).(*[][]byte) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return structPointer_ifield(p, f).(**bool) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return structPointer_ifield(p, f).(*bool) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return structPointer_ifield(p, f).(*[]bool) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return structPointer_ifield(p, f).(**string) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return structPointer_ifield(p, f).(*string) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return structPointer_ifield(p, f).(*[]string) -} - -// Extensions returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return structPointer_ifield(p, f).(*XXX_InternalExtensions) -} - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return structPointer_ifield(p, f).(*map[int32]Extension) -} - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return structPointer_field(p, f).Addr() -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - structPointer_field(p, f).Set(q.v) -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return structPointer{structPointer_field(p, f)} -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { - return structPointerSlice{structPointer_field(p, f)} -} - -// A structPointerSlice represents the address of a slice of pointers to structs -// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. -type structPointerSlice struct { - v reflect.Value -} - -func (p structPointerSlice) Len() int { return p.v.Len() } -func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } -func (p structPointerSlice) Append(q structPointer) { - p.v.Set(reflect.Append(p.v, q.v)) -} - -var ( - int32Type = reflect.TypeOf(int32(0)) - uint32Type = reflect.TypeOf(uint32(0)) - float32Type = reflect.TypeOf(float32(0)) - int64Type = reflect.TypeOf(int64(0)) - uint64Type = reflect.TypeOf(uint64(0)) - float64Type = reflect.TypeOf(float64(0)) -) - -// A word32 represents a field of type *int32, *uint32, *float32, or *enum. -// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. -type word32 struct { - v reflect.Value -} - -// IsNil reports whether p is nil. -func word32_IsNil(p word32) bool { - return p.v.IsNil() -} - -// Set sets p to point at a newly allocated word with bits set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - t := p.v.Type().Elem() - switch t { - case int32Type: - if len(o.int32s) == 0 { - o.int32s = make([]int32, uint32PoolSize) - } - o.int32s[0] = int32(x) - p.v.Set(reflect.ValueOf(&o.int32s[0])) - o.int32s = o.int32s[1:] - return - case uint32Type: - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - p.v.Set(reflect.ValueOf(&o.uint32s[0])) - o.uint32s = o.uint32s[1:] - return - case float32Type: - if len(o.float32s) == 0 { - o.float32s = make([]float32, uint32PoolSize) - } - o.float32s[0] = math.Float32frombits(x) - p.v.Set(reflect.ValueOf(&o.float32s[0])) - o.float32s = o.float32s[1:] - return - } - - // must be enum - p.v.Set(reflect.New(t)) - p.v.Elem().SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32_Get(p word32) uint32 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32{structPointer_field(p, f)} -} - -// A word32Val represents a field of type int32, uint32, float32, or enum. -// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. -type word32Val struct { - v reflect.Value -} - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - switch p.v.Type() { - case int32Type: - p.v.SetInt(int64(x)) - return - case uint32Type: - p.v.SetUint(uint64(x)) - return - case float32Type: - p.v.SetFloat(float64(math.Float32frombits(x))) - return - } - - // must be enum - p.v.SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32Val_Get(p word32Val) uint32 { - elem := p.v - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val{structPointer_field(p, f)} -} - -// A word32Slice is a slice of 32-bit values. -// That is, v.Type() is []int32, []uint32, []float32, or []enum. -type word32Slice struct { - v reflect.Value -} - -func (p word32Slice) Append(x uint32) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int32: - elem.SetInt(int64(int32(x))) - case reflect.Uint32: - elem.SetUint(uint64(x)) - case reflect.Float32: - elem.SetFloat(float64(math.Float32frombits(x))) - } -} - -func (p word32Slice) Len() int { - return p.v.Len() -} - -func (p word32Slice) Index(i int) uint32 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) word32Slice { - return word32Slice{structPointer_field(p, f)} -} - -// word64 is like word32 but for 64-bit values. -type word64 struct { - v reflect.Value -} - -func word64_Set(p word64, o *Buffer, x uint64) { - t := p.v.Type().Elem() - switch t { - case int64Type: - if len(o.int64s) == 0 { - o.int64s = make([]int64, uint64PoolSize) - } - o.int64s[0] = int64(x) - p.v.Set(reflect.ValueOf(&o.int64s[0])) - o.int64s = o.int64s[1:] - return - case uint64Type: - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - p.v.Set(reflect.ValueOf(&o.uint64s[0])) - o.uint64s = o.uint64s[1:] - return - case float64Type: - if len(o.float64s) == 0 { - o.float64s = make([]float64, uint64PoolSize) - } - o.float64s[0] = math.Float64frombits(x) - p.v.Set(reflect.ValueOf(&o.float64s[0])) - o.float64s = o.float64s[1:] - return - } - panic("unreachable") -} - -func word64_IsNil(p word64) bool { - return p.v.IsNil() -} - -func word64_Get(p word64) uint64 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64{structPointer_field(p, f)} -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val struct { - v reflect.Value -} - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - switch p.v.Type() { - case int64Type: - p.v.SetInt(int64(x)) - return - case uint64Type: - p.v.SetUint(x) - return - case float64Type: - p.v.SetFloat(math.Float64frombits(x)) - return - } - panic("unreachable") -} - -func word64Val_Get(p word64Val) uint64 { - elem := p.v - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val{structPointer_field(p, f)} -} - -type word64Slice struct { - v reflect.Value -} - -func (p word64Slice) Append(x uint64) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int64: - elem.SetInt(int64(int64(x))) - case reflect.Uint64: - elem.SetUint(uint64(x)) - case reflect.Float64: - elem.SetFloat(float64(math.Float64frombits(x))) - } -} - -func (p word64Slice) Len() int { - return p.v.Len() -} - -func (p word64Slice) Index(i int) uint64 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return uint64(elem.Uint()) - case reflect.Float64: - return math.Float64bits(float64(elem.Float())) - } - panic("unreachable") -} - -func structPointer_Word64Slice(p structPointer, f field) word64Slice { - return word64Slice{structPointer_field(p, f)} -} diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index 6b5567d47c..0000000000 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,270 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2012 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -// +build !appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "unsafe" -) - -// NOTE: These type_Foo functions would more idiomatically be methods, -// but Go does not allow methods on pointer types, and we must preserve -// some pointer type for the garbage collector. We use these -// funcs with clunky names as our poor approximation to methods. -// -// An alternative would be -// type structPointer struct { p unsafe.Pointer } -// but that does not registerize as well. - -// A structPointer is a pointer to a struct. -type structPointer unsafe.Pointer - -// toStructPointer returns a structPointer equivalent to the given reflect value. -func toStructPointer(v reflect.Value) structPointer { - return structPointer(unsafe.Pointer(v.Pointer())) -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p == nil -} - -// Interface returns the struct pointer, assumed to have element type t, -// as an interface value. -func structPointer_Interface(p structPointer, t reflect.Type) interface{} { - return reflect.NewAt(t, unsafe.Pointer(p)).Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != ^field(0) -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { - return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// NewAt returns the reflect.Value for a pointer to a field in the struct. -func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value { - return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f))) -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { - return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). -type structPointerSlice []structPointer - -func (v *structPointerSlice) Len() int { return len(*v) } -func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } -func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } - -// A word32 is the address of a "pointer to 32-bit value" field. -type word32 **uint32 - -// IsNil reports whether *v is nil. -func word32_IsNil(p word32) bool { - return *p == nil -} - -// Set sets *v to point at a newly allocated word set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - *p = &o.uint32s[0] - o.uint32s = o.uint32s[1:] -} - -// Get gets the value pointed at by *v. -func word32_Get(p word32) uint32 { - return **p -} - -// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Val is the address of a 32-bit value field. -type word32Val *uint32 - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - *p = x -} - -// Get gets the value pointed at by p. -func word32Val_Get(p word32Val) uint32 { - return *p -} - -// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Slice is a slice of 32-bit values. -type word32Slice []uint32 - -func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } -func (v *word32Slice) Len() int { return len(*v) } -func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } - -// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) *word32Slice { - return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// word64 is like word32 but for 64-bit values. -type word64 **uint64 - -func word64_Set(p word64, o *Buffer, x uint64) { - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - *p = &o.uint64s[0] - o.uint64s = o.uint64s[1:] -} - -func word64_IsNil(p word64) bool { - return *p == nil -} - -func word64_Get(p word64) uint64 { - return **p -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val *uint64 - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - *p = x -} - -func word64Val_Get(p word64Val) uint64 { - return *p -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Slice is like word32Slice but for 64-bit values. -type word64Slice []uint64 - -func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } -func (v *word64Slice) Len() int { return len(*v) } -func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } - -func structPointer_Word64Slice(p structPointer, f field) *word64Slice { - return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index ec2289c005..0000000000 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,872 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -const startSize = 10 // initial slice/string sizes - -// Encoders are defined in encode.go -// An encoder outputs the full representation of a field, including its -// tag and encoder type. -type encoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueEncoder encodes a single integer in a particular encoding. -type valueEncoder func(o *Buffer, x uint64) error - -// Sizers are defined in encode.go -// A sizer returns the encoded size of a field, including its tag and encoder -// type. -type sizer func(prop *Properties, base structPointer) int - -// A valueSizer returns the encoded size of a single integer in a particular -// encoding. -type valueSizer func(x uint64) int - -// Decoders are defined in decode.go -// A decoder creates a value from its wire representation. -// Unrecognized subelements are saved in unrec. -type decoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueDecoder decodes a single integer in a particular encoding. -type valueDecoder func(o *Buffer) (x uint64, err error) - -// A oneofMarshaler does the marshaling for all oneof fields in a message. -type oneofMarshaler func(Message, *Buffer) error - -// A oneofUnmarshaler does the unmarshaling for a oneof field in a message. -type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error) - -// A oneofSizer does the sizing for all oneof fields in a message. -type oneofSizer func(Message) int - -// tagMap is an optimization over map[int]int for typical protocol buffer -// use-cases. Encoded protocol buffers are often in tag order with small tag -// numbers. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - order []int // list of struct field numbers in tag order - unrecField field // field id of the XXX_unrecognized []byte field - extendable bool // is this an extendable proto - - oneofMarshaler oneofMarshaler - oneofUnmarshaler oneofUnmarshaler - oneofSizer oneofSizer - stype reflect.Type - - // OneofTypes contains information about the oneof fields in this message. - // It is keyed by the original name of a field. - OneofTypes map[string]*OneofProperties -} - -// OneofProperties represents information about a specific field in a oneof. -type OneofProperties struct { - Type reflect.Type // pointer to generated struct type for this oneof field - Field int // struct field number of the containing oneof in the message - Prop *Properties -} - -// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -type Properties struct { - Name string // name of the field, for error messages - OrigName string // original name before protocol compiler (always set) - JSONName string // name to use for JSON; determined by protoc - Wire string - WireType int - Tag int - Required bool - Optional bool - Repeated bool - Packed bool // relevant for repeated primitives only - Enum string // set for enum types only - proto3 bool // whether this is known to be a proto3 field; set for []byte only - oneof bool // whether this is a oneof field - - Default string // default value - HasDefault bool // whether an explicit default was provided - def_uint64 uint64 - - enc encoder - valEnc valueEncoder // set for bool and numeric types only - field field - tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) - tagbuf [8]byte - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - isMarshaler bool - isUnmarshaler bool - - mtype reflect.Type // set for map types only - mkeyprop *Properties // set for map types only - mvalprop *Properties // set for map types only - - size sizer - valSize valueSizer // set for bool and numeric types only - - dec decoder - valDec valueDecoder // set for bool and numeric types only - - // If this is a packable field, this will be the decoder for the packed version of the field. - packedDec decoder -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s = "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - s += ",name=" + p.OrigName - if p.JSONName != p.OrigName { - s += ",json=" + p.JSONName - } - if p.proto3 { - s += ",proto3" - } - if p.oneof { - s += ",oneof" - } - if len(p.Enum) > 0 { - s += ",enum=" + p.Enum - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeVarint - p.valDec = (*Buffer).DecodeVarint - p.valSize = sizeVarint - case "fixed32": - p.WireType = WireFixed32 - p.valEnc = (*Buffer).EncodeFixed32 - p.valDec = (*Buffer).DecodeFixed32 - p.valSize = sizeFixed32 - case "fixed64": - p.WireType = WireFixed64 - p.valEnc = (*Buffer).EncodeFixed64 - p.valDec = (*Buffer).DecodeFixed64 - p.valSize = sizeFixed64 - case "zigzag32": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag32 - p.valDec = (*Buffer).DecodeZigzag32 - p.valSize = sizeZigzag32 - case "zigzag64": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag64 - p.valDec = (*Buffer).DecodeZigzag64 - p.valSize = sizeZigzag64 - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - p.Packed = true - case strings.HasPrefix(f, "name="): - p.OrigName = f[5:] - case strings.HasPrefix(f, "json="): - p.JSONName = f[5:] - case strings.HasPrefix(f, "enum="): - p.Enum = f[5:] - case f == "proto3": - p.proto3 = true - case f == "oneof": - p.oneof = true - case strings.HasPrefix(f, "def="): - p.HasDefault = true - p.Default = f[4:] // rest of string - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break - } - } - } -} - -func logNoSliceEnc(t1, t2 reflect.Type) { - fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// Initialize the fields for encoding and decoding. -func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - p.enc = nil - p.dec = nil - p.size = nil - - switch t1 := typ; t1.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) - - // proto3 scalar types - - case reflect.Bool: - p.enc = (*Buffer).enc_proto3_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_proto3_bool - case reflect.Int32: - p.enc = (*Buffer).enc_proto3_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_proto3_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_proto3_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_proto3_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.String: - p.enc = (*Buffer).enc_proto3_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_proto3_string - - case reflect.Ptr: - switch t2 := t1.Elem(); t2.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) - break - case reflect.Bool: - p.enc = (*Buffer).enc_bool - p.dec = (*Buffer).dec_bool - p.size = size_bool - case reflect.Int32: - p.enc = (*Buffer).enc_int32 - p.dec = (*Buffer).dec_int32 - p.size = size_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_uint32 - p.dec = (*Buffer).dec_int32 // can reuse - p.size = size_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_int64 - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_int32 - p.size = size_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_int64 // can just treat them as bits - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.String: - p.enc = (*Buffer).enc_string - p.dec = (*Buffer).dec_string - p.size = size_string - case reflect.Struct: - p.stype = t1.Elem() - p.isMarshaler = isMarshaler(t1) - p.isUnmarshaler = isUnmarshaler(t1) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_struct_message - p.dec = (*Buffer).dec_struct_message - p.size = size_struct_message - } else { - p.enc = (*Buffer).enc_struct_group - p.dec = (*Buffer).dec_struct_group - p.size = size_struct_group - } - } - - case reflect.Slice: - switch t2 := t1.Elem(); t2.Kind() { - default: - logNoSliceEnc(t1, t2) - break - case reflect.Bool: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_bool - p.size = size_slice_packed_bool - } else { - p.enc = (*Buffer).enc_slice_bool - p.size = size_slice_bool - } - p.dec = (*Buffer).dec_slice_bool - p.packedDec = (*Buffer).dec_slice_packed_bool - case reflect.Int32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int32 - p.size = size_slice_packed_int32 - } else { - p.enc = (*Buffer).enc_slice_int32 - p.size = size_slice_int32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Uint32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Int64, reflect.Uint64: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - case reflect.Uint8: - p.dec = (*Buffer).dec_slice_byte - if p.proto3 { - p.enc = (*Buffer).enc_proto3_slice_byte - p.size = size_proto3_slice_byte - } else { - p.enc = (*Buffer).enc_slice_byte - p.size = size_slice_byte - } - case reflect.Float32, reflect.Float64: - switch t2.Bits() { - case 32: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case 64: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - default: - logNoSliceEnc(t1, t2) - break - } - case reflect.String: - p.enc = (*Buffer).enc_slice_string - p.dec = (*Buffer).dec_slice_string - p.size = size_slice_string - case reflect.Ptr: - switch t3 := t2.Elem(); t3.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) - break - case reflect.Struct: - p.stype = t2.Elem() - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_slice_struct_message - p.dec = (*Buffer).dec_slice_struct_message - p.size = size_slice_struct_message - } else { - p.enc = (*Buffer).enc_slice_struct_group - p.dec = (*Buffer).dec_slice_struct_group - p.size = size_slice_struct_group - } - } - case reflect.Slice: - switch t2.Elem().Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) - break - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_slice_byte - p.dec = (*Buffer).dec_slice_slice_byte - p.size = size_slice_slice_byte - } - } - - case reflect.Map: - p.enc = (*Buffer).enc_new_map - p.dec = (*Buffer).dec_new_map - p.size = size_new_map - - p.mtype = t1 - p.mkeyprop = &Properties{} - p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.mvalprop = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - // precalculate tag code - wire := p.WireType - if p.Packed { - wire = WireBytes - } - x := uint32(p.Tag)<<3 | uint32(wire) - i := 0 - for i = 0; x > 127; i++ { - p.tagbuf[i] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - p.tagbuf[i] = uint8(x) - p.tagcode = p.tagbuf[0 : i+1] - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() -) - -// isMarshaler reports whether type t implements Marshaler. -func isMarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isMarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isMarshaler") - } - return t.Implements(marshalerType) -} - -// isUnmarshaler reports whether type t implements Unmarshaler. -func isUnmarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isUnmarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isUnmarshaler") - } - return t.Implements(unmarshalerType) -} - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if f != nil { - p.field = toField(f) - } - if tag == "" { - return - } - p.Parse(tag) - p.setEncAndDec(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - if collectStats { - stats.Chit++ - } - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } - return prop - } - if collectStats { - stats.Cmiss++ - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || - reflect.PtrTo(t).Implements(extendableProtoV1Type) - prop.unrecField = invalidField - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - if f.Name == "XXX_InternalExtensions" { // special case - p.enc = (*Buffer).enc_exts - p.dec = nil // not needed - p.size = size_exts - } else if f.Name == "XXX_extensions" { // special case - p.enc = (*Buffer).enc_map - p.dec = nil // not needed - p.size = size_map - } else if f.Name == "XXX_unrecognized" { // special case - prop.unrecField = toField(&f) - } - oneof := f.Tag.Get("protobuf_oneof") // special case - if oneof != "" { - // Oneof fields don't use the traditional protobuf tag. - p.OrigName = oneof - } - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { - fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") - } - } - - // Re-order prop.order. - sort.Sort(prop) - - type oneofMessage interface { - XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{}) - } - if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok { - var oots []interface{} - prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs() - prop.stype = t - - // Interpret oneof metadata. - prop.OneofTypes = make(map[string]*OneofProperties) - for _, oot := range oots { - oop := &OneofProperties{ - Type: reflect.ValueOf(oot).Type(), // *T - Prop: new(Properties), - } - sft := oop.Type.Elem().Field(0) - oop.Prop.Name = sft.Name - oop.Prop.Parse(sft.Tag.Get("protobuf")) - // There will be exactly one interface field that - // this new value is assignable to. - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if f.Type.Kind() != reflect.Interface { - continue - } - if !oop.Type.AssignableTo(f.Type) { - continue - } - oop.Field = i - break - } - prop.OneofTypes[oop.Prop.OrigName] = oop - } - } - - // build required counts - // build tags - reqCount := 0 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// Return the Properties object for the x[0]'th field of the structure. -func propByIndex(t reflect.Type, x []int) *Properties { - if len(x) != 1 { - fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) - return nil - } - prop := GetProperties(t) - return prop.Prop[x[0]] -} - -// Get the address and type of a pointer to a struct from an interface. -func getbase(pb Message) (t reflect.Type, b structPointer, err error) { - if pb == nil { - err = ErrNil - return - } - // get the reflect type of the pointer to the struct. - t = reflect.TypeOf(pb) - // get the address of the struct. - value := reflect.ValueOf(pb) - b = toStructPointer(value) - return -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - enumValueMaps[typeName] = valueMap -} - -// EnumValueMap returns the mapping from names to integers of the -// enum type enumType, or a nil if not found. -func EnumValueMap(enumType string) map[string]int32 { - return enumValueMaps[enumType] -} - -// A registry of all linked message types. -// The string is a fully-qualified proto name ("pkg.Message"). -var ( - protoTypes = make(map[string]reflect.Type) - revProtoTypes = make(map[reflect.Type]string) -) - -// RegisterType is called from generated code and maps from the fully qualified -// proto name to the type (pointer to struct) of the protocol buffer. -func RegisterType(x Message, name string) { - if _, ok := protoTypes[name]; ok { - // TODO: Some day, make this a panic. - log.Printf("proto: duplicate proto type registered: %s", name) - return - } - t := reflect.TypeOf(x) - protoTypes[name] = t - revProtoTypes[t] = name -} - -// MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { - type xname interface { - XXX_MessageName() string - } - if m, ok := x.(xname); ok { - return m.XXX_MessageName() - } - return revProtoTypes[reflect.TypeOf(x)] -} - -// MessageType returns the message type (pointer to struct) for a named message. -func MessageType(name string) reflect.Type { return protoTypes[name] } - -// A registry of all linked proto files. -var ( - protoFiles = make(map[string][]byte) // file name => fileDescriptor -) - -// RegisterFile is called from generated code and maps from the -// full file name of a .proto file to its compressed FileDescriptorProto. -func RegisterFile(filename string, fileDescriptor []byte) { - protoFiles[filename] = fileDescriptor -} - -// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. -func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 965876bf03..0000000000 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,854 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - gtNewline = []byte(">\n") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Print("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -// raw is the interface satisfied by RawMessage. -type raw interface { - Bytes() []byte -} - -func requiresQuotes(u string) bool { - // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. - for _, ch := range u { - switch { - case ch == '.' || ch == '/' || ch == '_': - continue - case '0' <= ch && ch <= '9': - continue - case 'A' <= ch && ch <= 'Z': - continue - case 'a' <= ch && ch <= 'z': - continue - default: - return true - } - } - return false -} - -// isAny reports whether sv is a google.protobuf.Any message -func isAny(sv reflect.Value) bool { - type wkt interface { - XXX_WellKnownType() string - } - t, ok := sv.Addr().Interface().(wkt) - return ok && t.XXX_WellKnownType() == "Any" -} - -// writeProto3Any writes an expanded google.protobuf.Any message. -// -// It returns (false, nil) if sv value can't be unmarshaled (e.g. because -// required messages are not linked in). -// -// It returns (true, error) when sv was written in expanded format or an error -// was encountered. -func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { - turl := sv.FieldByName("TypeUrl") - val := sv.FieldByName("Value") - if !turl.IsValid() || !val.IsValid() { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - b, ok := val.Interface().([]byte) - if !ok { - return true, errors.New("proto: invalid google.protobuf.Any message") - } - - parts := strings.Split(turl.String(), "/") - mt := MessageType(parts[len(parts)-1]) - if mt == nil { - return false, nil - } - m := reflect.New(mt.Elem()) - if err := Unmarshal(b, m.Interface().(Message)); err != nil { - return false, nil - } - w.Write([]byte("[")) - u := turl.String() - if requiresQuotes(u) { - writeString(w, u) - } else { - w.Write([]byte(u)) - } - if w.compact { - w.Write([]byte("]:<")) - } else { - w.Write([]byte("]: <\n")) - w.ind++ - } - if err := tm.writeStruct(w, m.Elem()); err != nil { - return true, err - } - if w.compact { - w.Write([]byte("> ")) - } else { - w.ind-- - w.Write([]byte(">\n")) - } - return true, nil -} - -func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { - if tm.ExpandAny && isAny(sv) { - if canExpand, err := tm.writeProto3Any(w, sv); canExpand { - return err - } - } - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < sv.NumField(); i++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.mkeyprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - if isProto3Zero(fv) { - continue - } - } - - if fv.Kind() == reflect.Interface { - // Check if it is a oneof. - if st.Field(i).Tag.Get("protobuf_oneof") != "" { - // fv is nil, or holds a pointer to generated struct. - // That generated struct has exactly one field, - // which has a protobuf struct tag. - if fv.IsNil() { - continue - } - inner := fv.Elem().Elem() // interface -> *T -> T - tag := inner.Type().Field(0).Tag.Get("protobuf") - props = new(Properties) // Overwrite the outer props var, but not its pointee. - props.Parse(tag) - // Write the value in the oneof, not the oneof itself. - fv = inner.Field(0) - - // Special case to cope with malformed messages gracefully: - // If the value in the oneof is a nil pointer, don't panic - // in writeAny. - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Use errors.New so writeAny won't render quotes. - msg := errors.New("/* nil */") - fv = reflect.ValueOf(&msg).Elem() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if b, ok := fv.Interface().(raw); ok { - if err := writeRaw(w, b.Bytes()); err != nil { - return err - } - continue - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if _, ok := extendable(pv.Interface()); ok { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeRaw writes an uninterpreted raw message. -func writeRaw(w *textWriter, b []byte) error { - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if err := writeUnknownStruct(w, b); err != nil { - return err - } - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - switch v.Kind() { - case reflect.Slice: - // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Bytes())); err != nil { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if etm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = w.Write(text); err != nil { - return err - } - } else if err := tm.writeStruct(w, v); err != nil { - return err - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -func (s int32Slice) Len() int { return len(s) } -func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } -func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep, _ := extendable(pv.Interface()) - - // Order the extensions by ID. - // This isn't strictly necessary, but it will give us - // canonical output, which will also make testing easier. - m, mu := ep.extensionsRead() - if m == nil { - return nil - } - mu.Lock() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - mu.Unlock() - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - if err := tm.writeExtension(w, desc.Name, pb); err != nil { - return err - } - } else { - v := reflect.ValueOf(pb) - for i := 0; i < v.Len(); i++ { - if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// TextMarshaler is a configurable text format marshaler. -type TextMarshaler struct { - Compact bool // use compact text format (one line). - ExpandAny bool // expand google.protobuf.Any messages of known types -} - -// Marshal writes a given protocol buffer in text format. -// The only errors returned are from w. -func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { - val := reflect.ValueOf(pb) - if pb == nil || val.IsNil() { - w.Write([]byte("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil -} - -// Text is the same as Marshal, but returns the string directly. -func (tm *TextMarshaler) Text(pb Message) string { - var buf bytes.Buffer - tm.Marshal(&buf, pb) - return buf.String() -} - -var ( - defaultTextMarshaler = TextMarshaler{} - compactTextMarshaler = TextMarshaler{Compact: true} -) - -// TODO: consider removing some of the Marshal functions below. - -// MarshalText writes a given protocol buffer in text format. -// The only errors returned are from w. -func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } - -// CompactText writes a given protocol buffer in compact text format (one line). -func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index 5e14513f28..0000000000 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,895 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -// Error string emitted when deserializing Any and fields are already set -const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - return false -} - -func isQuote(c byte) bool { - switch c { - case '"', '\'': - return true - } - return false -} - -func (p *textParser) skipWhitespace() { - i := 0 - for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) - return - } - p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") - errBadHex = errors.New("proto: bad hexadecimal") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - base := 8 - ss := s[:2] - s = s[2:] - if r == 'x' || r == 'X' { - base = 16 - } else { - ss = string(r) + ss - } - i, err := strconv.ParseUint(ss, base, 8) - if err != nil { - return "", "", err - } - return string([]byte{byte(i)}), s, nil - case 'u', 'U': - n := 4 - if r == 'U' { - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) - } - - bs := make([]byte, n/2) - for i := 0; i < n; i += 2 { - a, ok1 := unhex(s[i]) - b, ok2 := unhex(s[i+1]) - if !ok1 || !ok2 { - return "", "", errBadHex - } - bs[i/2] = a<<4 | b - } - s = s[n:] - return string(bs), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Adapted from src/pkg/strconv/quote.go. -func unhex(b byte) (v byte, ok bool) { - switch { - case '0' <= b && b <= '9': - return b - '0', true - case 'a' <= b && b <= 'f': - return b - 'a' + 10, true - case 'A' <= b && b <= 'F': - return b - 'A' + 10, true - } - return 0, false -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { - // Look for multiple quoted strings separated by whitespace, - // and concatenate them. - cat := p.cur - for { - p.skipWhitespace() - if p.done || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - sprops := GetProperties(st) - reqCount := sprops.reqCount - var reqFieldErr error - fieldSet := make(map[string]bool) - // A struct is a sequence of "name: value", terminated by one of - // '>' or '}', or the end of the input. A name may also be - // "[extension]" or "[type/url]". - // - // The whole struct can also be an expanded Any message, like: - // [type/url] < ... struct contents ... > - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - extName, err := p.consumeExtName() - if err != nil { - return err - } - - if s := strings.LastIndex(extName, "/"); s >= 0 { - // If it contains a slash, it's an Any type URL. - messageName := extName[s+1:] - mt := MessageType(messageName) - if mt == nil { - return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) - } - tok = p.next() - if tok.err != nil { - return tok.err - } - // consume an optional colon - if tok.value == ":" { - tok = p.next() - if tok.err != nil { - return tok.err - } - } - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - v := reflect.New(mt.Elem()) - if pe := p.readStruct(v.Elem(), terminator); pe != nil { - return pe - } - b, err := Marshal(v.Interface().(Message)) - if err != nil { - return p.errorf("failed to marshal message of type %q: %v", messageName, err) - } - if fieldSet["type_url"] { - return p.errorf(anyRepeatedlyUnpacked, "type_url") - } - if fieldSet["value"] { - return p.errorf(anyRepeatedlyUnpacked, "value") - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - fieldSet["type_url"] = true - fieldSet["value"] = true - continue - } - - var desc *ExtensionDesc - // This could be faster, but it's functional. - // TODO: Do something smarter than a linear scan. - for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(Message) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - continue - } - - // This is a normal, non-extension field. - name := tok.value - var dst reflect.Value - fi, props, ok := structFieldByName(sprops, name) - if ok { - dst = sv.Field(fi) - } else if oop, ok := sprops.OneofTypes[name]; ok { - // It is a oneof. - props = oop.Prop - nv := reflect.New(oop.Type.Elem()) - dst = nv.Elem().Field(0) - field := sv.Field(oop.Field) - if !field.IsNil() { - return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) - } - field.Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - if dst.Kind() == reflect.Map { - // Consume any colon. - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Construct the map if it doesn't already exist. - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - key := reflect.New(dst.Type().Key()).Elem() - val := reflect.New(dst.Type().Elem()).Elem() - - // The map entry should be this sequence of tokens: - // < key : KEY value : VALUE > - // However, implementations may omit key or value, and technically - // we should support them in any order. See b/28924776 for a time - // this went wrong. - - tok := p.next() - var terminator string - switch tok.value { - case "<": - terminator = ">" - case "{": - terminator = "}" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - for { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == terminator { - break - } - switch tok.value { - case "key": - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - case "value": - if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - default: - p.back() - return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) - } - } - - dst.SetMapIndex(key, val) - continue - } - - // Check that it's not already set if it's not a repeated field. - if !props.Repeated && fieldSet[name] { - return p.errorf("non-repeated field %q was repeated", name) - } - - if err := p.checkForColon(props, dst.Type()); err != nil { - return err - } - - // Parse into the field. - fieldSet[name] = true - if err := p.readAny(dst, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - return reqFieldErr -} - -// consumeExtName consumes extension name or expanded Any type URL and the -// following ']'. It returns the name or URL consumed. -func (p *textParser) consumeExtName() (string, error) { - tok := p.next() - if tok.err != nil { - return "", tok.err - } - - // If extension name or type url is quoted, it's a single token. - if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { - name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) - if err != nil { - return "", err - } - return name, p.consumeToken("]") - } - - // Consume everything up to "]" - var parts []string - for tok.value != "]" { - parts = append(parts, tok.value) - tok = p.next() - if tok.err != nil { - return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) - } - } - return strings.Join(parts, ""), nil -} - -// consumeOptionalSeparator consumes an optional semicolon or comma. -// It is used in readStruct to provide backward compatibility. -func (p *textParser) consumeOptionalSeparator() error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // Repeated field. - if tok.value == "[" { - // Repeated field with list notation, like [1,2,3]. - for { - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - err := p.readAny(fv.Index(fv.Len()-1), props) - if err != nil { - return err - } - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "]" { - break - } - if tok.value != "," { - return p.errorf("Expected ']' or ',' found %q", tok.value) - } - } - return nil - } - // One value of the repeated field. - p.back() - fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) - return p.readAny(fv.Index(fv.Len()-1), props) - case reflect.Bool: - // true/1/t/True or false/f/0/False. - switch tok.value { - case "true", "1", "t", "True": - fv.SetBool(true) - return nil - case "false", "0", "f", "False": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(x) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - err := um.UnmarshalText([]byte(s)) - return err - } - pb.Reset() - v := reflect.ValueOf(pb) - if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { - return pe - } - return nil -} diff --git a/vendor/github.com/google/go-github/LICENSE b/vendor/github.com/google/go-github/LICENSE deleted file mode 100644 index 53d5374a71..0000000000 --- a/vendor/github.com/google/go-github/LICENSE +++ /dev/null @@ -1,341 +0,0 @@ -Copyright (c) 2013 The go-github AUTHORS. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ----------- - -Some documentation is taken from the GitHub Developer site -, which is available under the following Creative -Commons Attribution 3.0 License. This applies only to the go-github source -code and would not apply to any compiled binaries. - -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE -COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY -COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS -AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE -TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY -BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS -CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND -CONDITIONS. - -1. Definitions - - a. "Adaptation" means a work based upon the Work, or upon the Work and - other pre-existing works, such as a translation, adaptation, - derivative work, arrangement of music or other alterations of a - literary or artistic work, or phonogram or performance and includes - cinematographic adaptations or any other form in which the Work may be - recast, transformed, or adapted including in any form recognizably - derived from the original, except that a work that constitutes a - Collection will not be considered an Adaptation for the purpose of - this License. For the avoidance of doubt, where the Work is a musical - work, performance or phonogram, the synchronization of the Work in - timed-relation with a moving image ("synching") will be considered an - Adaptation for the purpose of this License. - b. "Collection" means a collection of literary or artistic works, such as - encyclopedias and anthologies, or performances, phonograms or - broadcasts, or other works or subject matter other than works listed - in Section 1(f) below, which, by reason of the selection and - arrangement of their contents, constitute intellectual creations, in - which the Work is included in its entirety in unmodified form along - with one or more other contributions, each constituting separate and - independent works in themselves, which together are assembled into a - collective whole. A work that constitutes a Collection will not be - considered an Adaptation (as defined above) for the purposes of this - License. - c. "Distribute" means to make available to the public the original and - copies of the Work or Adaptation, as appropriate, through sale or - other transfer of ownership. - d. "Licensor" means the individual, individuals, entity or entities that - offer(s) the Work under the terms of this License. - e. "Original Author" means, in the case of a literary or artistic work, - the individual, individuals, entity or entities who created the Work - or if no individual or entity can be identified, the publisher; and in - addition (i) in the case of a performance the actors, singers, - musicians, dancers, and other persons who act, sing, deliver, declaim, - play in, interpret or otherwise perform literary or artistic works or - expressions of folklore; (ii) in the case of a phonogram the producer - being the person or legal entity who first fixes the sounds of a - performance or other sounds; and, (iii) in the case of broadcasts, the - organization that transmits the broadcast. - f. "Work" means the literary and/or artistic work offered under the terms - of this License including without limitation any production in the - literary, scientific and artistic domain, whatever may be the mode or - form of its expression including digital form, such as a book, - pamphlet and other writing; a lecture, address, sermon or other work - of the same nature; a dramatic or dramatico-musical work; a - choreographic work or entertainment in dumb show; a musical - composition with or without words; a cinematographic work to which are - assimilated works expressed by a process analogous to cinematography; - a work of drawing, painting, architecture, sculpture, engraving or - lithography; a photographic work to which are assimilated works - expressed by a process analogous to photography; a work of applied - art; an illustration, map, plan, sketch or three-dimensional work - relative to geography, topography, architecture or science; a - performance; a broadcast; a phonogram; a compilation of data to the - extent it is protected as a copyrightable work; or a work performed by - a variety or circus performer to the extent it is not otherwise - considered a literary or artistic work. - g. "You" means an individual or entity exercising rights under this - License who has not previously violated the terms of this License with - respect to the Work, or who has received express permission from the - Licensor to exercise rights under this License despite a previous - violation. - h. "Publicly Perform" means to perform public recitations of the Work and - to communicate to the public those public recitations, by any means or - process, including by wire or wireless means or public digital - performances; to make available to the public Works in such a way that - members of the public may access these Works from a place and at a - place individually chosen by them; to perform the Work to the public - by any means or process and the communication to the public of the - performances of the Work, including by public digital performance; to - broadcast and rebroadcast the Work by any means including signs, - sounds or images. - i. "Reproduce" means to make copies of the Work by any means including - without limitation by sound or visual recordings and the right of - fixation and reproducing fixations of the Work, including storage of a - protected performance or phonogram in digital form or other electronic - medium. - -2. Fair Dealing Rights. Nothing in this License is intended to reduce, -limit, or restrict any uses free from copyright or rights arising from -limitations or exceptions that are provided for in connection with the -copyright protection under copyright law or other applicable laws. - -3. License Grant. Subject to the terms and conditions of this License, -Licensor hereby grants You a worldwide, royalty-free, non-exclusive, -perpetual (for the duration of the applicable copyright) license to -exercise the rights in the Work as stated below: - - a. to Reproduce the Work, to incorporate the Work into one or more - Collections, and to Reproduce the Work as incorporated in the - Collections; - b. to create and Reproduce Adaptations provided that any such Adaptation, - including any translation in any medium, takes reasonable steps to - clearly label, demarcate or otherwise identify that changes were made - to the original Work. For example, a translation could be marked "The - original work was translated from English to Spanish," or a - modification could indicate "The original work has been modified."; - c. to Distribute and Publicly Perform the Work including as incorporated - in Collections; and, - d. to Distribute and Publicly Perform Adaptations. - e. For the avoidance of doubt: - - i. Non-waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme cannot be waived, the Licensor - reserves the exclusive right to collect such royalties for any - exercise by You of the rights granted under this License; - ii. Waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme can be waived, the Licensor waives the - exclusive right to collect such royalties for any exercise by You - of the rights granted under this License; and, - iii. Voluntary License Schemes. The Licensor waives the right to - collect royalties, whether individually or, in the event that the - Licensor is a member of a collecting society that administers - voluntary licensing schemes, via that society, from any exercise - by You of the rights granted under this License. - -The above rights may be exercised in all media and formats whether now -known or hereafter devised. The above rights include the right to make -such modifications as are technically necessary to exercise the rights in -other media and formats. Subject to Section 8(f), all rights not expressly -granted by Licensor are hereby reserved. - -4. Restrictions. The license granted in Section 3 above is expressly made -subject to and limited by the following restrictions: - - a. You may Distribute or Publicly Perform the Work only under the terms - of this License. You must include a copy of, or the Uniform Resource - Identifier (URI) for, this License with every copy of the Work You - Distribute or Publicly Perform. You may not offer or impose any terms - on the Work that restrict the terms of this License or the ability of - the recipient of the Work to exercise the rights granted to that - recipient under the terms of the License. You may not sublicense the - Work. You must keep intact all notices that refer to this License and - to the disclaimer of warranties with every copy of the Work You - Distribute or Publicly Perform. When You Distribute or Publicly - Perform the Work, You may not impose any effective technological - measures on the Work that restrict the ability of a recipient of the - Work from You to exercise the rights granted to that recipient under - the terms of the License. This Section 4(a) applies to the Work as - incorporated in a Collection, but this does not require the Collection - apart from the Work itself to be made subject to the terms of this - License. If You create a Collection, upon notice from any Licensor You - must, to the extent practicable, remove from the Collection any credit - as required by Section 4(b), as requested. If You create an - Adaptation, upon notice from any Licensor You must, to the extent - practicable, remove from the Adaptation any credit as required by - Section 4(b), as requested. - b. If You Distribute, or Publicly Perform the Work or any Adaptations or - Collections, You must, unless a request has been made pursuant to - Section 4(a), keep intact all copyright notices for the Work and - provide, reasonable to the medium or means You are utilizing: (i) the - name of the Original Author (or pseudonym, if applicable) if supplied, - and/or if the Original Author and/or Licensor designate another party - or parties (e.g., a sponsor institute, publishing entity, journal) for - attribution ("Attribution Parties") in Licensor's copyright notice, - terms of service or by other reasonable means, the name of such party - or parties; (ii) the title of the Work if supplied; (iii) to the - extent reasonably practicable, the URI, if any, that Licensor - specifies to be associated with the Work, unless such URI does not - refer to the copyright notice or licensing information for the Work; - and (iv) , consistent with Section 3(b), in the case of an Adaptation, - a credit identifying the use of the Work in the Adaptation (e.g., - "French translation of the Work by Original Author," or "Screenplay - based on original Work by Original Author"). The credit required by - this Section 4 (b) may be implemented in any reasonable manner; - provided, however, that in the case of a Adaptation or Collection, at - a minimum such credit will appear, if a credit for all contributing - authors of the Adaptation or Collection appears, then as part of these - credits and in a manner at least as prominent as the credits for the - other contributing authors. For the avoidance of doubt, You may only - use the credit required by this Section for the purpose of attribution - in the manner set out above and, by exercising Your rights under this - License, You may not implicitly or explicitly assert or imply any - connection with, sponsorship or endorsement by the Original Author, - Licensor and/or Attribution Parties, as appropriate, of You or Your - use of the Work, without the separate, express prior written - permission of the Original Author, Licensor and/or Attribution - Parties. - c. Except as otherwise agreed in writing by the Licensor or as may be - otherwise permitted by applicable law, if You Reproduce, Distribute or - Publicly Perform the Work either by itself or as part of any - Adaptations or Collections, You must not distort, mutilate, modify or - take other derogatory action in relation to the Work which would be - prejudicial to the Original Author's honor or reputation. Licensor - agrees that in those jurisdictions (e.g. Japan), in which any exercise - of the right granted in Section 3(b) of this License (the right to - make Adaptations) would be deemed to be a distortion, mutilation, - modification or other derogatory action prejudicial to the Original - Author's honor and reputation, the Licensor will waive or not assert, - as appropriate, this Section, to the fullest extent permitted by the - applicable national law, to enable You to reasonably exercise Your - right under Section 3(b) of this License (right to make Adaptations) - but not otherwise. - -5. Representations, Warranties and Disclaimer - -UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR -OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY -KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, -INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, -FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF -LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, -WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION -OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE -LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR -ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES -ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - a. This License and the rights granted hereunder will terminate - automatically upon any breach by You of the terms of this License. - Individuals or entities who have received Adaptations or Collections - from You under this License, however, will not have their licenses - terminated provided such individuals or entities remain in full - compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will - survive any termination of this License. - b. Subject to the above terms and conditions, the license granted here is - perpetual (for the duration of the applicable copyright in the Work). - Notwithstanding the above, Licensor reserves the right to release the - Work under different license terms or to stop distributing the Work at - any time; provided, however that any such election will not serve to - withdraw this License (or any other license that has been, or is - required to be, granted under the terms of this License), and this - License will continue in full force and effect unless terminated as - stated above. - -8. Miscellaneous - - a. Each time You Distribute or Publicly Perform the Work or a Collection, - the Licensor offers to the recipient a license to the Work on the same - terms and conditions as the license granted to You under this License. - b. Each time You Distribute or Publicly Perform an Adaptation, Licensor - offers to the recipient a license to the original Work on the same - terms and conditions as the license granted to You under this License. - c. If any provision of this License is invalid or unenforceable under - applicable law, it shall not affect the validity or enforceability of - the remainder of the terms of this License, and without further action - by the parties to this agreement, such provision shall be reformed to - the minimum extent necessary to make such provision valid and - enforceable. - d. No term or provision of this License shall be deemed waived and no - breach consented to unless such waiver or consent shall be in writing - and signed by the party to be charged with such waiver or consent. - e. This License constitutes the entire agreement between the parties with - respect to the Work licensed here. There are no understandings, - agreements or representations with respect to the Work not specified - here. Licensor shall not be bound by any additional provisions that - may appear in any communication from You. This License may not be - modified without the mutual written agreement of the Licensor and You. - f. The rights granted under, and the subject matter referenced, in this - License were drafted utilizing the terminology of the Berne Convention - for the Protection of Literary and Artistic Works (as amended on - September 28, 1979), the Rome Convention of 1961, the WIPO Copyright - Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 - and the Universal Copyright Convention (as revised on July 24, 1971). - These rights and subject matter take effect in the relevant - jurisdiction in which the License terms are sought to be enforced - according to the corresponding provisions of the implementation of - those treaty provisions in the applicable national law. If the - standard suite of rights granted under applicable copyright law - includes additional rights not granted under this License, such - additional rights are deemed to be included in the License; this - License is not intended to restrict the license of any rights under - applicable law. - - -Creative Commons Notice - - Creative Commons is not a party to this License, and makes no warranty - whatsoever in connection with the Work. Creative Commons will not be - liable to You or any party on any legal theory for any damages - whatsoever, including without limitation any general, special, - incidental or consequential damages arising in connection to this - license. Notwithstanding the foregoing two (2) sentences, if Creative - Commons has expressly identified itself as the Licensor hereunder, it - shall have all rights and obligations of Licensor. - - Except for the limited purpose of indicating to the public that the - Work is licensed under the CCPL, Creative Commons does not authorize - the use by either party of the trademark "Creative Commons" or any - related trademark or logo of Creative Commons without the prior - written consent of Creative Commons. Any permitted use will be in - compliance with Creative Commons' then-current trademark usage - guidelines, as may be published on its website or otherwise made - available upon request from time to time. For the avoidance of doubt, - this trademark restriction does not form part of this License. - - Creative Commons may be contacted at http://creativecommons.org/. diff --git a/vendor/github.com/google/go-github/github/activity.go b/vendor/github.com/google/go-github/github/activity.go deleted file mode 100644 index d6c992c7f5..0000000000 --- a/vendor/github.com/google/go-github/github/activity.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import "context" - -// ActivityService handles communication with the activity related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/activity/ -type ActivityService service - -// FeedLink represents a link to a related resource. -type FeedLink struct { - HRef *string `json:"href,omitempty"` - Type *string `json:"type,omitempty"` -} - -// Feeds represents timeline resources in Atom format. -type Feeds struct { - TimelineURL *string `json:"timeline_url,omitempty"` - UserURL *string `json:"user_url,omitempty"` - CurrentUserPublicURL *string `json:"current_user_public_url,omitempty"` - CurrentUserURL *string `json:"current_user_url,omitempty"` - CurrentUserActorURL *string `json:"current_user_actor_url,omitempty"` - CurrentUserOrganizationURL *string `json:"current_user_organization_url,omitempty"` - CurrentUserOrganizationURLs []string `json:"current_user_organization_urls,omitempty"` - Links *struct { - Timeline *FeedLink `json:"timeline,omitempty"` - User *FeedLink `json:"user,omitempty"` - CurrentUserPublic *FeedLink `json:"current_user_public,omitempty"` - CurrentUser *FeedLink `json:"current_user,omitempty"` - CurrentUserActor *FeedLink `json:"current_user_actor,omitempty"` - CurrentUserOrganization *FeedLink `json:"current_user_organization,omitempty"` - CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"` - } `json:"_links,omitempty"` -} - -// ListFeeds lists all the feeds available to the authenticated user. -// -// GitHub provides several timeline resources in Atom format: -// Timeline: The GitHub global public timeline -// User: The public timeline for any user, using URI template -// Current user public: The public timeline for the authenticated user -// Current user: The private timeline for the authenticated user -// Current user actor: The private timeline for activity created by the -// authenticated user -// Current user organizations: The private timeline for the organizations -// the authenticated user is a member of. -// -// Note: Private feeds are only returned when authenticating via Basic Auth -// since current feed URIs use the older, non revocable auth tokens. -func (s *ActivityService) ListFeeds(ctx context.Context) (*Feeds, *Response, error) { - req, err := s.client.NewRequest("GET", "feeds", nil) - if err != nil { - return nil, nil, err - } - - f := &Feeds{} - resp, err := s.client.Do(ctx, req, f) - if err != nil { - return nil, resp, err - } - - return f, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_events.go b/vendor/github.com/google/go-github/github/activity_events.go deleted file mode 100644 index 6b35056f40..0000000000 --- a/vendor/github.com/google/go-github/github/activity_events.go +++ /dev/null @@ -1,322 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "encoding/json" - "fmt" - "time" -) - -// Event represents a GitHub event. -type Event struct { - Type *string `json:"type,omitempty"` - Public *bool `json:"public"` - RawPayload *json.RawMessage `json:"payload,omitempty"` - Repo *Repository `json:"repo,omitempty"` - Actor *User `json:"actor,omitempty"` - Org *Organization `json:"org,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ID *string `json:"id,omitempty"` -} - -func (e Event) String() string { - return Stringify(e) -} - -// ParsePayload parses the event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -func (e *Event) ParsePayload() (payload interface{}, err error) { - switch *e.Type { - case "CommitCommentEvent": - payload = &CommitCommentEvent{} - case "CreateEvent": - payload = &CreateEvent{} - case "DeleteEvent": - payload = &DeleteEvent{} - case "DeploymentEvent": - payload = &DeploymentEvent{} - case "DeploymentStatusEvent": - payload = &DeploymentStatusEvent{} - case "ForkEvent": - payload = &ForkEvent{} - case "GollumEvent": - payload = &GollumEvent{} - case "InstallationEvent": - payload = &InstallationEvent{} - case "InstallationRepositoriesEvent": - payload = &InstallationRepositoriesEvent{} - case "IssueCommentEvent": - payload = &IssueCommentEvent{} - case "IssuesEvent": - payload = &IssuesEvent{} - case "LabelEvent": - payload = &LabelEvent{} - case "MemberEvent": - payload = &MemberEvent{} - case "MembershipEvent": - payload = &MembershipEvent{} - case "MilestoneEvent": - payload = &MilestoneEvent{} - case "OrganizationEvent": - payload = &OrganizationEvent{} - case "OrgBlockEvent": - payload = &OrgBlockEvent{} - case "PageBuildEvent": - payload = &PageBuildEvent{} - case "PingEvent": - payload = &PingEvent{} - case "ProjectEvent": - payload = &ProjectEvent{} - case "ProjectCardEvent": - payload = &ProjectCardEvent{} - case "ProjectColumnEvent": - payload = &ProjectColumnEvent{} - case "PublicEvent": - payload = &PublicEvent{} - case "PullRequestEvent": - payload = &PullRequestEvent{} - case "PullRequestReviewEvent": - payload = &PullRequestReviewEvent{} - case "PullRequestReviewCommentEvent": - payload = &PullRequestReviewCommentEvent{} - case "PushEvent": - payload = &PushEvent{} - case "ReleaseEvent": - payload = &ReleaseEvent{} - case "RepositoryEvent": - payload = &RepositoryEvent{} - case "StatusEvent": - payload = &StatusEvent{} - case "TeamEvent": - payload = &TeamEvent{} - case "TeamAddEvent": - payload = &TeamAddEvent{} - case "WatchEvent": - payload = &WatchEvent{} - } - err = json.Unmarshal(*e.RawPayload, &payload) - return payload, err -} - -// Payload returns the parsed event payload. For recognized event types, -// a value of the corresponding struct type will be returned. -// -// Deprecated: Use ParsePayload instead, which returns an error -// rather than panics if JSON unmarshaling raw payload fails. -func (e *Event) Payload() (payload interface{}) { - var err error - payload, err = e.ParsePayload() - if err != nil { - panic(err) - } - return payload -} - -// ListEvents drinks from the firehose of all public events across GitHub. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events -func (s *ActivityService) ListEvents(ctx context.Context, opt *ListOptions) ([]*Event, *Response, error) { - u, err := addOptions("events", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-repository-events -func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListIssueEventsForRepository lists issue events for a repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository -func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForRepoNetwork lists public events for a network of repositories. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories -func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("networks/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsForOrganization lists public events for an organization. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-an-organization -func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("orgs/%v/events", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsPerformedByUser lists the events performed by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-performed-by-a-user -func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/events/public", user) - } else { - u = fmt.Sprintf("users/%v/events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListEventsReceivedByUser lists the events received by a user. If publicOnly is -// true, only public events will be returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received -func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { - var u string - if publicOnly { - u = fmt.Sprintf("users/%v/received_events/public", user) - } else { - u = fmt.Sprintf("users/%v/received_events", user) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListUserEventsForOrganization provides the user’s organization dashboard. You -// must be authenticated as the user to view this. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-for-an-organization -func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opt *ListOptions) ([]*Event, *Response, error) { - u := fmt.Sprintf("users/%v/events/orgs/%v", user, org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*Event - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/activity_notifications.go b/vendor/github.com/google/go-github/github/activity_notifications.go deleted file mode 100644 index 45c8b2aece..0000000000 --- a/vendor/github.com/google/go-github/github/activity_notifications.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// Notification identifies a GitHub notification for a user. -type Notification struct { - ID *string `json:"id,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Subject *NotificationSubject `json:"subject,omitempty"` - - // Reason identifies the event that triggered the notification. - // - // GitHub API docs: https://developer.github.com/v3/activity/notifications/#notification-reasons - Reason *string `json:"reason,omitempty"` - - Unread *bool `json:"unread,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - LastReadAt *time.Time `json:"last_read_at,omitempty"` - URL *string `json:"url,omitempty"` -} - -// NotificationSubject identifies the subject of a notification. -type NotificationSubject struct { - Title *string `json:"title,omitempty"` - URL *string `json:"url,omitempty"` - LatestCommentURL *string `json:"latest_comment_url,omitempty"` - Type *string `json:"type,omitempty"` -} - -// NotificationListOptions specifies the optional parameters to the -// ActivityService.ListNotifications method. -type NotificationListOptions struct { - All bool `url:"all,omitempty"` - Participating bool `url:"participating,omitempty"` - Since time.Time `url:"since,omitempty"` - Before time.Time `url:"before,omitempty"` - - ListOptions -} - -// ListNotifications lists all notifications for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications -func (s *ActivityService) ListNotifications(ctx context.Context, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("notifications") - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -// ListRepositoryNotifications lists all notifications in a given repository -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository -func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var notifications []*Notification - resp, err := s.client.Do(ctx, req, ¬ifications) - if err != nil { - return nil, resp, err - } - - return notifications, resp, nil -} - -type markReadOptions struct { - LastReadAt time.Time `json:"last_read_at,omitempty"` -} - -// MarkNotificationsRead marks all notifications up to lastRead as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-as-read -func (s *ActivityService) MarkNotificationsRead(ctx context.Context, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - req, err := s.client.NewRequest("PUT", "notifications", opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// MarkRepositoryNotificationsRead marks all notifications up to lastRead in -// the specified repository as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository -func (s *ActivityService) MarkRepositoryNotificationsRead(ctx context.Context, owner, repo string, lastRead time.Time) (*Response, error) { - opts := &markReadOptions{ - LastReadAt: lastRead, - } - u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - req, err := s.client.NewRequest("PUT", u, opts) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThread gets the specified notification thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#view-a-single-thread -func (s *ActivityService) GetThread(ctx context.Context, id string) (*Notification, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - notification := new(Notification) - resp, err := s.client.Do(ctx, req, notification) - if err != nil { - return nil, resp, err - } - - return notification, resp, nil -} - -// MarkThreadRead marks the specified thread as read. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read -func (s *ActivityService) MarkThreadRead(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v", id) - - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// GetThreadSubscription checks to see if the authenticated user is subscribed -// to a thread. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription -func (s *ActivityService) GetThreadSubscription(ctx context.Context, id string) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// SetThreadSubscription sets the subscription for the specified thread for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription -func (s *ActivityService) SetThreadSubscription(ctx context.Context, id string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteThreadSubscription deletes the subscription for the specified thread -// for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription -func (s *ActivityService) DeleteThreadSubscription(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("notifications/threads/%v/subscription", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_star.go b/vendor/github.com/google/go-github/github/activity_star.go deleted file mode 100644 index d5b067127c..0000000000 --- a/vendor/github.com/google/go-github/github/activity_star.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// StarredRepository is returned by ListStarred. -type StarredRepository struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - Repository *Repository `json:"repo,omitempty"` -} - -// Stargazer represents a user that has starred a repository. -type Stargazer struct { - StarredAt *Timestamp `json:"starred_at,omitempty"` - User *User `json:"user,omitempty"` -} - -// ListStargazers lists people who have starred the specified repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-stargazers -func (s *ActivityService) ListStargazers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/stargazers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var stargazers []*Stargazer - resp, err := s.client.Do(ctx, req, &stargazers) - if err != nil { - return nil, resp, err - } - - return stargazers, resp, nil -} - -// ActivityListStarredOptions specifies the optional parameters to the -// ActivityService.ListStarred method. -type ActivityListStarredOptions struct { - // How to sort the repository list. Possible values are: created, updated, - // pushed, full_name. Default is "full_name". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Possible values are: asc, desc. - // Default is "asc" when sort is "full_name", otherwise default is "desc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListStarred lists all the repos starred by a user. Passing the empty string -// will list the starred repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#list-repositories-being-starred -func (s *ActivityService) ListStarred(ctx context.Context, user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/starred", user) - } else { - u = "user/starred" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeStarringPreview) - - var repos []*StarredRepository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsStarred checks if a repository is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository -func (s *ActivityService) IsStarred(ctx context.Context, owner, repo string) (bool, *Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Star a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#star-a-repository -func (s *ActivityService) Star(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a repository as the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/starring/#unstar-a-repository -func (s *ActivityService) Unstar(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("user/starred/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/activity_watching.go b/vendor/github.com/google/go-github/github/activity_watching.go deleted file mode 100644 index c749ca86e7..0000000000 --- a/vendor/github.com/google/go-github/github/activity_watching.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Subscription identifies a repository or thread subscription. -type Subscription struct { - Subscribed *bool `json:"subscribed,omitempty"` - Ignored *bool `json:"ignored,omitempty"` - Reason *string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - - // only populated for repository subscriptions - RepositoryURL *string `json:"repository_url,omitempty"` - - // only populated for thread subscriptions - ThreadURL *string `json:"thread_url,omitempty"` -} - -// ListWatchers lists watchers of a particular repo. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-watchers -func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscribers", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watchers []*User - resp, err := s.client.Do(ctx, req, &watchers) - if err != nil { - return nil, resp, err - } - - return watchers, resp, nil -} - -// ListWatched lists the repositories the specified user is watching. Passing -// the empty string will fetch watched repos for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched -func (s *ActivityService) ListWatched(ctx context.Context, user string, opt *ListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/subscriptions", user) - } else { - u = "user/subscriptions" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var watched []*Repository - resp, err := s.client.Do(ctx, req, &watched) - if err != nil { - return nil, resp, err - } - - return watched, resp, nil -} - -// GetRepositorySubscription returns the subscription for the specified -// repository for the authenticated user. If the authenticated user is not -// watching the repository, a nil Subscription is returned. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#get-a-repository-subscription -func (s *ActivityService) GetRepositorySubscription(ctx context.Context, owner, repo string) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - // if it's just a 404, don't return that as an error - _, err = parseBoolResponse(err) - return nil, resp, err - } - - return sub, resp, nil -} - -// SetRepositorySubscription sets the subscription for the specified repository -// for the authenticated user. -// -// To watch a repository, set subscription.Subscribed to true. -// To ignore notifications made within a repository, set subscription.Ignored to true. -// To stop watching a repository, use DeleteRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#set-a-repository-subscription -func (s *ActivityService) SetRepositorySubscription(ctx context.Context, owner, repo string, subscription *Subscription) (*Subscription, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - - req, err := s.client.NewRequest("PUT", u, subscription) - if err != nil { - return nil, nil, err - } - - sub := new(Subscription) - resp, err := s.client.Do(ctx, req, sub) - if err != nil { - return nil, resp, err - } - - return sub, resp, nil -} - -// DeleteRepositorySubscription deletes the subscription for the specified -// repository for the authenticated user. -// -// This is used to stop watching a repository. To control whether or not to -// receive notifications from a repository, use SetRepositorySubscription. -// -// GitHub API docs: https://developer.github.com/v3/activity/watching/#delete-a-repository-subscription -func (s *ActivityService) DeleteRepositorySubscription(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/subscription", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/admin.go b/vendor/github.com/google/go-github/github/admin.go deleted file mode 100644 index d0f055bcfa..0000000000 --- a/vendor/github.com/google/go-github/github/admin.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// AdminService handles communication with the admin related methods of the -// GitHub API. These API routes are normally only accessible for GitHub -// Enterprise installations. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ -type AdminService service - -// TeamLDAPMapping represents the mapping between a GitHub team and an LDAP group. -type TeamLDAPMapping struct { - ID *int `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Slug *string `json:"slug,omitempty"` - Description *string `json:"description,omitempty"` - Privacy *string `json:"privacy,omitempty"` - Permission *string `json:"permission,omitempty"` - - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` -} - -func (m TeamLDAPMapping) String() string { - return Stringify(m) -} - -// UserLDAPMapping represents the mapping between a GitHub user and an LDAP user. -type UserLDAPMapping struct { - ID *int `json:"id,omitempty"` - LDAPDN *string `json:"ldap_dn,omitempty"` - Login *string `json:"login,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` -} - -func (m UserLDAPMapping) String() string { - return Stringify(m) -} - -// UpdateUserLDAPMapping updates the mapping between a GitHub user and an LDAP user. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-user -func (s *AdminService) UpdateUserLDAPMapping(ctx context.Context, user string, mapping *UserLDAPMapping) (*UserLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/users/%v/mapping", user) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(UserLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// UpdateTeamLDAPMapping updates the mapping between a GitHub team and an LDAP group. -// -// GitHub API docs: https://developer.github.com/v3/enterprise/ldap/#update-ldap-mapping-for-a-team -func (s *AdminService) UpdateTeamLDAPMapping(ctx context.Context, team int, mapping *TeamLDAPMapping) (*TeamLDAPMapping, *Response, error) { - u := fmt.Sprintf("admin/ldap/teams/%v/mapping", team) - req, err := s.client.NewRequest("PATCH", u, mapping) - if err != nil { - return nil, nil, err - } - - m := new(TeamLDAPMapping) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps.go b/vendor/github.com/google/go-github/github/apps.go deleted file mode 100644 index ff3389382e..0000000000 --- a/vendor/github.com/google/go-github/github/apps.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import "context" - -// AppsService provides access to the installation related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/apps/ -type AppsService service - -// ListInstallations lists the installations that the current GitHub App has. -// -// GitHub API docs: https://developer.github.com/v3/apps/#find-installations -func (s *AppsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("app/installations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var i []*Installation - resp, err := s.client.Do(ctx, req, &i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/apps_installation.go b/vendor/github.com/google/go-github/github/apps_installation.go deleted file mode 100644 index 6a27799531..0000000000 --- a/vendor/github.com/google/go-github/github/apps_installation.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import "context" - -// Installation represents a GitHub Apps installation. -type Installation struct { - ID *int `json:"id,omitempty"` - Account *User `json:"account,omitempty"` - AccessTokensURL *string `json:"access_tokens_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -func (i Installation) String() string { - return Stringify(i) -} - -// ListRepos lists the repositories that are accessible to the authenticated installation. -// -// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories -func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { - u, err := addOptions("installation/repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeIntegrationPreview) - - var r struct { - Repositories []*Repository `json:"repositories"` - } - resp, err := s.client.Do(ctx, req, &r) - if err != nil { - return nil, resp, err - } - - return r.Repositories, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/authorizations.go b/vendor/github.com/google/go-github/github/authorizations.go deleted file mode 100644 index d87adc0bdc..0000000000 --- a/vendor/github.com/google/go-github/github/authorizations.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2015 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Scope models a GitHub authorization scope. -// -// GitHub API docs: https://developer.github.com/v3/oauth/#scopes -type Scope string - -// This is the set of scopes for GitHub API V3 -const ( - ScopeNone Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact? - ScopeUser Scope = "user" - ScopeUserEmail Scope = "user:email" - ScopeUserFollow Scope = "user:follow" - ScopePublicRepo Scope = "public_repo" - ScopeRepo Scope = "repo" - ScopeRepoDeployment Scope = "repo_deployment" - ScopeRepoStatus Scope = "repo:status" - ScopeDeleteRepo Scope = "delete_repo" - ScopeNotifications Scope = "notifications" - ScopeGist Scope = "gist" - ScopeReadRepoHook Scope = "read:repo_hook" - ScopeWriteRepoHook Scope = "write:repo_hook" - ScopeAdminRepoHook Scope = "admin:repo_hook" - ScopeAdminOrgHook Scope = "admin:org_hook" - ScopeReadOrg Scope = "read:org" - ScopeWriteOrg Scope = "write:org" - ScopeAdminOrg Scope = "admin:org" - ScopeReadPublicKey Scope = "read:public_key" - ScopeWritePublicKey Scope = "write:public_key" - ScopeAdminPublicKey Scope = "admin:public_key" - ScopeReadGPGKey Scope = "read:gpg_key" - ScopeWriteGPGKey Scope = "write:gpg_key" - ScopeAdminGPGKey Scope = "admin:gpg_key" -) - -// AuthorizationsService handles communication with the authorization related -// methods of the GitHub API. -// -// This service requires HTTP Basic Authentication; it cannot be accessed using -// an OAuth token. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/ -type AuthorizationsService service - -// Authorization represents an individual GitHub authorization. -type Authorization struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Scopes []Scope `json:"scopes,omitempty"` - Token *string `json:"token,omitempty"` - TokenLastEight *string `json:"token_last_eight,omitempty"` - HashedToken *string `json:"hashed_token,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - UpdateAt *Timestamp `json:"updated_at,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` - - // User is only populated by the Check and Reset methods. - User *User `json:"user,omitempty"` -} - -func (a Authorization) String() string { - return Stringify(a) -} - -// AuthorizationApp represents an individual GitHub app (in the context of authorization). -type AuthorizationApp struct { - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - ClientID *string `json:"client_id,omitempty"` -} - -func (a AuthorizationApp) String() string { - return Stringify(a) -} - -// Grant represents an OAuth application that has been granted access to an account. -type Grant struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - App *AuthorizationApp `json:"app,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Scopes []string `json:"scopes,omitempty"` -} - -func (g Grant) String() string { - return Stringify(g) -} - -// AuthorizationRequest represents a request to create an authorization. -type AuthorizationRequest struct { - Scopes []Scope `json:"scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - ClientID *string `json:"client_id,omitempty"` - ClientSecret *string `json:"client_secret,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationRequest) String() string { - return Stringify(a) -} - -// AuthorizationUpdateRequest represents a request to update an authorization. -// -// Note that for any one update, you must only provide one of the "scopes" -// fields. That is, you may provide only one of "Scopes", or "AddScopes", or -// "RemoveScopes". -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -type AuthorizationUpdateRequest struct { - Scopes []string `json:"scopes,omitempty"` - AddScopes []string `json:"add_scopes,omitempty"` - RemoveScopes []string `json:"remove_scopes,omitempty"` - Note *string `json:"note,omitempty"` - NoteURL *string `json:"note_url,omitempty"` - Fingerprint *string `json:"fingerprint,omitempty"` -} - -func (a AuthorizationUpdateRequest) String() string { - return Stringify(a) -} - -// List the authorizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations -func (s *AuthorizationsService) List(ctx context.Context, opt *ListOptions) ([]*Authorization, *Response, error) { - u := "authorizations" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var auths []*Authorization - resp, err := s.client.Do(ctx, req, &auths) - if err != nil { - return nil, resp, err - } - return auths, resp, nil -} - -// Get a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization -func (s *AuthorizationsService) Get(ctx context.Context, id int) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// Create a new authorization for the specified OAuth application. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization -func (s *AuthorizationsService) Create(ctx context.Context, auth *AuthorizationRequest) (*Authorization, *Response, error) { - u := "authorizations" - - req, err := s.client.NewRequest("POST", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// GetOrCreateForApp creates a new authorization for the specified OAuth -// application, only if an authorization for that application doesn’t already -// exist for the user. -// -// If a new token is created, the HTTP status code will be "201 Created", and -// the returned Authorization.Token field will be populated. If an existing -// token is returned, the status code will be "200 OK" and the -// Authorization.Token field will be empty. -// -// clientID is the OAuth Client ID with which to create the token. -// -// GitHub API docs: -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app -// https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app-and-fingerprint -func (s *AuthorizationsService) GetOrCreateForApp(ctx context.Context, clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error) { - var u string - if auth.Fingerprint == nil || *auth.Fingerprint == "" { - u = fmt.Sprintf("authorizations/clients/%v", clientID) - } else { - u = fmt.Sprintf("authorizations/clients/%v/%v", clientID, *auth.Fingerprint) - } - - req, err := s.client.NewRequest("PUT", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Edit a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization -func (s *AuthorizationsService) Edit(ctx context.Context, id int, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("PATCH", u, auth) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Delete a single authorization. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization -func (s *AuthorizationsService) Delete(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("authorizations/%d", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Check if an OAuth token is valid for a specific app. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#check-an-authorization -func (s *AuthorizationsService) Check(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Reset is used to reset a valid OAuth token without end user involvement. -// Applications must save the "token" property in the response, because changes -// take effect immediately. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// The returned Authorization.User field will be populated. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization -func (s *AuthorizationsService) Reset(ctx context.Context, clientID string, token string) (*Authorization, *Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - - return a, resp, nil -} - -// Revoke an authorization for an application. -// -// Note that this operation requires the use of BasicAuth, but where the -// username is the OAuth application clientID, and the password is its -// clientSecret. Invalid tokens will return a 404 Not Found. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application -func (s *AuthorizationsService) Revoke(ctx context.Context, clientID string, token string) (*Response, error) { - u := fmt.Sprintf("applications/%v/tokens/%v", clientID, token) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListGrants lists the set of OAuth applications that have been granted -// access to a user's account. This will return one entry for each application -// that has been granted access to the account, regardless of the number of -// tokens an application has generated for the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants -func (s *AuthorizationsService) ListGrants(ctx context.Context, opt *ListOptions) ([]*Grant, *Response, error) { - u, err := addOptions("applications/grants", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grants := []*Grant{} - resp, err := s.client.Do(ctx, req, &grants) - if err != nil { - return nil, resp, err - } - - return grants, resp, nil -} - -// GetGrant gets a single OAuth application grant. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-grant -func (s *AuthorizationsService) GetGrant(ctx context.Context, id int) (*Grant, *Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - grant := new(Grant) - resp, err := s.client.Do(ctx, req, grant) - if err != nil { - return nil, resp, err - } - - return grant, resp, nil -} - -// DeleteGrant deletes an OAuth application grant. Deleting an application's -// grant will also delete all OAuth tokens associated with the application for -// the user. -// -// GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-a-grant -func (s *AuthorizationsService) DeleteGrant(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("applications/grants/%d", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// CreateImpersonation creates an impersonation OAuth token. -// -// This requires admin permissions. With the returned Authorization.Token -// you can e.g. create or delete a user's public SSH key. NOTE: creating a -// new token automatically revokes an existing one. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#create-an-impersonation-oauth-token -func (s *AuthorizationsService) CreateImpersonation(ctx context.Context, username string, authReq *AuthorizationRequest) (*Authorization, *Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("POST", u, authReq) - if err != nil { - return nil, nil, err - } - - a := new(Authorization) - resp, err := s.client.Do(ctx, req, a) - if err != nil { - return nil, resp, err - } - return a, resp, nil -} - -// DeleteImpersonation deletes an impersonation OAuth token. -// -// NOTE: there can be only one at a time. -// -// GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#delete-an-impersonation-oauth-token -func (s *AuthorizationsService) DeleteImpersonation(ctx context.Context, username string) (*Response, error) { - u := fmt.Sprintf("admin/users/%v/authorizations", username) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/doc.go b/vendor/github.com/google/go-github/github/doc.go deleted file mode 100644 index abbcf6406f..0000000000 --- a/vendor/github.com/google/go-github/github/doc.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2013 The go-github 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 github provides a client for using the GitHub API. - -Usage: - - import "github.com/google/go-github/github" - -Construct a new GitHub client, then use the various services on the client to -access different parts of the GitHub API. For example: - - client := github.NewClient(nil) - - // list all organizations for user "willnorris" - orgs, _, err := client.Organizations.List(ctx, "willnorris", nil) - -Some API methods have optional parameters that can be passed. For example: - - client := github.NewClient(nil) - - // list public repositories for org "github" - opt := &github.RepositoryListByOrgOptions{Type: "public"} - repos, _, err := client.Repositories.ListByOrg(ctx, "github", opt) - -The services of a client divide the API into logical chunks and correspond to -the structure of the GitHub API documentation at -https://developer.github.com/v3/. - -Authentication - -The go-github library does not directly handle authentication. Instead, when -creating a new client, pass an http.Client that can handle authentication for -you. The easiest and recommended way to do this is using the golang.org/x/oauth2 -library, but you can always use any other library that provides an http.Client. -If you have an OAuth2 access token (for example, a personal API token), you can -use it with the oauth2 library using: - - import "golang.org/x/oauth2" - - func main() { - ctx := context.Background() - ts := oauth2.StaticTokenSource( - &oauth2.Token{AccessToken: "... your access token ..."}, - ) - tc := oauth2.NewClient(ctx, ts) - - client := github.NewClient(tc) - - // list all repositories for the authenticated user - repos, _, err := client.Repositories.List(ctx, "", nil) - } - -Note that when using an authenticated Client, all calls made by the client will -include the specified OAuth token. Therefore, authenticated clients should -almost never be shared between different users. - -See the oauth2 docs for complete instructions on using that library. - -For API methods that require HTTP Basic Authentication, use the -BasicAuthTransport. - -GitHub Apps authentication can be provided by the -https://github.com/bradleyfalzon/ghinstallation package. - - import "github.com/bradleyfalzon/ghinstallation" - - func main() { - // Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99. - itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem") - if err != nil { - // Handle error. - } - - // Use installation transport with client - client := github.NewClient(&http.Client{Transport: itr}) - - // Use client... - } - -Rate Limiting - -GitHub imposes a rate limit on all API clients. Unauthenticated clients are -limited to 60 requests per hour, while authenticated clients can make up to -5,000 requests per hour. To receive the higher rate limit when making calls -that are not issued on behalf of a user, use the -UnauthenticatedRateLimitedTransport. - -The returned Response.Rate value contains the rate limit information -from the most recent API call. If a recent enough response isn't -available, you can use RateLimits to fetch the most up-to-date rate -limit data for the client. - -To detect an API rate limit error, you can check if its type is *github.RateLimitError: - - repos, _, err := client.Repositories.List(ctx, "", nil) - if _, ok := err.(*github.RateLimitError); ok { - log.Println("hit rate limit") - } - -Learn more about GitHub rate limiting at -https://developer.github.com/v3/#rate-limiting. - -Accepted Status - -Some endpoints may return a 202 Accepted status code, meaning that the -information required is not yet ready and was scheduled to be gathered on -the GitHub side. Methods known to behave like this are documented specifying -this behavior. - -To detect this condition of error, you can check if its type is -*github.AcceptedError: - - stats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo) - if _, ok := err.(*github.AcceptedError); ok { - log.Println("scheduled on GitHub side") - } - -Conditional Requests - -The GitHub API has good support for conditional requests which will help -prevent you from burning through your rate limit, as well as help speed up your -application. go-github does not handle conditional requests directly, but is -instead designed to work with a caching http.Transport. We recommend using -https://github.com/gregjones/httpcache for that. - -Learn more about GitHub conditional requests at -https://developer.github.com/v3/#conditional-requests. - -Creating and Updating Resources - -All structs for GitHub resources use pointer values for all non-repeated fields. -This allows distinguishing between unset fields and those set to a zero-value. -Helper functions have been provided to easily create these pointers for string, -bool, and int values. For example: - - // create a new private repository named "foo" - repo := &github.Repository{ - Name: github.String("foo"), - Private: github.Bool(true), - } - client.Repositories.Create(ctx, "", repo) - -Users who have worked with protocol buffers should find this pattern familiar. - -Pagination - -All requests for resource collections (repos, pull requests, issues, etc.) -support pagination. Pagination options are described in the -github.ListOptions struct and passed to the list methods directly or as an -embedded type of a more specific list options struct (for example -github.PullRequestListOptions). Pages information is available via the -github.Response struct. - - client := github.NewClient(nil) - - opt := &github.RepositoryListByOrgOptions{ - ListOptions: github.ListOptions{PerPage: 10}, - } - // get all pages of results - var allRepos []*github.Repository - for { - repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt) - if err != nil { - return err - } - allRepos = append(allRepos, repos...) - if resp.NextPage == 0 { - break - } - opt.Page = resp.NextPage - } - -Google App Engine - -Go on App Engine Classic (which as of this writing uses Go 1.6) can not use -the "context" import and still relies on "golang.org/x/net/context". -As a result, if you wish to continue to use "go-github" on App Engine Classic, -you will need to rewrite all the "context" imports using the following command: - - gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go - -See "with_appengine.go" for more details. - -*/ -package github diff --git a/vendor/github.com/google/go-github/github/event_types.go b/vendor/github.com/google/go-github/github/event_types.go deleted file mode 100644 index c6b29b9a24..0000000000 --- a/vendor/github.com/google/go-github/github/event_types.go +++ /dev/null @@ -1,728 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// These event types are shared between the Events API and used as Webhook payloads. - -package github - -// CommitCommentEvent is triggered when a commit comment is created. -// The Webhook event name is "commit_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent -type CommitCommentEvent struct { - Comment *RepositoryComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// CreateEvent represents a created repository, branch, or tag. -// The Webhook event name is "create". -// -// Note: webhooks will not receive this event for created repositories. -// Additionally, webhooks will not receive this event for tags if more -// than three tags are pushed at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#createevent -type CreateEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was created. Possible values are: "repository", "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Description *string `json:"description,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeleteEvent represents a deleted branch or tag. -// The Webhook event name is "delete". -// -// Note: webhooks will not receive this event for tags if more than three tags -// are deleted at once. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deleteevent -type DeleteEvent struct { - Ref *string `json:"ref,omitempty"` - // RefType is the object that was deleted. Possible values are: "branch", "tag". - RefType *string `json:"ref_type,omitempty"` - - // The following fields are only populated by Webhook events. - PusherType *string `json:"pusher_type,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentEvent represents a deployment. -// The Webhook event name is "deployment". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentevent -type DeploymentEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// DeploymentStatusEvent represents a deployment status. -// The Webhook event name is "deployment_status". -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent -type DeploymentStatusEvent struct { - Deployment *Deployment `json:"deployment,omitempty"` - DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ForkEvent is triggered when a user forks a repository. -// The Webhook event name is "fork". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#forkevent -type ForkEvent struct { - // Forkee is the created repository. - Forkee *Repository `json:"forkee,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// Page represents a single Wiki page. -type Page struct { - PageName *string `json:"page_name,omitempty"` - Title *string `json:"title,omitempty"` - Summary *string `json:"summary,omitempty"` - Action *string `json:"action,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// GollumEvent is triggered when a Wiki page is created or updated. -// The Webhook event name is "gollum". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#gollumevent -type GollumEvent struct { - Pages []*Page `json:"pages,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// EditChange represents the changes when an issue, pull request, or comment has -// been edited. -type EditChange struct { - Title *struct { - From *string `json:"from,omitempty"` - } `json:"title,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectChange represents the changes when a project has been edited. -type ProjectChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Body *struct { - From *string `json:"from,omitempty"` - } `json:"body,omitempty"` -} - -// ProjectCardChange represents the changes when a project card has been edited. -type ProjectCardChange struct { - Note *struct { - From *string `json:"from,omitempty"` - } `json:"note,omitempty"` -} - -// ProjectColumnChange represents the changes when a project column has been edited. -type ProjectColumnChange struct { - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` -} - -// TeamChange represents the changes when a team has been edited. -type TeamChange struct { - Description *struct { - From *string `json:"from,omitempty"` - } `json:"description,omitempty"` - Name *struct { - From *string `json:"from,omitempty"` - } `json:"name,omitempty"` - Privacy *struct { - From *string `json:"from,omitempty"` - } `json:"privacy,omitempty"` - Repository *struct { - Permissions *struct { - From *struct { - Admin *bool `json:"admin,omitempty"` - Pull *bool `json:"pull,omitempty"` - Push *bool `json:"push,omitempty"` - } `json:"from,omitempty"` - } `json:"permissions,omitempty"` - } `json:"repository,omitempty"` -} - -// InstallationEvent is triggered when a GitHub App has been installed or uninstalled. -// The Webhook event name is "installation". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationevent -type InstallationEvent struct { - // The action that was performed. Can be either "created" or "deleted". - Action *string `json:"action,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// InstallationRepositoriesEvent is triggered when a repository is added or -// removed from an installation. The Webhook event name is "installation_repositories". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationrepositoriesevent -type InstallationRepositoriesEvent struct { - // The action that was performed. Can be either "added" or "removed". - Action *string `json:"action,omitempty"` - RepositoriesAdded []*Repository `json:"repositories_added,omitempty"` - RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"` - RepositorySelection *string `json:"repository_selection,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssueCommentEvent is triggered when an issue comment is created on an issue -// or pull request. -// The Webhook event name is "issue_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent -type IssueCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Comment *IssueComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// IssuesEvent is triggered when an issue is assigned, unassigned, labeled, -// unlabeled, opened, closed, or reopened. -// The Webhook event name is "issues". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#issuesevent -type IssuesEvent struct { - // Action is the action that was performed. Possible values are: "assigned", - // "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited". - Action *string `json:"action,omitempty"` - Issue *Issue `json:"issue,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// LabelEvent is triggered when a repository's label is created, edited, or deleted. -// The Webhook event name is "label" -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#labelevent -type LabelEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "edited", "deleted" - Action *string `json:"action,omitempty"` - Label *Label `json:"label,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MemberEvent is triggered when a user is added as a collaborator to a repository. -// The Webhook event name is "member". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#memberevent -type MemberEvent struct { - // Action is the action that was performed. Possible value is: "added". - Action *string `json:"action,omitempty"` - Member *User `json:"member,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MembershipEvent is triggered when a user is added or removed from a team. -// The Webhook event name is "membership". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#membershipevent -type MembershipEvent struct { - // Action is the action that was performed. Possible values are: "added", "removed". - Action *string `json:"action,omitempty"` - // Scope is the scope of the membership. Possible value is: "team". - Scope *string `json:"scope,omitempty"` - Member *User `json:"member,omitempty"` - Team *Team `json:"team,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// MilestoneEvent is triggered when a milestone is created, closed, opened, edited, or deleted. -// The Webhook event name is "milestone". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#milestoneevent -type MilestoneEvent struct { - // Action is the action that was performed. Possible values are: - // "created", "closed", "opened", "edited", "deleted" - Action *string `json:"action,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Org *Organization `json:"organization,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrganizationEvent is triggered when a user is added, removed, or invited to an organization. -// Events of this type are not visible in timelines. These events are only used to trigger organization hooks. -// Webhook event name is "organization". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#organizationevent -type OrganizationEvent struct { - // Action is the action that was performed. - // Can be one of "member_added", "member_removed", or "member_invited". - Action *string `json:"action,omitempty"` - - // Invitaion is the invitation for the user or email if the action is "member_invited". - Invitation *Invitation `json:"invitation,omitempty"` - - // Membership is the membership between the user and the organization. - // Not present when the action is "member_invited". - Membership *Membership `json:"membership,omitempty"` - - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// OrgBlockEvent is triggered when an organization blocks or unblocks a user. -// The Webhook event name is "org_block". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#orgblockevent -type OrgBlockEvent struct { - // Action is the action that was performed. - // Can be "blocked" or "unblocked". - Action *string `json:"action,omitempty"` - BlockedUser *User `json:"blocked_user,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - - // The following fields are only populated by Webhook events. - Installation *Installation `json:"installation,omitempty"` -} - -// PageBuildEvent represents an attempted build of a GitHub Pages site, whether -// successful or not. -// The Webhook event name is "page_build". -// -// This event is triggered on push to a GitHub Pages enabled branch (gh-pages -// for project pages, master for user and organization pages). -// -// Events of this type are not visible in timelines, they are only used to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent -type PageBuildEvent struct { - Build *PagesBuild `json:"build,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PingEvent is triggered when a Webhook is added to GitHub. -// -// GitHub API docs: https://developer.github.com/webhooks/#ping-event -type PingEvent struct { - // Random string of GitHub zen. - Zen *string `json:"zen,omitempty"` - // The ID of the webhook that triggered the ping. - HookID *int `json:"hook_id,omitempty"` - // The webhook configuration. - Hook *Hook `json:"hook,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectEvent is triggered when project is created, modified or deleted. -// The webhook event name is "project". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectevent -type ProjectEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectChange `json:"changes,omitempty"` - Project *Project `json:"project,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectCardEvent is triggered when a project card is created, updated, moved, converted to an issue, or deleted. -// The webhook event name is "project_card". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcardevent -type ProjectCardEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectCardChange `json:"changes,omitempty"` - AfterID *int `json:"after_id,omitempty"` - ProjectCard *ProjectCard `json:"project_card,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// ProjectColumnEvent is triggered when a project column is created, updated, moved, or deleted. -// The webhook event name is "project_column". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#projectcolumnevent -type ProjectColumnEvent struct { - Action *string `json:"action,omitempty"` - Changes *ProjectColumnChange `json:"changes,omitempty"` - AfterID *int `json:"after_id,omitempty"` - ProjectColumn *ProjectColumn `json:"project_column,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PublicEvent is triggered when a private repository is open sourced. -// According to GitHub: "Without a doubt: the best GitHub event." -// The Webhook event name is "public". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#publicevent -type PublicEvent struct { - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PullRequestEvent is triggered when a pull request is assigned, unassigned, -// labeled, unlabeled, opened, closed, reopened, or synchronized. -// The Webhook event name is "pull_request". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent -type PullRequestEvent struct { - // Action is the action that was performed. Possible values are: "assigned", - // "unassigned", "labeled", "unlabeled", "opened", "closed", or "reopened", - // "synchronize", "edited". If the action is "closed" and the merged key is false, - // the pull request was closed with unmerged commits. If the action is "closed" - // and the merged key is true, the pull request was merged. - Action *string `json:"action,omitempty"` - Number *int `json:"number,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PullRequestReviewEvent is triggered when a review is submitted on a pull -// request. -// The Webhook event name is "pull_request_review". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewevent -type PullRequestReviewEvent struct { - // Action is always "submitted". - Action *string `json:"action,omitempty"` - Review *PullRequestReview `json:"review,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` - - // The following field is only present when the webhook is triggered on - // a repository belonging to an organization. - Organization *Organization `json:"organization,omitempty"` -} - -// PullRequestReviewCommentEvent is triggered when a comment is created on a -// portion of the unified diff of a pull request. -// The Webhook event name is "pull_request_review_comment". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent -type PullRequestReviewCommentEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` - PullRequest *PullRequest `json:"pull_request,omitempty"` - Comment *PullRequestComment `json:"comment,omitempty"` - - // The following fields are only populated by Webhook events. - Changes *EditChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// PushEvent represents a git push to a GitHub repository. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#pushevent -type PushEvent struct { - PushID *int `json:"push_id,omitempty"` - Head *string `json:"head,omitempty"` - Ref *string `json:"ref,omitempty"` - Size *int `json:"size,omitempty"` - Commits []PushEventCommit `json:"commits,omitempty"` - Before *string `json:"before,omitempty"` - DistinctSize *int `json:"distinct_size,omitempty"` - - // The following fields are only populated by Webhook events. - After *string `json:"after,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - BaseRef *string `json:"base_ref,omitempty"` - Compare *string `json:"compare,omitempty"` - Repo *PushEventRepository `json:"repository,omitempty"` - HeadCommit *PushEventCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -func (p PushEvent) String() string { - return Stringify(p) -} - -// PushEventCommit represents a git commit in a GitHub PushEvent. -type PushEventCommit struct { - Message *string `json:"message,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - URL *string `json:"url,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - - // The following fields are only populated by Events API. - SHA *string `json:"sha,omitempty"` - - // The following fields are only populated by Webhook events. - ID *string `json:"id,omitempty"` - TreeID *string `json:"tree_id,omitempty"` - Timestamp *Timestamp `json:"timestamp,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Added []string `json:"added,omitempty"` - Removed []string `json:"removed,omitempty"` - Modified []string `json:"modified,omitempty"` -} - -func (p PushEventCommit) String() string { - return Stringify(p) -} - -// PushEventRepository represents the repo object in a PushEvent payload. -type PushEventRepository struct { - ID *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Owner *PushEventRepoOwner `json:"owner,omitempty"` - Private *bool `json:"private,omitempty"` - Description *string `json:"description,omitempty"` - Fork *bool `json:"fork,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Homepage *string `json:"homepage,omitempty"` - Size *int `json:"size,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Language *string `json:"language,omitempty"` - HasIssues *bool `json:"has_issues,omitempty"` - HasDownloads *bool `json:"has_downloads,omitempty"` - HasWiki *bool `json:"has_wiki,omitempty"` - HasPages *bool `json:"has_pages,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - Organization *string `json:"organization,omitempty"` - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` -} - -// PushEventRepoOwner is a basic representation of user/org in a PushEvent payload. -type PushEventRepoOwner struct { - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` -} - -// ReleaseEvent is triggered when a release is published. -// The Webhook event name is "release". -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#releaseevent -type ReleaseEvent struct { - // Action is the action that was performed. Possible value is: "published". - Action *string `json:"action,omitempty"` - Release *RepositoryRelease `json:"release,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// RepositoryEvent is triggered when a repository is created. -// The Webhook event name is "repository". -// -// Events of this type are not visible in timelines, they are only used to -// trigger organization webhooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#repositoryevent -type RepositoryEvent struct { - // Action is the action that was performed. Possible values are: "created", "deleted", - // "publicized", "privatized". - Action *string `json:"action,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// StatusEvent is triggered when the status of a Git commit changes. -// The Webhook event name is "status". -// -// Events of this type are not visible in timelines, they are only used to -// trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#statusevent -type StatusEvent struct { - SHA *string `json:"sha,omitempty"` - // State is the new state. Possible values are: "pending", "success", "failure", "error". - State *string `json:"state,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - Branches []*Branch `json:"branches,omitempty"` - - // The following fields are only populated by Webhook events. - ID *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Context *string `json:"context,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamEvent is triggered when an organization's team is created, modified or deleted. -// The Webhook event name is "team". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamevent -type TeamEvent struct { - Action *string `json:"action,omitempty"` - Team *Team `json:"team,omitempty"` - Changes *TeamChange `json:"changes,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// TeamAddEvent is triggered when a repository is added to a team. -// The Webhook event name is "team_add". -// -// Events of this type are not visible in timelines. These events are only used -// to trigger hooks. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamaddevent -type TeamAddEvent struct { - Team *Team `json:"team,omitempty"` - Repo *Repository `json:"repository,omitempty"` - - // The following fields are only populated by Webhook events. - Org *Organization `json:"organization,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} - -// WatchEvent is related to starring a repository, not watching. See this API -// blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/ -// -// The event’s actor is the user who starred a repository, and the event’s -// repository is the repository that was starred. -// -// GitHub API docs: https://developer.github.com/v3/activity/events/types/#watchevent -type WatchEvent struct { - // Action is the action that was performed. Possible value is: "started". - Action *string `json:"action,omitempty"` - - // The following fields are only populated by Webhook events. - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` - Installation *Installation `json:"installation,omitempty"` -} diff --git a/vendor/github.com/google/go-github/github/gists.go b/vendor/github.com/google/go-github/github/gists.go deleted file mode 100644 index 15276ea1d7..0000000000 --- a/vendor/github.com/google/go-github/github/gists.go +++ /dev/null @@ -1,351 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by BSD-style -// license that can be found in the LICENSE file. - -package github - -import ( - "context" - "fmt" - "time" -) - -// GistsService handles communication with the Gist related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gists/ -type GistsService service - -// Gist represents a GitHub's gist. -type Gist struct { - ID *string `json:"id,omitempty"` - Description *string `json:"description,omitempty"` - Public *bool `json:"public,omitempty"` - Owner *User `json:"owner,omitempty"` - Files map[GistFilename]GistFile `json:"files,omitempty"` - Comments *int `json:"comments,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitPullURL *string `json:"git_pull_url,omitempty"` - GitPushURL *string `json:"git_push_url,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -func (g Gist) String() string { - return Stringify(g) -} - -// GistFilename represents filename on a gist. -type GistFilename string - -// GistFile represents a file on a gist. -type GistFile struct { - Size *int `json:"size,omitempty"` - Filename *string `json:"filename,omitempty"` - Language *string `json:"language,omitempty"` - Type *string `json:"type,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - Content *string `json:"content,omitempty"` -} - -func (g GistFile) String() string { - return Stringify(g) -} - -// GistCommit represents a commit on a gist. -type GistCommit struct { - URL *string `json:"url,omitempty"` - Version *string `json:"version,omitempty"` - User *User `json:"user,omitempty"` - ChangeStatus *CommitStats `json:"change_status,omitempty"` - CommittedAt *Timestamp `json:"committed_at,omitempty"` -} - -func (gc GistCommit) String() string { - return Stringify(gc) -} - -// GistFork represents a fork of a gist. -type GistFork struct { - URL *string `json:"url,omitempty"` - User *User `json:"user,omitempty"` - ID *string `json:"id,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -func (gf GistFork) String() string { - return Stringify(gf) -} - -// GistListOptions specifies the optional parameters to the -// GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods. -type GistListOptions struct { - // Since filters Gists by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// List gists for a user. Passing the empty string will list -// all public gists if called anonymously. However, if the call -// is authenticated, it will returns all gists for the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) List(ctx context.Context, user string, opt *GistListOptions) ([]*Gist, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gists", user) - } else { - u = "gists" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListAll lists all public gists. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListAll(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/public", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// ListStarred lists starred gists of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListStarred(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/starred", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gists []*Gist - resp, err := s.client.Do(ctx, req, &gists) - if err != nil { - return nil, resp, err - } - - return gists, resp, nil -} - -// Get a single gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-single-gist -func (s *GistsService) Get(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// GetRevision gets a specific revision of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist -func (s *GistsService) GetRevision(ctx context.Context, id, sha string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/%v", id, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - gist := new(Gist) - resp, err := s.client.Do(ctx, req, gist) - if err != nil { - return nil, resp, err - } - - return gist, resp, nil -} - -// Create a gist for authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#create-a-gist -func (s *GistsService) Create(ctx context.Context, gist *Gist) (*Gist, *Response, error) { - u := "gists" - req, err := s.client.NewRequest("POST", u, gist) - if err != nil { - return nil, nil, err - } - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// Edit a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#edit-a-gist -func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("PATCH", u, gist) - if err != nil { - return nil, nil, err - } - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListCommits lists commits of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-commits -func (s *GistsService) ListCommits(ctx context.Context, id string, opt *ListOptions) ([]*GistCommit, *Response, error) { - u := fmt.Sprintf("gists/%v/commits", id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gistCommits []*GistCommit - resp, err := s.client.Do(ctx, req, &gistCommits) - if err != nil { - return nil, resp, err - } - - return gistCommits, resp, nil -} - -// Delete a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#delete-a-gist -func (s *GistsService) Delete(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Star a gist on behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#star-a-gist -func (s *GistsService) Star(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// Unstar a gist on a behalf of authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#unstar-a-gist -func (s *GistsService) Unstar(ctx context.Context, id string) (*Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// IsStarred checks if a gist is starred by authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/gists/#check-if-a-gist-is-starred -func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Response, error) { - u := fmt.Sprintf("gists/%v/star", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - starred, err := parseBoolResponse(err) - return starred, resp, err -} - -// Fork a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#fork-a-gist -func (s *GistsService) Fork(ctx context.Context, id string) (*Gist, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - g := new(Gist) - resp, err := s.client.Do(ctx, req, g) - if err != nil { - return nil, resp, err - } - - return g, resp, nil -} - -// ListForks lists forks of a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/#list-gist-forks -func (s *GistsService) ListForks(ctx context.Context, id string) ([]*GistFork, *Response, error) { - u := fmt.Sprintf("gists/%v/forks", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var gistForks []*GistFork - resp, err := s.client.Do(ctx, req, &gistForks) - if err != nil { - return nil, resp, err - } - - return gistForks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/gists_comments.go b/vendor/github.com/google/go-github/github/gists_comments.go deleted file mode 100644 index 2d0722375e..0000000000 --- a/vendor/github.com/google/go-github/github/gists_comments.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// GistComment represents a Gist comment. -type GistComment struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` -} - -func (g GistComment) String() string { - return Stringify(g) -} - -// ListComments lists all comments for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist -func (s *GistsService) ListComments(ctx context.Context, gistID string, opt *ListOptions) ([]*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*GistComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment retrieves a single comment from a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#get-a-single-comment -func (s *GistsService) GetComment(ctx context.Context, gistID string, commentID int) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// CreateComment creates a comment for a gist. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#create-a-comment -func (s *GistsService) CreateComment(ctx context.Context, gistID string, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments", gistID) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment edits an existing gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#edit-a-comment -func (s *GistsService) EditComment(ctx context.Context, gistID string, commentID int, comment *GistComment) (*GistComment, *Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(GistComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a gist comment. -// -// GitHub API docs: https://developer.github.com/v3/gists/comments/#delete-a-comment -func (s *GistsService) DeleteComment(ctx context.Context, gistID string, commentID int) (*Response, error) { - u := fmt.Sprintf("gists/%v/comments/%v", gistID, commentID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git.go b/vendor/github.com/google/go-github/github/git.go deleted file mode 100644 index 1ce47437bd..0000000000 --- a/vendor/github.com/google/go-github/github/git.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 The go-github 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 github - -// GitService handles communication with the git data related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/git/ -type GitService service diff --git a/vendor/github.com/google/go-github/github/git_blobs.go b/vendor/github.com/google/go-github/github/git_blobs.go deleted file mode 100644 index 67ea74a196..0000000000 --- a/vendor/github.com/google/go-github/github/git_blobs.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Blob represents a blob object. -type Blob struct { - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` -} - -// GetBlob fetchs a blob from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#get-a-blob -func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha string) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - blob := new(Blob) - resp, err := s.client.Do(ctx, req, blob) - return blob, resp, err -} - -// CreateBlob creates a blob object. -// -// GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob -func (s *GitService) CreateBlob(ctx context.Context, owner string, repo string, blob *Blob) (*Blob, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/blobs", owner, repo) - req, err := s.client.NewRequest("POST", u, blob) - if err != nil { - return nil, nil, err - } - - t := new(Blob) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_commits.go b/vendor/github.com/google/go-github/github/git_commits.go deleted file mode 100644 index 3c49a8a299..0000000000 --- a/vendor/github.com/google/go-github/github/git_commits.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// SignatureVerification represents GPG signature verification. -type SignatureVerification struct { - Verified *bool `json:"verified,omitempty"` - Reason *string `json:"reason,omitempty"` - Signature *string `json:"signature,omitempty"` - Payload *string `json:"payload,omitempty"` -} - -// Commit represents a GitHub commit. -type Commit struct { - SHA *string `json:"sha,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *Tree `json:"tree,omitempty"` - Parents []Commit `json:"parents,omitempty"` - Stats *CommitStats `json:"stats,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` - - // CommentCount is the number of GitHub comments on the commit. This - // is only populated for requests that fetch GitHub data like - // Pulls.ListCommits, Repositories.ListCommits, etc. - CommentCount *int `json:"comment_count,omitempty"` -} - -func (c Commit) String() string { - return Stringify(c) -} - -// CommitAuthor represents the author or committer of a commit. The commit -// author may not correspond to a GitHub User. -type CommitAuthor struct { - Date *time.Time `json:"date,omitempty"` - Name *string `json:"name,omitempty"` - Email *string `json:"email,omitempty"` - - // The following fields are only populated by Webhook events. - Login *string `json:"username,omitempty"` // Renamed for go-github consistency. -} - -func (c CommitAuthor) String() string { - return Stringify(c) -} - -// GetCommit fetchs the Commit object for a given SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#get-a-commit -func (s *GitService) GetCommit(ctx context.Context, owner string, repo string, sha string) (*Commit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/commits/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// createCommit represents the body of a CreateCommit request. -type createCommit struct { - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` - Message *string `json:"message,omitempty"` - Tree *string `json:"tree,omitempty"` - Parents []string `json:"parents,omitempty"` -} - -// CreateCommit creates a new commit in a repository. -// commit must not be nil. -// -// The commit.Committer is optional and will be filled with the commit.Author -// data if omitted. If the commit.Author is omitted, it will be filled in with -// the authenticated user’s information and the current date. -// -// GitHub API docs: https://developer.github.com/v3/git/commits/#create-a-commit -func (s *GitService) CreateCommit(ctx context.Context, owner string, repo string, commit *Commit) (*Commit, *Response, error) { - if commit == nil { - return nil, nil, fmt.Errorf("commit must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/git/commits", owner, repo) - - parents := make([]string, len(commit.Parents)) - for i, parent := range commit.Parents { - parents[i] = *parent.SHA - } - - body := &createCommit{ - Author: commit.Author, - Committer: commit.Committer, - Message: commit.Message, - Parents: parents, - } - if commit.Tree != nil { - body.Tree = commit.Tree.SHA - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - c := new(Commit) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/git_refs.go b/vendor/github.com/google/go-github/github/git_refs.go deleted file mode 100644 index e78fdc6c09..0000000000 --- a/vendor/github.com/google/go-github/github/git_refs.go +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" -) - -// Reference represents a GitHub reference. -type Reference struct { - Ref *string `json:"ref"` - URL *string `json:"url"` - Object *GitObject `json:"object"` -} - -func (r Reference) String() string { - return Stringify(r) -} - -// GitObject represents a Git object. -type GitObject struct { - Type *string `json:"type"` - SHA *string `json:"sha"` - URL *string `json:"url"` -} - -func (o GitObject) String() string { - return Stringify(o) -} - -// createRefRequest represents the payload for creating a reference. -type createRefRequest struct { - Ref *string `json:"ref"` - SHA *string `json:"sha"` -} - -// updateRefRequest represents the payload for updating a reference. -type updateRefRequest struct { - SHA *string `json:"sha"` - Force *bool `json:"force"` -} - -// GetRef fetches a single Reference object for a given Git ref. -// If there is no exact match, GetRef will return an error. -// -// Note: The GitHub API can return multiple matches. -// If you wish to use this functionality please use the GetRefs() method. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref string) (*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if _, ok := err.(*json.UnmarshalTypeError); ok { - // Multiple refs, means there wasn't an exact match. - return nil, resp, errors.New("no exact match found for this ref") - } else if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetRefs fetches a slice of Reference objects for a given Git ref. -// If there is an exact match, only that ref is returned. -// If there is no exact match, GitHub returns all refs that start with ref. -// If returned error is nil, there will be at least 1 ref returned. -// For example: -// -// "heads/featureA" -> ["refs/heads/featureA"] // Exact match, single ref is returned. -// "heads/feature" -> ["refs/heads/featureA", "refs/heads/featureB"] // All refs that start with ref. -// "heads/notexist" -> [] // Returns an error. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference -func (s *GitService) GetRefs(ctx context.Context, owner string, repo string, ref string) ([]*Reference, *Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var rawJSON json.RawMessage - resp, err := s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, resp, err - } - - // Prioritize the most common case: a single returned ref. - r := new(Reference) - singleUnmarshalError := json.Unmarshal(rawJSON, r) - if singleUnmarshalError == nil { - return []*Reference{r}, resp, nil - } - - // Attempt to unmarshal multiple refs. - var rs []*Reference - multipleUnmarshalError := json.Unmarshal(rawJSON, &rs) - if multipleUnmarshalError == nil { - if len(rs) == 0 { - return nil, resp, fmt.Errorf("unexpected response from GitHub API: an array of refs with length 0") - } - return rs, resp, nil - } - - return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", singleUnmarshalError, multipleUnmarshalError) -} - -// ReferenceListOptions specifies optional parameters to the -// GitService.ListRefs method. -type ReferenceListOptions struct { - Type string `url:"-"` - - ListOptions -} - -// ListRefs lists all refs in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#get-all-references -func (s *GitService) ListRefs(ctx context.Context, owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error) { - var u string - if opt != nil && opt.Type != "" { - u = fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, opt.Type) - } else { - u = fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var rs []*Reference - resp, err := s.client.Do(ctx, req, &rs) - if err != nil { - return nil, resp, err - } - - return rs, resp, nil -} - -// CreateRef creates a new ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#create-a-reference -func (s *GitService) CreateRef(ctx context.Context, owner string, repo string, ref *Reference) (*Reference, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) - req, err := s.client.NewRequest("POST", u, &createRefRequest{ - // back-compat with previous behavior that didn't require 'refs/' prefix - Ref: String("refs/" + strings.TrimPrefix(*ref.Ref, "refs/")), - SHA: ref.Object.SHA, - }) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdateRef updates an existing ref in a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#update-a-reference -func (s *GitService) UpdateRef(ctx context.Context, owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error) { - refPath := strings.TrimPrefix(*ref.Ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, refPath) - req, err := s.client.NewRequest("PATCH", u, &updateRefRequest{ - SHA: ref.Object.SHA, - Force: &force, - }) - if err != nil { - return nil, nil, err - } - - r := new(Reference) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DeleteRef deletes a ref from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/refs/#delete-a-reference -func (s *GitService) DeleteRef(ctx context.Context, owner string, repo string, ref string) (*Response, error) { - ref = strings.TrimPrefix(ref, "refs/") - u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/git_tags.go b/vendor/github.com/google/go-github/github/git_tags.go deleted file mode 100644 index 08df3d3d1b..0000000000 --- a/vendor/github.com/google/go-github/github/git_tags.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Tag represents a tag object. -type Tag struct { - Tag *string `json:"tag,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - Message *string `json:"message,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` - Object *GitObject `json:"object,omitempty"` - Verification *SignatureVerification `json:"verification,omitempty"` -} - -// createTagRequest represents the body of a CreateTag request. This is mostly -// identical to Tag with the exception that the object SHA and Type are -// top-level fields, rather than being nested inside a JSON object. -type createTagRequest struct { - Tag *string `json:"tag,omitempty"` - Message *string `json:"message,omitempty"` - Object *string `json:"object,omitempty"` - Type *string `json:"type,omitempty"` - Tagger *CommitAuthor `json:"tagger,omitempty"` -} - -// GetTag fetchs a tag from a repo given a SHA. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#get-a-tag -func (s *GitService) GetTag(ctx context.Context, owner string, repo string, sha string) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags/%v", owner, repo, sha) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - tag := new(Tag) - resp, err := s.client.Do(ctx, req, tag) - return tag, resp, err -} - -// CreateTag creates a tag object. -// -// GitHub API docs: https://developer.github.com/v3/git/tags/#create-a-tag-object -func (s *GitService) CreateTag(ctx context.Context, owner string, repo string, tag *Tag) (*Tag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/tags", owner, repo) - - // convert Tag into a createTagRequest - tagRequest := &createTagRequest{ - Tag: tag.Tag, - Message: tag.Message, - Tagger: tag.Tagger, - } - if tag.Object != nil { - tagRequest.Object = tag.Object.SHA - tagRequest.Type = tag.Object.Type - } - - req, err := s.client.NewRequest("POST", u, tagRequest) - if err != nil { - return nil, nil, err - } - - t := new(Tag) - resp, err := s.client.Do(ctx, req, t) - return t, resp, err -} diff --git a/vendor/github.com/google/go-github/github/git_trees.go b/vendor/github.com/google/go-github/github/git_trees.go deleted file mode 100644 index 4d6809a880..0000000000 --- a/vendor/github.com/google/go-github/github/git_trees.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Tree represents a GitHub tree. -type Tree struct { - SHA *string `json:"sha,omitempty"` - Entries []TreeEntry `json:"tree,omitempty"` -} - -func (t Tree) String() string { - return Stringify(t) -} - -// TreeEntry represents the contents of a tree structure. TreeEntry can -// represent either a blob, a commit (in the case of a submodule), or another -// tree. -type TreeEntry struct { - SHA *string `json:"sha,omitempty"` - Path *string `json:"path,omitempty"` - Mode *string `json:"mode,omitempty"` - Type *string `json:"type,omitempty"` - Size *int `json:"size,omitempty"` - Content *string `json:"content,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (t TreeEntry) String() string { - return Stringify(t) -} - -// GetTree fetches the Tree object for a given sha hash from a repository. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#get-a-tree -func (s *GitService) GetTree(ctx context.Context, owner string, repo string, sha string, recursive bool) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees/%v", owner, repo, sha) - if recursive { - u += "?recursive=1" - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// createTree represents the body of a CreateTree request. -type createTree struct { - BaseTree string `json:"base_tree,omitempty"` - Entries []TreeEntry `json:"tree"` -} - -// CreateTree creates a new tree in a repository. If both a tree and a nested -// path modifying that tree are specified, it will overwrite the contents of -// that tree with the new path contents and write a new tree out. -// -// GitHub API docs: https://developer.github.com/v3/git/trees/#create-a-tree -func (s *GitService) CreateTree(ctx context.Context, owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/git/trees", owner, repo) - - body := &createTree{ - BaseTree: baseTree, - Entries: entries, - } - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - t := new(Tree) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/github-accessors.go b/vendor/github.com/google/go-github/github/github-accessors.go deleted file mode 100644 index 5368001033..0000000000 --- a/vendor/github.com/google/go-github/github/github-accessors.go +++ /dev/null @@ -1,7469 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by gen-accessors; DO NOT EDIT. - -package github - -import ( - "encoding/json" - "time" -) - -// GetRetryAfter returns the RetryAfter field if it's non-nil, zero value otherwise. -func (a *AbuseRateLimitError) GetRetryAfter() time.Duration { - if a == nil || a.RetryAfter == nil { - return 0 - } - return *a.RetryAfter -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AdminEnforcement) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetVerifiablePasswordAuthentication returns the VerifiablePasswordAuthentication field if it's non-nil, zero value otherwise. -func (a *APIMeta) GetVerifiablePasswordAuthentication() bool { - if a == nil || a.VerifiablePasswordAuthentication == nil { - return false - } - return *a.VerifiablePasswordAuthentication -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetCreatedAt() Timestamp { - if a == nil || a.CreatedAt == nil { - return Timestamp{} - } - return *a.CreatedAt -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *Authorization) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetHashedToken returns the HashedToken field if it's non-nil, zero value otherwise. -func (a *Authorization) GetHashedToken() string { - if a == nil || a.HashedToken == nil { - return "" - } - return *a.HashedToken -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (a *Authorization) GetID() int { - if a == nil || a.ID == nil { - return 0 - } - return *a.ID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetToken returns the Token field if it's non-nil, zero value otherwise. -func (a *Authorization) GetToken() string { - if a == nil || a.Token == nil { - return "" - } - return *a.Token -} - -// GetTokenLastEight returns the TokenLastEight field if it's non-nil, zero value otherwise. -func (a *Authorization) GetTokenLastEight() string { - if a == nil || a.TokenLastEight == nil { - return "" - } - return *a.TokenLastEight -} - -// GetUpdateAt returns the UpdateAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetUpdateAt() Timestamp { - if a == nil || a.UpdateAt == nil { - return Timestamp{} - } - return *a.UpdateAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *Authorization) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetName() string { - if a == nil || a.Name == nil { - return "" - } - return *a.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (a *AuthorizationApp) GetURL() string { - if a == nil || a.URL == nil { - return "" - } - return *a.URL -} - -// GetClientID returns the ClientID field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientID() string { - if a == nil || a.ClientID == nil { - return "" - } - return *a.ClientID -} - -// GetClientSecret returns the ClientSecret field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetClientSecret() string { - if a == nil || a.ClientSecret == nil { - return "" - } - return *a.ClientSecret -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetFingerprint returns the Fingerprint field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetFingerprint() string { - if a == nil || a.Fingerprint == nil { - return "" - } - return *a.Fingerprint -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNote() string { - if a == nil || a.Note == nil { - return "" - } - return *a.Note -} - -// GetNoteURL returns the NoteURL field if it's non-nil, zero value otherwise. -func (a *AuthorizationUpdateRequest) GetNoteURL() string { - if a == nil || a.NoteURL == nil { - return "" - } - return *a.NoteURL -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (b *Blob) GetContent() string { - if b == nil || b.Content == nil { - return "" - } - return *b.Content -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (b *Blob) GetEncoding() string { - if b == nil || b.Encoding == nil { - return "" - } - return *b.Encoding -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (b *Blob) GetSHA() string { - if b == nil || b.SHA == nil { - return "" - } - return *b.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (b *Blob) GetSize() int { - if b == nil || b.Size == nil { - return 0 - } - return *b.Size -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (b *Blob) GetURL() string { - if b == nil || b.URL == nil { - return "" - } - return *b.URL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (b *Branch) GetName() string { - if b == nil || b.Name == nil { - return "" - } - return *b.Name -} - -// GetProtected returns the Protected field if it's non-nil, zero value otherwise. -func (b *Branch) GetProtected() bool { - if b == nil || b.Protected == nil { - return false - } - return *b.Protected -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetBody() string { - if c == nil || c.Body == nil { - return "" - } - return *c.Body -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetKey() string { - if c == nil || c.Key == nil { - return "" - } - return *c.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CodeOfConduct) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetPath() string { - if c == nil || c.Path == nil { - return "" - } - return *c.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CodeResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CodeSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetCommitURL() string { - if c == nil || c.CommitURL == nil { - return "" - } - return *c.CommitURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetRepositoryURL() string { - if c == nil || c.RepositoryURL == nil { - return "" - } - return *c.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetState() string { - if c == nil || c.State == nil { - return "" - } - return *c.State -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (c *CombinedStatus) GetTotalCount() int { - if c == nil || c.TotalCount == nil { - return 0 - } - return *c.TotalCount -} - -// GetCommentCount returns the CommentCount field if it's non-nil, zero value otherwise. -func (c *Commit) GetCommentCount() int { - if c == nil || c.CommentCount == nil { - return 0 - } - return *c.CommentCount -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Commit) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *Commit) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *Commit) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Commit) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetDate returns the Date field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetDate() time.Time { - if c == nil || c.Date == nil { - return time.Time{} - } - return *c.Date -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetEmail() string { - if c == nil || c.Email == nil { - return "" - } - return *c.Email -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (c *CommitAuthor) GetName() string { - if c == nil || c.Name == nil { - return "" - } - return *c.Name -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (c *CommitCommentEvent) GetAction() string { - if c == nil || c.Action == nil { - return "" - } - return *c.Action -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetBlobURL returns the BlobURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetBlobURL() string { - if c == nil || c.BlobURL == nil { - return "" - } - return *c.BlobURL -} - -// GetChanges returns the Changes field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetChanges() int { - if c == nil || c.Changes == nil { - return 0 - } - return *c.Changes -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetContentsURL() string { - if c == nil || c.ContentsURL == nil { - return "" - } - return *c.ContentsURL -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetFilename() string { - if c == nil || c.Filename == nil { - return "" - } - return *c.Filename -} - -// GetPatch returns the Patch field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetPatch() string { - if c == nil || c.Patch == nil { - return "" - } - return *c.Patch -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetRawURL() string { - if c == nil || c.RawURL == nil { - return "" - } - return *c.RawURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitFile) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetCommentsURL() string { - if c == nil || c.CommentsURL == nil { - return "" - } - return *c.CommentsURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitResult) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetAheadBy returns the AheadBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetAheadBy() int { - if c == nil || c.AheadBy == nil { - return 0 - } - return *c.AheadBy -} - -// GetBehindBy returns the BehindBy field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetBehindBy() int { - if c == nil || c.BehindBy == nil { - return 0 - } - return *c.BehindBy -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetDiffURL() string { - if c == nil || c.DiffURL == nil { - return "" - } - return *c.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPatchURL() string { - if c == nil || c.PatchURL == nil { - return "" - } - return *c.PatchURL -} - -// GetPermalinkURL returns the PermalinkURL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetPermalinkURL() string { - if c == nil || c.PermalinkURL == nil { - return "" - } - return *c.PermalinkURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetStatus() string { - if c == nil || c.Status == nil { - return "" - } - return *c.Status -} - -// GetTotalCommits returns the TotalCommits field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetTotalCommits() int { - if c == nil || c.TotalCommits == nil { - return 0 - } - return *c.TotalCommits -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *CommitsComparison) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetIncompleteResults() bool { - if c == nil || c.IncompleteResults == nil { - return false - } - return *c.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitsSearchResult) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetAdditions() int { - if c == nil || c.Additions == nil { - return 0 - } - return *c.Additions -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetDeletions() int { - if c == nil || c.Deletions == nil { - return 0 - } - return *c.Deletions -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *CommitStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetHealthPercentage returns the HealthPercentage field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetHealthPercentage() int { - if c == nil || c.HealthPercentage == nil { - return 0 - } - return *c.HealthPercentage -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (c *CommunityHealthMetrics) GetUpdatedAt() time.Time { - if c == nil || c.UpdatedAt == nil { - return time.Time{} - } - return *c.UpdatedAt -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetAvatarURL() string { - if c == nil || c.AvatarURL == nil { - return "" - } - return *c.AvatarURL -} - -// GetContributions returns the Contributions field if it's non-nil, zero value otherwise. -func (c *Contributor) GetContributions() int { - if c == nil || c.Contributions == nil { - return 0 - } - return *c.Contributions -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetEventsURL() string { - if c == nil || c.EventsURL == nil { - return "" - } - return *c.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowersURL() string { - if c == nil || c.FollowersURL == nil { - return "" - } - return *c.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetFollowingURL() string { - if c == nil || c.FollowingURL == nil { - return "" - } - return *c.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGistsURL() string { - if c == nil || c.GistsURL == nil { - return "" - } - return *c.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetGravatarID() string { - if c == nil || c.GravatarID == nil { - return "" - } - return *c.GravatarID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetHTMLURL() string { - if c == nil || c.HTMLURL == nil { - return "" - } - return *c.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (c *Contributor) GetID() int { - if c == nil || c.ID == nil { - return 0 - } - return *c.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (c *Contributor) GetLogin() string { - if c == nil || c.Login == nil { - return "" - } - return *c.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetOrganizationsURL() string { - if c == nil || c.OrganizationsURL == nil { - return "" - } - return *c.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReceivedEventsURL() string { - if c == nil || c.ReceivedEventsURL == nil { - return "" - } - return *c.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetReposURL() string { - if c == nil || c.ReposURL == nil { - return "" - } - return *c.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSiteAdmin() bool { - if c == nil || c.SiteAdmin == nil { - return false - } - return *c.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetStarredURL() string { - if c == nil || c.StarredURL == nil { - return "" - } - return *c.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetSubscriptionsURL() string { - if c == nil || c.SubscriptionsURL == nil { - return "" - } - return *c.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (c *Contributor) GetType() string { - if c == nil || c.Type == nil { - return "" - } - return *c.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (c *Contributor) GetURL() string { - if c == nil || c.URL == nil { - return "" - } - return *c.URL -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (c *ContributorStats) GetTotal() int { - if c == nil || c.Total == nil { - return 0 - } - return *c.Total -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *createCommit) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetTree returns the Tree field if it's non-nil, zero value otherwise. -func (c *createCommit) GetTree() string { - if c == nil || c.Tree == nil { - return "" - } - return *c.Tree -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetDescription() string { - if c == nil || c.Description == nil { - return "" - } - return *c.Description -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetMasterBranch() string { - if c == nil || c.MasterBranch == nil { - return "" - } - return *c.MasterBranch -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetPusherType() string { - if c == nil || c.PusherType == nil { - return "" - } - return *c.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRef() string { - if c == nil || c.Ref == nil { - return "" - } - return *c.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (c *CreateEvent) GetRefType() string { - if c == nil || c.RefType == nil { - return "" - } - return *c.RefType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (c *createRefRequest) GetRef() string { - if c == nil || c.Ref == nil { - return "" - } - return *c.Ref -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (c *createRefRequest) GetSHA() string { - if c == nil || c.SHA == nil { - return "" - } - return *c.SHA -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (c *createTagRequest) GetMessage() string { - if c == nil || c.Message == nil { - return "" - } - return *c.Message -} - -// GetObject returns the Object field if it's non-nil, zero value otherwise. -func (c *createTagRequest) GetObject() string { - if c == nil || c.Object == nil { - return "" - } - return *c.Object -} - -// GetTag returns the Tag field if it's non-nil, zero value otherwise. -func (c *createTagRequest) GetTag() string { - if c == nil || c.Tag == nil { - return "" - } - return *c.Tag -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (c *createTagRequest) GetType() string { - if c == nil || c.Type == nil { - return "" - } - return *c.Type -} - -// GetPusherType returns the PusherType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetPusherType() string { - if d == nil || d.PusherType == nil { - return "" - } - return *d.PusherType -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRefType returns the RefType field if it's non-nil, zero value otherwise. -func (d *DeleteEvent) GetRefType() string { - if d == nil || d.RefType == nil { - return "" - } - return *d.RefType -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *Deployment) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *Deployment) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *Deployment) GetID() int { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (d *Deployment) GetSHA() string { - if d == nil || d.SHA == nil { - return "" - } - return *d.SHA -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetStatusesURL() string { - if d == nil || d.StatusesURL == nil { - return "" - } - return *d.StatusesURL -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *Deployment) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *Deployment) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (d *Deployment) GetURL() string { - if d == nil || d.URL == nil { - return "" - } - return *d.URL -} - -// GetAutoMerge returns the AutoMerge field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetAutoMerge() bool { - if d == nil || d.AutoMerge == nil { - return false - } - return *d.AutoMerge -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironment returns the Environment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetEnvironment() string { - if d == nil || d.Environment == nil { - return "" - } - return *d.Environment -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetPayload() string { - if d == nil || d.Payload == nil { - return "" - } - return *d.Payload -} - -// GetProductionEnvironment returns the ProductionEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetProductionEnvironment() bool { - if d == nil || d.ProductionEnvironment == nil { - return false - } - return *d.ProductionEnvironment -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRef() string { - if d == nil || d.Ref == nil { - return "" - } - return *d.Ref -} - -// GetRequiredContexts returns the RequiredContexts field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetRequiredContexts() []string { - if d == nil || d.RequiredContexts == nil { - return nil - } - return *d.RequiredContexts -} - -// GetTask returns the Task field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTask() string { - if d == nil || d.Task == nil { - return "" - } - return *d.Task -} - -// GetTransientEnvironment returns the TransientEnvironment field if it's non-nil, zero value otherwise. -func (d *DeploymentRequest) GetTransientEnvironment() bool { - if d == nil || d.TransientEnvironment == nil { - return false - } - return *d.TransientEnvironment -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetCreatedAt() Timestamp { - if d == nil || d.CreatedAt == nil { - return Timestamp{} - } - return *d.CreatedAt -} - -// GetDeploymentURL returns the DeploymentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDeploymentURL() string { - if d == nil || d.DeploymentURL == nil { - return "" - } - return *d.DeploymentURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetID() int { - if d == nil || d.ID == nil { - return 0 - } - return *d.ID -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetRepositoryURL() string { - if d == nil || d.RepositoryURL == nil { - return "" - } - return *d.RepositoryURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetTargetURL() string { - if d == nil || d.TargetURL == nil { - return "" - } - return *d.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (d *DeploymentStatus) GetUpdatedAt() Timestamp { - if d == nil || d.UpdatedAt == nil { - return Timestamp{} - } - return *d.UpdatedAt -} - -// GetAutoInactive returns the AutoInactive field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetAutoInactive() bool { - if d == nil || d.AutoInactive == nil { - return false - } - return *d.AutoInactive -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetDescription() string { - if d == nil || d.Description == nil { - return "" - } - return *d.Description -} - -// GetEnvironmentURL returns the EnvironmentURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetEnvironmentURL() string { - if d == nil || d.EnvironmentURL == nil { - return "" - } - return *d.EnvironmentURL -} - -// GetLogURL returns the LogURL field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetLogURL() string { - if d == nil || d.LogURL == nil { - return "" - } - return *d.LogURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (d *DeploymentStatusRequest) GetState() string { - if d == nil || d.State == nil { - return "" - } - return *d.State -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetBody() string { - if d == nil || d.Body == nil { - return "" - } - return *d.Body -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPath() string { - if d == nil || d.Path == nil { - return "" - } - return *d.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (d *DraftReviewComment) GetPosition() int { - if d == nil || d.Position == nil { - return 0 - } - return *d.Position -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (e *Event) GetCreatedAt() time.Time { - if e == nil || e.CreatedAt == nil { - return time.Time{} - } - return *e.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (e *Event) GetID() string { - if e == nil || e.ID == nil { - return "" - } - return *e.ID -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (e *Event) GetPublic() bool { - if e == nil || e.Public == nil { - return false - } - return *e.Public -} - -// GetRawPayload returns the RawPayload field if it's non-nil, zero value otherwise. -func (e *Event) GetRawPayload() json.RawMessage { - if e == nil || e.RawPayload == nil { - return json.RawMessage{} - } - return *e.RawPayload -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (e *Event) GetType() string { - if e == nil || e.Type == nil { - return "" - } - return *e.Type -} - -// GetHRef returns the HRef field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetHRef() string { - if f == nil || f.HRef == nil { - return "" - } - return *f.HRef -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (f *FeedLink) GetType() string { - if f == nil || f.Type == nil { - return "" - } - return *f.Type -} - -// GetCurrentUserActorURL returns the CurrentUserActorURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserActorURL() string { - if f == nil || f.CurrentUserActorURL == nil { - return "" - } - return *f.CurrentUserActorURL -} - -// GetCurrentUserOrganizationURL returns the CurrentUserOrganizationURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserOrganizationURL() string { - if f == nil || f.CurrentUserOrganizationURL == nil { - return "" - } - return *f.CurrentUserOrganizationURL -} - -// GetCurrentUserPublicURL returns the CurrentUserPublicURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserPublicURL() string { - if f == nil || f.CurrentUserPublicURL == nil { - return "" - } - return *f.CurrentUserPublicURL -} - -// GetCurrentUserURL returns the CurrentUserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetCurrentUserURL() string { - if f == nil || f.CurrentUserURL == nil { - return "" - } - return *f.CurrentUserURL -} - -// GetTimelineURL returns the TimelineURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetTimelineURL() string { - if f == nil || f.TimelineURL == nil { - return "" - } - return *f.TimelineURL -} - -// GetUserURL returns the UserURL field if it's non-nil, zero value otherwise. -func (f *Feeds) GetUserURL() string { - if f == nil || f.UserURL == nil { - return "" - } - return *f.UserURL -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (g *Gist) GetComments() int { - if g == nil || g.Comments == nil { - return 0 - } - return *g.Comments -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (g *Gist) GetDescription() string { - if g == nil || g.Description == nil { - return "" - } - return *g.Description -} - -// GetGitPullURL returns the GitPullURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPullURL() string { - if g == nil || g.GitPullURL == nil { - return "" - } - return *g.GitPullURL -} - -// GetGitPushURL returns the GitPushURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetGitPushURL() string { - if g == nil || g.GitPushURL == nil { - return "" - } - return *g.GitPushURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (g *Gist) GetHTMLURL() string { - if g == nil || g.HTMLURL == nil { - return "" - } - return *g.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Gist) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetPublic returns the Public field if it's non-nil, zero value otherwise. -func (g *Gist) GetPublic() bool { - if g == nil || g.Public == nil { - return false - } - return *g.Public -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Gist) GetUpdatedAt() time.Time { - if g == nil || g.UpdatedAt == nil { - return time.Time{} - } - return *g.UpdatedAt -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (g *GistComment) GetBody() string { - if g == nil || g.Body == nil { - return "" - } - return *g.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistComment) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistComment) GetID() int { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistComment) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetCommittedAt returns the CommittedAt field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetCommittedAt() Timestamp { - if g == nil || g.CommittedAt == nil { - return Timestamp{} - } - return *g.CommittedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetVersion returns the Version field if it's non-nil, zero value otherwise. -func (g *GistCommit) GetVersion() string { - if g == nil || g.Version == nil { - return "" - } - return *g.Version -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (g *GistFile) GetContent() string { - if g == nil || g.Content == nil { - return "" - } - return *g.Content -} - -// GetFilename returns the Filename field if it's non-nil, zero value otherwise. -func (g *GistFile) GetFilename() string { - if g == nil || g.Filename == nil { - return "" - } - return *g.Filename -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (g *GistFile) GetLanguage() string { - if g == nil || g.Language == nil { - return "" - } - return *g.Language -} - -// GetRawURL returns the RawURL field if it's non-nil, zero value otherwise. -func (g *GistFile) GetRawURL() string { - if g == nil || g.RawURL == nil { - return "" - } - return *g.RawURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (g *GistFile) GetSize() int { - if g == nil || g.Size == nil { - return 0 - } - return *g.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GistFile) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GistFork) GetID() string { - if g == nil || g.ID == nil { - return "" - } - return *g.ID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *GistFork) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GistFork) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetName() string { - if g == nil || g.Name == nil { - return "" - } - return *g.Name -} - -// GetSource returns the Source field if it's non-nil, zero value otherwise. -func (g *Gitignore) GetSource() string { - if g == nil || g.Source == nil { - return "" - } - return *g.Source -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (g *GitObject) GetSHA() string { - if g == nil || g.SHA == nil { - return "" - } - return *g.SHA -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (g *GitObject) GetType() string { - if g == nil || g.Type == nil { - return "" - } - return *g.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *GitObject) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetEmail() string { - if g == nil || g.Email == nil { - return "" - } - return *g.Email -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (g *GPGEmail) GetVerified() bool { - if g == nil || g.Verified == nil { - return false - } - return *g.Verified -} - -// GetCanCertify returns the CanCertify field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanCertify() bool { - if g == nil || g.CanCertify == nil { - return false - } - return *g.CanCertify -} - -// GetCanEncryptComms returns the CanEncryptComms field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptComms() bool { - if g == nil || g.CanEncryptComms == nil { - return false - } - return *g.CanEncryptComms -} - -// GetCanEncryptStorage returns the CanEncryptStorage field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanEncryptStorage() bool { - if g == nil || g.CanEncryptStorage == nil { - return false - } - return *g.CanEncryptStorage -} - -// GetCanSign returns the CanSign field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCanSign() bool { - if g == nil || g.CanSign == nil { - return false - } - return *g.CanSign -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetCreatedAt() time.Time { - if g == nil || g.CreatedAt == nil { - return time.Time{} - } - return *g.CreatedAt -} - -// GetExpiresAt returns the ExpiresAt field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetExpiresAt() time.Time { - if g == nil || g.ExpiresAt == nil { - return time.Time{} - } - return *g.ExpiresAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetID() int { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetKeyID returns the KeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetKeyID() string { - if g == nil || g.KeyID == nil { - return "" - } - return *g.KeyID -} - -// GetPrimaryKeyID returns the PrimaryKeyID field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPrimaryKeyID() int { - if g == nil || g.PrimaryKeyID == nil { - return 0 - } - return *g.PrimaryKeyID -} - -// GetPublicKey returns the PublicKey field if it's non-nil, zero value otherwise. -func (g *GPGKey) GetPublicKey() string { - if g == nil || g.PublicKey == nil { - return "" - } - return *g.PublicKey -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetCreatedAt() Timestamp { - if g == nil || g.CreatedAt == nil { - return Timestamp{} - } - return *g.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (g *Grant) GetID() int { - if g == nil || g.ID == nil { - return 0 - } - return *g.ID -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (g *Grant) GetUpdatedAt() Timestamp { - if g == nil || g.UpdatedAt == nil { - return Timestamp{} - } - return *g.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (g *Grant) GetURL() string { - if g == nil || g.URL == nil { - return "" - } - return *g.URL -} - -// GetActive returns the Active field if it's non-nil, zero value otherwise. -func (h *Hook) GetActive() bool { - if h == nil || h.Active == nil { - return false - } - return *h.Active -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetCreatedAt() time.Time { - if h == nil || h.CreatedAt == nil { - return time.Time{} - } - return *h.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (h *Hook) GetID() int { - if h == nil || h.ID == nil { - return 0 - } - return *h.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (h *Hook) GetName() string { - if h == nil || h.Name == nil { - return "" - } - return *h.Name -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (h *Hook) GetUpdatedAt() time.Time { - if h == nil || h.UpdatedAt == nil { - return time.Time{} - } - return *h.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (h *Hook) GetURL() string { - if h == nil || h.URL == nil { - return "" - } - return *h.URL -} - -// GetAuthorsCount returns the AuthorsCount field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsCount() int { - if i == nil || i.AuthorsCount == nil { - return 0 - } - return *i.AuthorsCount -} - -// GetAuthorsURL returns the AuthorsURL field if it's non-nil, zero value otherwise. -func (i *Import) GetAuthorsURL() string { - if i == nil || i.AuthorsURL == nil { - return "" - } - return *i.AuthorsURL -} - -// GetCommitCount returns the CommitCount field if it's non-nil, zero value otherwise. -func (i *Import) GetCommitCount() int { - if i == nil || i.CommitCount == nil { - return 0 - } - return *i.CommitCount -} - -// GetFailedStep returns the FailedStep field if it's non-nil, zero value otherwise. -func (i *Import) GetFailedStep() string { - if i == nil || i.FailedStep == nil { - return "" - } - return *i.FailedStep -} - -// GetHasLargeFiles returns the HasLargeFiles field if it's non-nil, zero value otherwise. -func (i *Import) GetHasLargeFiles() bool { - if i == nil || i.HasLargeFiles == nil { - return false - } - return *i.HasLargeFiles -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Import) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetHumanName returns the HumanName field if it's non-nil, zero value otherwise. -func (i *Import) GetHumanName() string { - if i == nil || i.HumanName == nil { - return "" - } - return *i.HumanName -} - -// GetLargeFilesCount returns the LargeFilesCount field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesCount() int { - if i == nil || i.LargeFilesCount == nil { - return 0 - } - return *i.LargeFilesCount -} - -// GetLargeFilesSize returns the LargeFilesSize field if it's non-nil, zero value otherwise. -func (i *Import) GetLargeFilesSize() int { - if i == nil || i.LargeFilesSize == nil { - return 0 - } - return *i.LargeFilesSize -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (i *Import) GetMessage() string { - if i == nil || i.Message == nil { - return "" - } - return *i.Message -} - -// GetPercent returns the Percent field if it's non-nil, zero value otherwise. -func (i *Import) GetPercent() int { - if i == nil || i.Percent == nil { - return 0 - } - return *i.Percent -} - -// GetPushPercent returns the PushPercent field if it's non-nil, zero value otherwise. -func (i *Import) GetPushPercent() int { - if i == nil || i.PushPercent == nil { - return 0 - } - return *i.PushPercent -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (i *Import) GetRepositoryURL() string { - if i == nil || i.RepositoryURL == nil { - return "" - } - return *i.RepositoryURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (i *Import) GetStatus() string { - if i == nil || i.Status == nil { - return "" - } - return *i.Status -} - -// GetStatusText returns the StatusText field if it's non-nil, zero value otherwise. -func (i *Import) GetStatusText() string { - if i == nil || i.StatusText == nil { - return "" - } - return *i.StatusText -} - -// GetTFVCProject returns the TFVCProject field if it's non-nil, zero value otherwise. -func (i *Import) GetTFVCProject() string { - if i == nil || i.TFVCProject == nil { - return "" - } - return *i.TFVCProject -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Import) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetUseLFS returns the UseLFS field if it's non-nil, zero value otherwise. -func (i *Import) GetUseLFS() string { - if i == nil || i.UseLFS == nil { - return "" - } - return *i.UseLFS -} - -// GetVCS returns the VCS field if it's non-nil, zero value otherwise. -func (i *Import) GetVCS() string { - if i == nil || i.VCS == nil { - return "" - } - return *i.VCS -} - -// GetVCSPassword returns the VCSPassword field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSPassword() string { - if i == nil || i.VCSPassword == nil { - return "" - } - return *i.VCSPassword -} - -// GetVCSURL returns the VCSURL field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSURL() string { - if i == nil || i.VCSURL == nil { - return "" - } - return *i.VCSURL -} - -// GetVCSUsername returns the VCSUsername field if it's non-nil, zero value otherwise. -func (i *Import) GetVCSUsername() string { - if i == nil || i.VCSUsername == nil { - return "" - } - return *i.VCSUsername -} - -// GetAccessTokensURL returns the AccessTokensURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetAccessTokensURL() string { - if i == nil || i.AccessTokensURL == nil { - return "" - } - return *i.AccessTokensURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Installation) GetID() int { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (i *Installation) GetRepositoriesURL() string { - if i == nil || i.RepositoriesURL == nil { - return "" - } - return *i.RepositoriesURL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetRepositorySelection returns the RepositorySelection field if it's non-nil, zero value otherwise. -func (i *InstallationRepositoriesEvent) GetRepositorySelection() string { - if i == nil || i.RepositorySelection == nil { - return "" - } - return *i.RepositorySelection -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Invitation) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (i *Invitation) GetEmail() string { - if i == nil || i.Email == nil { - return "" - } - return *i.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Invitation) GetID() int { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (i *Invitation) GetLogin() string { - if i == nil || i.Login == nil { - return "" - } - return *i.Login -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (i *Invitation) GetRole() string { - if i == nil || i.Role == nil { - return "" - } - return *i.Role -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *Issue) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetClosedAt() time.Time { - if i == nil || i.ClosedAt == nil { - return time.Time{} - } - return *i.ClosedAt -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (i *Issue) GetComments() int { - if i == nil || i.Comments == nil { - return 0 - } - return *i.Comments -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *Issue) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *Issue) GetID() int { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetLocked returns the Locked field if it's non-nil, zero value otherwise. -func (i *Issue) GetLocked() bool { - if i == nil || i.Locked == nil { - return false - } - return *i.Locked -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (i *Issue) GetNumber() int { - if i == nil || i.Number == nil { - return 0 - } - return *i.Number -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *Issue) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *Issue) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *Issue) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *Issue) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetHTMLURL() string { - if i == nil || i.HTMLURL == nil { - return "" - } - return *i.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetID() int { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetIssueURL() string { - if i == nil || i.IssueURL == nil { - return "" - } - return *i.IssueURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetUpdatedAt() time.Time { - if i == nil || i.UpdatedAt == nil { - return time.Time{} - } - return *i.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueComment) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssueCommentEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCommitID() string { - if i == nil || i.CommitID == nil { - return "" - } - return *i.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetCreatedAt() time.Time { - if i == nil || i.CreatedAt == nil { - return time.Time{} - } - return *i.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetEvent() string { - if i == nil || i.Event == nil { - return "" - } - return *i.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetID() int { - if i == nil || i.ID == nil { - return 0 - } - return *i.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (i *IssueEvent) GetURL() string { - if i == nil || i.URL == nil { - return "" - } - return *i.URL -} - -// GetAssignee returns the Assignee field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignee() string { - if i == nil || i.Assignee == nil { - return "" - } - return *i.Assignee -} - -// GetAssignees returns the Assignees field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetAssignees() []string { - if i == nil || i.Assignees == nil { - return nil - } - return *i.Assignees -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetBody() string { - if i == nil || i.Body == nil { - return "" - } - return *i.Body -} - -// GetLabels returns the Labels field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetLabels() []string { - if i == nil || i.Labels == nil { - return nil - } - return *i.Labels -} - -// GetMilestone returns the Milestone field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetMilestone() int { - if i == nil || i.Milestone == nil { - return 0 - } - return *i.Milestone -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetState() string { - if i == nil || i.State == nil { - return "" - } - return *i.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (i *IssueRequest) GetTitle() string { - if i == nil || i.Title == nil { - return "" - } - return *i.Title -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IssuesEvent) GetAction() string { - if i == nil || i.Action == nil { - return "" - } - return *i.Action -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetIncompleteResults() bool { - if i == nil || i.IncompleteResults == nil { - return false - } - return *i.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (i *IssuesSearchResult) GetTotal() int { - if i == nil || i.Total == nil { - return 0 - } - return *i.Total -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (k *Key) GetID() int { - if k == nil || k.ID == nil { - return 0 - } - return *k.ID -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (k *Key) GetKey() string { - if k == nil || k.Key == nil { - return "" - } - return *k.Key -} - -// GetReadOnly returns the ReadOnly field if it's non-nil, zero value otherwise. -func (k *Key) GetReadOnly() bool { - if k == nil || k.ReadOnly == nil { - return false - } - return *k.ReadOnly -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (k *Key) GetTitle() string { - if k == nil || k.Title == nil { - return "" - } - return *k.Title -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (k *Key) GetURL() string { - if k == nil || k.URL == nil { - return "" - } - return *k.URL -} - -// GetColor returns the Color field if it's non-nil, zero value otherwise. -func (l *Label) GetColor() string { - if l == nil || l.Color == nil { - return "" - } - return *l.Color -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (l *Label) GetID() int { - if l == nil || l.ID == nil { - return 0 - } - return *l.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *Label) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *Label) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (l *LabelEvent) GetAction() string { - if l == nil || l.Action == nil { - return "" - } - return *l.Action -} - -// GetOID returns the OID field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetOID() string { - if l == nil || l.OID == nil { - return "" - } - return *l.OID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetPath() string { - if l == nil || l.Path == nil { - return "" - } - return *l.Path -} - -// GetRefName returns the RefName field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetRefName() string { - if l == nil || l.RefName == nil { - return "" - } - return *l.RefName -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (l *LargeFile) GetSize() int { - if l == nil || l.Size == nil { - return 0 - } - return *l.Size -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (l *License) GetBody() string { - if l == nil || l.Body == nil { - return "" - } - return *l.Body -} - -// GetConditions returns the Conditions field if it's non-nil, zero value otherwise. -func (l *License) GetConditions() []string { - if l == nil || l.Conditions == nil { - return nil - } - return *l.Conditions -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (l *License) GetDescription() string { - if l == nil || l.Description == nil { - return "" - } - return *l.Description -} - -// GetFeatured returns the Featured field if it's non-nil, zero value otherwise. -func (l *License) GetFeatured() bool { - if l == nil || l.Featured == nil { - return false - } - return *l.Featured -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (l *License) GetHTMLURL() string { - if l == nil || l.HTMLURL == nil { - return "" - } - return *l.HTMLURL -} - -// GetImplementation returns the Implementation field if it's non-nil, zero value otherwise. -func (l *License) GetImplementation() string { - if l == nil || l.Implementation == nil { - return "" - } - return *l.Implementation -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (l *License) GetKey() string { - if l == nil || l.Key == nil { - return "" - } - return *l.Key -} - -// GetLimitations returns the Limitations field if it's non-nil, zero value otherwise. -func (l *License) GetLimitations() []string { - if l == nil || l.Limitations == nil { - return nil - } - return *l.Limitations -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (l *License) GetName() string { - if l == nil || l.Name == nil { - return "" - } - return *l.Name -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (l *License) GetPermissions() []string { - if l == nil || l.Permissions == nil { - return nil - } - return *l.Permissions -} - -// GetSPDXID returns the SPDXID field if it's non-nil, zero value otherwise. -func (l *License) GetSPDXID() string { - if l == nil || l.SPDXID == nil { - return "" - } - return *l.SPDXID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (l *License) GetURL() string { - if l == nil || l.URL == nil { - return "" - } - return *l.URL -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (m *markdownRequest) GetContext() string { - if m == nil || m.Context == nil { - return "" - } - return *m.Context -} - -// GetMode returns the Mode field if it's non-nil, zero value otherwise. -func (m *markdownRequest) GetMode() string { - if m == nil || m.Mode == nil { - return "" - } - return *m.Mode -} - -// GetText returns the Text field if it's non-nil, zero value otherwise. -func (m *markdownRequest) GetText() string { - if m == nil || m.Text == nil { - return "" - } - return *m.Text -} - -// GetText returns the Text field if it's non-nil, zero value otherwise. -func (m *Match) GetText() string { - if m == nil || m.Text == nil { - return "" - } - return *m.Text -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MemberEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetOrganizationURL returns the OrganizationURL field if it's non-nil, zero value otherwise. -func (m *Membership) GetOrganizationURL() string { - if m == nil || m.OrganizationURL == nil { - return "" - } - return *m.OrganizationURL -} - -// GetRole returns the Role field if it's non-nil, zero value otherwise. -func (m *Membership) GetRole() string { - if m == nil || m.Role == nil { - return "" - } - return *m.Role -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Membership) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Membership) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetScope returns the Scope field if it's non-nil, zero value otherwise. -func (m *MembershipEvent) GetScope() string { - if m == nil || m.Scope == nil { - return "" - } - return *m.Scope -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Metric) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetKey returns the Key field if it's non-nil, zero value otherwise. -func (m *Metric) GetKey() string { - if m == nil || m.Key == nil { - return "" - } - return *m.Key -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (m *Metric) GetName() string { - if m == nil || m.Name == nil { - return "" - } - return *m.Name -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Metric) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetCreatedAt() string { - if m == nil || m.CreatedAt == nil { - return "" - } - return *m.CreatedAt -} - -// GetExcludeAttachments returns the ExcludeAttachments field if it's non-nil, zero value otherwise. -func (m *Migration) GetExcludeAttachments() bool { - if m == nil || m.ExcludeAttachments == nil { - return false - } - return *m.ExcludeAttachments -} - -// GetGUID returns the GUID field if it's non-nil, zero value otherwise. -func (m *Migration) GetGUID() string { - if m == nil || m.GUID == nil { - return "" - } - return *m.GUID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Migration) GetID() int { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLockRepositories returns the LockRepositories field if it's non-nil, zero value otherwise. -func (m *Migration) GetLockRepositories() bool { - if m == nil || m.LockRepositories == nil { - return false - } - return *m.LockRepositories -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Migration) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Migration) GetUpdatedAt() string { - if m == nil || m.UpdatedAt == nil { - return "" - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Migration) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedAt() time.Time { - if m == nil || m.ClosedAt == nil { - return time.Time{} - } - return *m.ClosedAt -} - -// GetClosedIssues returns the ClosedIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetClosedIssues() int { - if m == nil || m.ClosedIssues == nil { - return 0 - } - return *m.ClosedIssues -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetCreatedAt() time.Time { - if m == nil || m.CreatedAt == nil { - return time.Time{} - } - return *m.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDescription() string { - if m == nil || m.Description == nil { - return "" - } - return *m.Description -} - -// GetDueOn returns the DueOn field if it's non-nil, zero value otherwise. -func (m *Milestone) GetDueOn() time.Time { - if m == nil || m.DueOn == nil { - return time.Time{} - } - return *m.DueOn -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetHTMLURL() string { - if m == nil || m.HTMLURL == nil { - return "" - } - return *m.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (m *Milestone) GetID() int { - if m == nil || m.ID == nil { - return 0 - } - return *m.ID -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetLabelsURL() string { - if m == nil || m.LabelsURL == nil { - return "" - } - return *m.LabelsURL -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (m *Milestone) GetNumber() int { - if m == nil || m.Number == nil { - return 0 - } - return *m.Number -} - -// GetOpenIssues returns the OpenIssues field if it's non-nil, zero value otherwise. -func (m *Milestone) GetOpenIssues() int { - if m == nil || m.OpenIssues == nil { - return 0 - } - return *m.OpenIssues -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (m *Milestone) GetState() string { - if m == nil || m.State == nil { - return "" - } - return *m.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (m *Milestone) GetTitle() string { - if m == nil || m.Title == nil { - return "" - } - return *m.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (m *Milestone) GetUpdatedAt() time.Time { - if m == nil || m.UpdatedAt == nil { - return time.Time{} - } - return *m.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (m *Milestone) GetURL() string { - if m == nil || m.URL == nil { - return "" - } - return *m.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (m *MilestoneEvent) GetAction() string { - if m == nil || m.Action == nil { - return "" - } - return *m.Action -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBase() string { - if n == nil || n.Base == nil { - return "" - } - return *n.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetBody() string { - if n == nil || n.Body == nil { - return "" - } - return *n.Body -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetHead() string { - if n == nil || n.Head == nil { - return "" - } - return *n.Head -} - -// GetIssue returns the Issue field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetIssue() int { - if n == nil || n.Issue == nil { - return 0 - } - return *n.Issue -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetMaintainerCanModify() bool { - if n == nil || n.MaintainerCanModify == nil { - return false - } - return *n.MaintainerCanModify -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NewPullRequest) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (n *Notification) GetID() string { - if n == nil || n.ID == nil { - return "" - } - return *n.ID -} - -// GetLastReadAt returns the LastReadAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetLastReadAt() time.Time { - if n == nil || n.LastReadAt == nil { - return time.Time{} - } - return *n.LastReadAt -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (n *Notification) GetReason() string { - if n == nil || n.Reason == nil { - return "" - } - return *n.Reason -} - -// GetUnread returns the Unread field if it's non-nil, zero value otherwise. -func (n *Notification) GetUnread() bool { - if n == nil || n.Unread == nil { - return false - } - return *n.Unread -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (n *Notification) GetUpdatedAt() time.Time { - if n == nil || n.UpdatedAt == nil { - return time.Time{} - } - return *n.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *Notification) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetLatestCommentURL returns the LatestCommentURL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetLatestCommentURL() string { - if n == nil || n.LatestCommentURL == nil { - return "" - } - return *n.LatestCommentURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetTitle() string { - if n == nil || n.Title == nil { - return "" - } - return *n.Title -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetType() string { - if n == nil || n.Type == nil { - return "" - } - return *n.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (n *NotificationSubject) GetURL() string { - if n == nil || n.URL == nil { - return "" - } - return *n.URL -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetAvatarURL() string { - if o == nil || o.AvatarURL == nil { - return "" - } - return *o.AvatarURL -} - -// GetBillingEmail returns the BillingEmail field if it's non-nil, zero value otherwise. -func (o *Organization) GetBillingEmail() string { - if o == nil || o.BillingEmail == nil { - return "" - } - return *o.BillingEmail -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (o *Organization) GetBlog() string { - if o == nil || o.Blog == nil { - return "" - } - return *o.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (o *Organization) GetCollaborators() int { - if o == nil || o.Collaborators == nil { - return 0 - } - return *o.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (o *Organization) GetCompany() string { - if o == nil || o.Company == nil { - return "" - } - return *o.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetCreatedAt() time.Time { - if o == nil || o.CreatedAt == nil { - return time.Time{} - } - return *o.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (o *Organization) GetDescription() string { - if o == nil || o.Description == nil { - return "" - } - return *o.Description -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (o *Organization) GetDiskUsage() int { - if o == nil || o.DiskUsage == nil { - return 0 - } - return *o.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (o *Organization) GetEmail() string { - if o == nil || o.Email == nil { - return "" - } - return *o.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetEventsURL() string { - if o == nil || o.EventsURL == nil { - return "" - } - return *o.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowers() int { - if o == nil || o.Followers == nil { - return 0 - } - return *o.Followers -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (o *Organization) GetFollowing() int { - if o == nil || o.Following == nil { - return 0 - } - return *o.Following -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHooksURL() string { - if o == nil || o.HooksURL == nil { - return "" - } - return *o.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetHTMLURL() string { - if o == nil || o.HTMLURL == nil { - return "" - } - return *o.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (o *Organization) GetID() int { - if o == nil || o.ID == nil { - return 0 - } - return *o.ID -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetIssuesURL() string { - if o == nil || o.IssuesURL == nil { - return "" - } - return *o.IssuesURL -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (o *Organization) GetLocation() string { - if o == nil || o.Location == nil { - return "" - } - return *o.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (o *Organization) GetLogin() string { - if o == nil || o.Login == nil { - return "" - } - return *o.Login -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetMembersURL() string { - if o == nil || o.MembersURL == nil { - return "" - } - return *o.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (o *Organization) GetName() string { - if o == nil || o.Name == nil { - return "" - } - return *o.Name -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetOwnedPrivateRepos() int { - if o == nil || o.OwnedPrivateRepos == nil { - return 0 - } - return *o.OwnedPrivateRepos -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPrivateGists() int { - if o == nil || o.PrivateGists == nil { - return 0 - } - return *o.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicGists() int { - if o == nil || o.PublicGists == nil { - return 0 - } - return *o.PublicGists -} - -// GetPublicMembersURL returns the PublicMembersURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicMembersURL() string { - if o == nil || o.PublicMembersURL == nil { - return "" - } - return *o.PublicMembersURL -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetPublicRepos() int { - if o == nil || o.PublicRepos == nil { - return 0 - } - return *o.PublicRepos -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (o *Organization) GetReposURL() string { - if o == nil || o.ReposURL == nil { - return "" - } - return *o.ReposURL -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (o *Organization) GetTotalPrivateRepos() int { - if o == nil || o.TotalPrivateRepos == nil { - return 0 - } - return *o.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (o *Organization) GetType() string { - if o == nil || o.Type == nil { - return "" - } - return *o.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (o *Organization) GetUpdatedAt() time.Time { - if o == nil || o.UpdatedAt == nil { - return time.Time{} - } - return *o.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (o *Organization) GetURL() string { - if o == nil || o.URL == nil { - return "" - } - return *o.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrganizationEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (o *OrgBlockEvent) GetAction() string { - if o == nil || o.Action == nil { - return "" - } - return *o.Action -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *Page) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Page) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPageName returns the PageName field if it's non-nil, zero value otherwise. -func (p *Page) GetPageName() string { - if p == nil || p.PageName == nil { - return "" - } - return *p.PageName -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *Page) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetSummary returns the Summary field if it's non-nil, zero value otherwise. -func (p *Page) GetSummary() string { - if p == nil || p.Summary == nil { - return "" - } - return *p.Summary -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *Page) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PageBuildEvent) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetCNAME returns the CNAME field if it's non-nil, zero value otherwise. -func (p *Pages) GetCNAME() string { - if p == nil || p.CNAME == nil { - return "" - } - return *p.CNAME -} - -// GetCustom404 returns the Custom404 field if it's non-nil, zero value otherwise. -func (p *Pages) GetCustom404() bool { - if p == nil || p.Custom404 == nil { - return false - } - return *p.Custom404 -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *Pages) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *Pages) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Pages) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetCommit returns the Commit field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCommit() string { - if p == nil || p.Commit == nil { - return "" - } - return *p.Commit -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDuration returns the Duration field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetDuration() int { - if p == nil || p.Duration == nil { - return 0 - } - return *p.Duration -} - -// GetStatus returns the Status field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetStatus() string { - if p == nil || p.Status == nil { - return "" - } - return *p.Status -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PagesBuild) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PagesError) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetHookID returns the HookID field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetHookID() int { - if p == nil || p.HookID == nil { - return 0 - } - return *p.HookID -} - -// GetZen returns the Zen field if it's non-nil, zero value otherwise. -func (p *PingEvent) GetZen() string { - if p == nil || p.Zen == nil { - return "" - } - return *p.Zen -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (p *Plan) GetCollaborators() int { - if p == nil || p.Collaborators == nil { - return 0 - } - return *p.Collaborators -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Plan) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetPrivateRepos returns the PrivateRepos field if it's non-nil, zero value otherwise. -func (p *Plan) GetPrivateRepos() int { - if p == nil || p.PrivateRepos == nil { - return 0 - } - return *p.PrivateRepos -} - -// GetSpace returns the Space field if it's non-nil, zero value otherwise. -func (p *Plan) GetSpace() int { - if p == nil || p.Space == nil { - return 0 - } - return *p.Space -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *Project) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *Project) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *Project) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *Project) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetOwnerURL returns the OwnerURL field if it's non-nil, zero value otherwise. -func (p *Project) GetOwnerURL() string { - if p == nil || p.OwnerURL == nil { - return "" - } - return *p.OwnerURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *Project) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *Project) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetColumnID returns the ColumnID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnID() int { - if p == nil || p.ColumnID == nil { - return 0 - } - return *p.ColumnID -} - -// GetColumnURL returns the ColumnURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetColumnURL() string { - if p == nil || p.ColumnURL == nil { - return "" - } - return *p.ColumnURL -} - -// GetContentURL returns the ContentURL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetContentURL() string { - if p == nil || p.ContentURL == nil { - return "" - } - return *p.ContentURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetNote returns the Note field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetNote() string { - if p == nil || p.Note == nil { - return "" - } - return *p.Note -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *ProjectCard) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectCardEvent) GetAfterID() int { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetProjectURL returns the ProjectURL field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetProjectURL() string { - if p == nil || p.ProjectURL == nil { - return "" - } - return *p.ProjectURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *ProjectColumn) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAfterID returns the AfterID field if it's non-nil, zero value otherwise. -func (p *ProjectColumnEvent) GetAfterID() int { - if p == nil || p.AfterID == nil { - return 0 - } - return *p.AfterID -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *ProjectEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetAdditions() int { - if p == nil || p.Additions == nil { - return 0 - } - return *p.Additions -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetChangedFiles returns the ChangedFiles field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetChangedFiles() int { - if p == nil || p.ChangedFiles == nil { - return 0 - } - return *p.ChangedFiles -} - -// GetClosedAt returns the ClosedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetClosedAt() time.Time { - if p == nil || p.ClosedAt == nil { - return time.Time{} - } - return *p.ClosedAt -} - -// GetComments returns the Comments field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetComments() int { - if p == nil || p.Comments == nil { - return 0 - } - return *p.Comments -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDeletions() int { - if p == nil || p.Deletions == nil { - return 0 - } - return *p.Deletions -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetIssueURL returns the IssueURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetIssueURL() string { - if p == nil || p.IssueURL == nil { - return "" - } - return *p.IssueURL -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMaintainerCanModify() bool { - if p == nil || p.MaintainerCanModify == nil { - return false - } - return *p.MaintainerCanModify -} - -// GetMergeable returns the Mergeable field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeable() bool { - if p == nil || p.Mergeable == nil { - return false - } - return *p.Mergeable -} - -// GetMergeCommitSHA returns the MergeCommitSHA field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergeCommitSHA() string { - if p == nil || p.MergeCommitSHA == nil { - return "" - } - return *p.MergeCommitSHA -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMergedAt returns the MergedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetMergedAt() time.Time { - if p == nil || p.MergedAt == nil { - return time.Time{} - } - return *p.MergedAt -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetReviewCommentsURL returns the ReviewCommentsURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentsURL() string { - if p == nil || p.ReviewCommentsURL == nil { - return "" - } - return *p.ReviewCommentsURL -} - -// GetReviewCommentURL returns the ReviewCommentURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetReviewCommentURL() string { - if p == nil || p.ReviewCommentURL == nil { - return "" - } - return *p.ReviewCommentURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequest) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetLabel() string { - if p == nil || p.Label == nil { - return "" - } - return *p.Label -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestBranch) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetCreatedAt() time.Time { - if p == nil || p.CreatedAt == nil { - return time.Time{} - } - return *p.CreatedAt -} - -// GetDiffHunk returns the DiffHunk field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetDiffHunk() string { - if p == nil || p.DiffHunk == nil { - return "" - } - return *p.DiffHunk -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetInReplyTo returns the InReplyTo field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetInReplyTo() int { - if p == nil || p.InReplyTo == nil { - return 0 - } - return *p.InReplyTo -} - -// GetOriginalCommitID returns the OriginalCommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalCommitID() string { - if p == nil || p.OriginalCommitID == nil { - return "" - } - return *p.OriginalCommitID -} - -// GetOriginalPosition returns the OriginalPosition field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetOriginalPosition() int { - if p == nil || p.OriginalPosition == nil { - return 0 - } - return *p.OriginalPosition -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPath() string { - if p == nil || p.Path == nil { - return "" - } - return *p.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPosition() int { - if p == nil || p.Position == nil { - return 0 - } - return *p.Position -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetUpdatedAt() time.Time { - if p == nil || p.UpdatedAt == nil { - return time.Time{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestComment) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetNumber returns the Number field if it's non-nil, zero value otherwise. -func (p *PullRequestEvent) GetNumber() int { - if p == nil || p.Number == nil { - return 0 - } - return *p.Number -} - -// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetDiffURL() string { - if p == nil || p.DiffURL == nil { - return "" - } - return *p.DiffURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetPatchURL() string { - if p == nil || p.PatchURL == nil { - return "" - } - return *p.PatchURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PullRequestLinks) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetMerged returns the Merged field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMerged() bool { - if p == nil || p.Merged == nil { - return false - } - return *p.Merged -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PullRequestMergeResult) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetCommitID() string { - if p == nil || p.CommitID == nil { - return "" - } - return *p.CommitID -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetPullRequestURL returns the PullRequestURL field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetPullRequestURL() string { - if p == nil || p.PullRequestURL == nil { - return "" - } - return *p.PullRequestURL -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetSubmittedAt returns the SubmittedAt field if it's non-nil, zero value otherwise. -func (p *PullRequestReview) GetSubmittedAt() time.Time { - if p == nil || p.SubmittedAt == nil { - return time.Time{} - } - return *p.SubmittedAt -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewCommentEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewDismissalRequest) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewEvent) GetAction() string { - if p == nil || p.Action == nil { - return "" - } - return *p.Action -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewRequest) GetEvent() string { - if p == nil || p.Event == nil { - return "" - } - return *p.Event -} - -// GetDismissStaleReviews returns the DismissStaleReviews field if it's non-nil, zero value otherwise. -func (p *PullRequestReviewsEnforcementUpdate) GetDismissStaleReviews() bool { - if p == nil || p.DismissStaleReviews == nil { - return false - } - return *p.DismissStaleReviews -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (p *pullRequestUpdate) GetBase() string { - if p == nil || p.Base == nil { - return "" - } - return *p.Base -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (p *pullRequestUpdate) GetBody() string { - if p == nil || p.Body == nil { - return "" - } - return *p.Body -} - -// GetMaintainerCanModify returns the MaintainerCanModify field if it's non-nil, zero value otherwise. -func (p *pullRequestUpdate) GetMaintainerCanModify() bool { - if p == nil || p.MaintainerCanModify == nil { - return false - } - return *p.MaintainerCanModify -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (p *pullRequestUpdate) GetState() string { - if p == nil || p.State == nil { - return "" - } - return *p.State -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (p *pullRequestUpdate) GetTitle() string { - if p == nil || p.Title == nil { - return "" - } - return *p.Title -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetCommits() int { - if p == nil || p.Commits == nil { - return 0 - } - return *p.Commits -} - -// GetDay returns the Day field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetDay() int { - if p == nil || p.Day == nil { - return 0 - } - return *p.Day -} - -// GetHour returns the Hour field if it's non-nil, zero value otherwise. -func (p *PunchCard) GetHour() int { - if p == nil || p.Hour == nil { - return 0 - } - return *p.Hour -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetAfter() string { - if p == nil || p.After == nil { - return "" - } - return *p.After -} - -// GetBaseRef returns the BaseRef field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBaseRef() string { - if p == nil || p.BaseRef == nil { - return "" - } - return *p.BaseRef -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetBefore() string { - if p == nil || p.Before == nil { - return "" - } - return *p.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCompare() string { - if p == nil || p.Compare == nil { - return "" - } - return *p.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetCreated() bool { - if p == nil || p.Created == nil { - return false - } - return *p.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDeleted() bool { - if p == nil || p.Deleted == nil { - return false - } - return *p.Deleted -} - -// GetDistinctSize returns the DistinctSize field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetDistinctSize() int { - if p == nil || p.DistinctSize == nil { - return 0 - } - return *p.DistinctSize -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetForced() bool { - if p == nil || p.Forced == nil { - return false - } - return *p.Forced -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetHead() string { - if p == nil || p.Head == nil { - return "" - } - return *p.Head -} - -// GetPushID returns the PushID field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetPushID() int { - if p == nil || p.PushID == nil { - return 0 - } - return *p.PushID -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetRef() string { - if p == nil || p.Ref == nil { - return "" - } - return *p.Ref -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEvent) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetDistinct() bool { - if p == nil || p.Distinct == nil { - return false - } - return *p.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetID() string { - if p == nil || p.ID == nil { - return "" - } - return *p.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetMessage() string { - if p == nil || p.Message == nil { - return "" - } - return *p.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetSHA() string { - if p == nil || p.SHA == nil { - return "" - } - return *p.SHA -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTimestamp() Timestamp { - if p == nil || p.Timestamp == nil { - return Timestamp{} - } - return *p.Timestamp -} - -// GetTreeID returns the TreeID field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetTreeID() string { - if p == nil || p.TreeID == nil { - return "" - } - return *p.TreeID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventCommit) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetEmail() string { - if p == nil || p.Email == nil { - return "" - } - return *p.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepoOwner) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetArchiveURL() string { - if p == nil || p.ArchiveURL == nil { - return "" - } - return *p.ArchiveURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCloneURL() string { - if p == nil || p.CloneURL == nil { - return "" - } - return *p.CloneURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetCreatedAt() Timestamp { - if p == nil || p.CreatedAt == nil { - return Timestamp{} - } - return *p.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDefaultBranch() string { - if p == nil || p.DefaultBranch == nil { - return "" - } - return *p.DefaultBranch -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetDescription() string { - if p == nil || p.Description == nil { - return "" - } - return *p.Description -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFork() bool { - if p == nil || p.Fork == nil { - return false - } - return *p.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetForksCount() int { - if p == nil || p.ForksCount == nil { - return 0 - } - return *p.ForksCount -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetFullName() string { - if p == nil || p.FullName == nil { - return "" - } - return *p.FullName -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetGitURL() string { - if p == nil || p.GitURL == nil { - return "" - } - return *p.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasDownloads() bool { - if p == nil || p.HasDownloads == nil { - return false - } - return *p.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasIssues() bool { - if p == nil || p.HasIssues == nil { - return false - } - return *p.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasPages() bool { - if p == nil || p.HasPages == nil { - return false - } - return *p.HasPages -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHasWiki() bool { - if p == nil || p.HasWiki == nil { - return false - } - return *p.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHomepage() string { - if p == nil || p.Homepage == nil { - return "" - } - return *p.Homepage -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetHTMLURL() string { - if p == nil || p.HTMLURL == nil { - return "" - } - return *p.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetID() int { - if p == nil || p.ID == nil { - return 0 - } - return *p.ID -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetLanguage() string { - if p == nil || p.Language == nil { - return "" - } - return *p.Language -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetMasterBranch() string { - if p == nil || p.MasterBranch == nil { - return "" - } - return *p.MasterBranch -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetName() string { - if p == nil || p.Name == nil { - return "" - } - return *p.Name -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOpenIssuesCount() int { - if p == nil || p.OpenIssuesCount == nil { - return 0 - } - return *p.OpenIssuesCount -} - -// GetOrganization returns the Organization field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetOrganization() string { - if p == nil || p.Organization == nil { - return "" - } - return *p.Organization -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPrivate() bool { - if p == nil || p.Private == nil { - return false - } - return *p.Private -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetPushedAt() Timestamp { - if p == nil || p.PushedAt == nil { - return Timestamp{} - } - return *p.PushedAt -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSize() int { - if p == nil || p.Size == nil { - return 0 - } - return *p.Size -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSSHURL() string { - if p == nil || p.SSHURL == nil { - return "" - } - return *p.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStargazersCount() int { - if p == nil || p.StargazersCount == nil { - return 0 - } - return *p.StargazersCount -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetStatusesURL() string { - if p == nil || p.StatusesURL == nil { - return "" - } - return *p.StatusesURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetSVNURL() string { - if p == nil || p.SVNURL == nil { - return "" - } - return *p.SVNURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetUpdatedAt() Timestamp { - if p == nil || p.UpdatedAt == nil { - return Timestamp{} - } - return *p.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetURL() string { - if p == nil || p.URL == nil { - return "" - } - return *p.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (p *PushEventRepository) GetWatchersCount() int { - if p == nil || p.WatchersCount == nil { - return 0 - } - return *p.WatchersCount -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *Reaction) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Reaction) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetConfused returns the Confused field if it's non-nil, zero value otherwise. -func (r *Reactions) GetConfused() int { - if r == nil || r.Confused == nil { - return 0 - } - return *r.Confused -} - -// GetHeart returns the Heart field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHeart() int { - if r == nil || r.Heart == nil { - return 0 - } - return *r.Heart -} - -// GetHooray returns the Hooray field if it's non-nil, zero value otherwise. -func (r *Reactions) GetHooray() int { - if r == nil || r.Hooray == nil { - return 0 - } - return *r.Hooray -} - -// GetLaugh returns the Laugh field if it's non-nil, zero value otherwise. -func (r *Reactions) GetLaugh() int { - if r == nil || r.Laugh == nil { - return 0 - } - return *r.Laugh -} - -// GetMinusOne returns the MinusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetMinusOne() int { - if r == nil || r.MinusOne == nil { - return 0 - } - return *r.MinusOne -} - -// GetPlusOne returns the PlusOne field if it's non-nil, zero value otherwise. -func (r *Reactions) GetPlusOne() int { - if r == nil || r.PlusOne == nil { - return 0 - } - return *r.PlusOne -} - -// GetTotalCount returns the TotalCount field if it's non-nil, zero value otherwise. -func (r *Reactions) GetTotalCount() int { - if r == nil || r.TotalCount == nil { - return 0 - } - return *r.TotalCount -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reactions) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (r *Reference) GetRef() string { - if r == nil || r.Ref == nil { - return "" - } - return *r.Ref -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Reference) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBrowserDownloadURL returns the BrowserDownloadURL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetBrowserDownloadURL() string { - if r == nil || r.BrowserDownloadURL == nil { - return "" - } - return *r.BrowserDownloadURL -} - -// GetContentType returns the ContentType field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetContentType() string { - if r == nil || r.ContentType == nil { - return "" - } - return *r.ContentType -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDownloadCount returns the DownloadCount field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetDownloadCount() int { - if r == nil || r.DownloadCount == nil { - return 0 - } - return *r.DownloadCount -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetLabel returns the Label field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetLabel() string { - if r == nil || r.Label == nil { - return "" - } - return *r.Label -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *ReleaseAsset) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *ReleaseEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetFrom returns the From field if it's non-nil, zero value otherwise. -func (r *Rename) GetFrom() string { - if r == nil || r.From == nil { - return "" - } - return *r.From -} - -// GetTo returns the To field if it's non-nil, zero value otherwise. -func (r *Rename) GetTo() string { - if r == nil || r.To == nil { - return "" - } - return *r.To -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetIncompleteResults() bool { - if r == nil || r.IncompleteResults == nil { - return false - } - return *r.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (r *RepositoriesSearchResult) GetTotal() int { - if r == nil || r.Total == nil { - return 0 - } - return *r.Total -} - -// GetAllowMergeCommit returns the AllowMergeCommit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowMergeCommit() bool { - if r == nil || r.AllowMergeCommit == nil { - return false - } - return *r.AllowMergeCommit -} - -// GetAllowRebaseMerge returns the AllowRebaseMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowRebaseMerge() bool { - if r == nil || r.AllowRebaseMerge == nil { - return false - } - return *r.AllowRebaseMerge -} - -// GetAllowSquashMerge returns the AllowSquashMerge field if it's non-nil, zero value otherwise. -func (r *Repository) GetAllowSquashMerge() bool { - if r == nil || r.AllowSquashMerge == nil { - return false - } - return *r.AllowSquashMerge -} - -// GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetArchiveURL() string { - if r == nil || r.ArchiveURL == nil { - return "" - } - return *r.ArchiveURL -} - -// GetAssigneesURL returns the AssigneesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetAssigneesURL() string { - if r == nil || r.AssigneesURL == nil { - return "" - } - return *r.AssigneesURL -} - -// GetAutoInit returns the AutoInit field if it's non-nil, zero value otherwise. -func (r *Repository) GetAutoInit() bool { - if r == nil || r.AutoInit == nil { - return false - } - return *r.AutoInit -} - -// GetBlobsURL returns the BlobsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBlobsURL() string { - if r == nil || r.BlobsURL == nil { - return "" - } - return *r.BlobsURL -} - -// GetBranchesURL returns the BranchesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetBranchesURL() string { - if r == nil || r.BranchesURL == nil { - return "" - } - return *r.BranchesURL -} - -// GetCloneURL returns the CloneURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCloneURL() string { - if r == nil || r.CloneURL == nil { - return "" - } - return *r.CloneURL -} - -// GetCollaboratorsURL returns the CollaboratorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCollaboratorsURL() string { - if r == nil || r.CollaboratorsURL == nil { - return "" - } - return *r.CollaboratorsURL -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetCommitsURL returns the CommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCommitsURL() string { - if r == nil || r.CommitsURL == nil { - return "" - } - return *r.CommitsURL -} - -// GetCompareURL returns the CompareURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetCompareURL() string { - if r == nil || r.CompareURL == nil { - return "" - } - return *r.CompareURL -} - -// GetContentsURL returns the ContentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContentsURL() string { - if r == nil || r.ContentsURL == nil { - return "" - } - return *r.ContentsURL -} - -// GetContributorsURL returns the ContributorsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetContributorsURL() string { - if r == nil || r.ContributorsURL == nil { - return "" - } - return *r.ContributorsURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDefaultBranch returns the DefaultBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetDefaultBranch() string { - if r == nil || r.DefaultBranch == nil { - return "" - } - return *r.DefaultBranch -} - -// GetDeploymentsURL returns the DeploymentsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDeploymentsURL() string { - if r == nil || r.DeploymentsURL == nil { - return "" - } - return *r.DeploymentsURL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *Repository) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetDownloadsURL returns the DownloadsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetDownloadsURL() string { - if r == nil || r.DownloadsURL == nil { - return "" - } - return *r.DownloadsURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetEventsURL() string { - if r == nil || r.EventsURL == nil { - return "" - } - return *r.EventsURL -} - -// GetFork returns the Fork field if it's non-nil, zero value otherwise. -func (r *Repository) GetFork() bool { - if r == nil || r.Fork == nil { - return false - } - return *r.Fork -} - -// GetForksCount returns the ForksCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksCount() int { - if r == nil || r.ForksCount == nil { - return 0 - } - return *r.ForksCount -} - -// GetForksURL returns the ForksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetForksURL() string { - if r == nil || r.ForksURL == nil { - return "" - } - return *r.ForksURL -} - -// GetFullName returns the FullName field if it's non-nil, zero value otherwise. -func (r *Repository) GetFullName() string { - if r == nil || r.FullName == nil { - return "" - } - return *r.FullName -} - -// GetGitCommitsURL returns the GitCommitsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitCommitsURL() string { - if r == nil || r.GitCommitsURL == nil { - return "" - } - return *r.GitCommitsURL -} - -// GetGitignoreTemplate returns the GitignoreTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitignoreTemplate() string { - if r == nil || r.GitignoreTemplate == nil { - return "" - } - return *r.GitignoreTemplate -} - -// GetGitRefsURL returns the GitRefsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitRefsURL() string { - if r == nil || r.GitRefsURL == nil { - return "" - } - return *r.GitRefsURL -} - -// GetGitTagsURL returns the GitTagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitTagsURL() string { - if r == nil || r.GitTagsURL == nil { - return "" - } - return *r.GitTagsURL -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHasDownloads returns the HasDownloads field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasDownloads() bool { - if r == nil || r.HasDownloads == nil { - return false - } - return *r.HasDownloads -} - -// GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasIssues() bool { - if r == nil || r.HasIssues == nil { - return false - } - return *r.HasIssues -} - -// GetHasPages returns the HasPages field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasPages() bool { - if r == nil || r.HasPages == nil { - return false - } - return *r.HasPages -} - -// GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. -func (r *Repository) GetHasWiki() bool { - if r == nil || r.HasWiki == nil { - return false - } - return *r.HasWiki -} - -// GetHomepage returns the Homepage field if it's non-nil, zero value otherwise. -func (r *Repository) GetHomepage() string { - if r == nil || r.Homepage == nil { - return "" - } - return *r.Homepage -} - -// GetHooksURL returns the HooksURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHooksURL() string { - if r == nil || r.HooksURL == nil { - return "" - } - return *r.HooksURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *Repository) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetIssueCommentURL returns the IssueCommentURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueCommentURL() string { - if r == nil || r.IssueCommentURL == nil { - return "" - } - return *r.IssueCommentURL -} - -// GetIssueEventsURL returns the IssueEventsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssueEventsURL() string { - if r == nil || r.IssueEventsURL == nil { - return "" - } - return *r.IssueEventsURL -} - -// GetIssuesURL returns the IssuesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetIssuesURL() string { - if r == nil || r.IssuesURL == nil { - return "" - } - return *r.IssuesURL -} - -// GetKeysURL returns the KeysURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetKeysURL() string { - if r == nil || r.KeysURL == nil { - return "" - } - return *r.KeysURL -} - -// GetLabelsURL returns the LabelsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLabelsURL() string { - if r == nil || r.LabelsURL == nil { - return "" - } - return *r.LabelsURL -} - -// GetLanguage returns the Language field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguage() string { - if r == nil || r.Language == nil { - return "" - } - return *r.Language -} - -// GetLanguagesURL returns the LanguagesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetLanguagesURL() string { - if r == nil || r.LanguagesURL == nil { - return "" - } - return *r.LanguagesURL -} - -// GetLicenseTemplate returns the LicenseTemplate field if it's non-nil, zero value otherwise. -func (r *Repository) GetLicenseTemplate() string { - if r == nil || r.LicenseTemplate == nil { - return "" - } - return *r.LicenseTemplate -} - -// GetMasterBranch returns the MasterBranch field if it's non-nil, zero value otherwise. -func (r *Repository) GetMasterBranch() string { - if r == nil || r.MasterBranch == nil { - return "" - } - return *r.MasterBranch -} - -// GetMergesURL returns the MergesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMergesURL() string { - if r == nil || r.MergesURL == nil { - return "" - } - return *r.MergesURL -} - -// GetMilestonesURL returns the MilestonesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMilestonesURL() string { - if r == nil || r.MilestonesURL == nil { - return "" - } - return *r.MilestonesURL -} - -// GetMirrorURL returns the MirrorURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetMirrorURL() string { - if r == nil || r.MirrorURL == nil { - return "" - } - return *r.MirrorURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *Repository) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetNetworkCount returns the NetworkCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetNetworkCount() int { - if r == nil || r.NetworkCount == nil { - return 0 - } - return *r.NetworkCount -} - -// GetNotificationsURL returns the NotificationsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetNotificationsURL() string { - if r == nil || r.NotificationsURL == nil { - return "" - } - return *r.NotificationsURL -} - -// GetOpenIssuesCount returns the OpenIssuesCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetOpenIssuesCount() int { - if r == nil || r.OpenIssuesCount == nil { - return 0 - } - return *r.OpenIssuesCount -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *Repository) GetPermissions() map[string]bool { - if r == nil || r.Permissions == nil { - return map[string]bool{} - } - return *r.Permissions -} - -// GetPrivate returns the Private field if it's non-nil, zero value otherwise. -func (r *Repository) GetPrivate() bool { - if r == nil || r.Private == nil { - return false - } - return *r.Private -} - -// GetPullsURL returns the PullsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetPullsURL() string { - if r == nil || r.PullsURL == nil { - return "" - } - return *r.PullsURL -} - -// GetPushedAt returns the PushedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetPushedAt() Timestamp { - if r == nil || r.PushedAt == nil { - return Timestamp{} - } - return *r.PushedAt -} - -// GetReleasesURL returns the ReleasesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetReleasesURL() string { - if r == nil || r.ReleasesURL == nil { - return "" - } - return *r.ReleasesURL -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *Repository) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetSSHURL returns the SSHURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSSHURL() string { - if r == nil || r.SSHURL == nil { - return "" - } - return *r.SSHURL -} - -// GetStargazersCount returns the StargazersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersCount() int { - if r == nil || r.StargazersCount == nil { - return 0 - } - return *r.StargazersCount -} - -// GetStargazersURL returns the StargazersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStargazersURL() string { - if r == nil || r.StargazersURL == nil { - return "" - } - return *r.StargazersURL -} - -// GetStatusesURL returns the StatusesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetStatusesURL() string { - if r == nil || r.StatusesURL == nil { - return "" - } - return *r.StatusesURL -} - -// GetSubscribersCount returns the SubscribersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersCount() int { - if r == nil || r.SubscribersCount == nil { - return 0 - } - return *r.SubscribersCount -} - -// GetSubscribersURL returns the SubscribersURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscribersURL() string { - if r == nil || r.SubscribersURL == nil { - return "" - } - return *r.SubscribersURL -} - -// GetSubscriptionURL returns the SubscriptionURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSubscriptionURL() string { - if r == nil || r.SubscriptionURL == nil { - return "" - } - return *r.SubscriptionURL -} - -// GetSVNURL returns the SVNURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetSVNURL() string { - if r == nil || r.SVNURL == nil { - return "" - } - return *r.SVNURL -} - -// GetTagsURL returns the TagsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTagsURL() string { - if r == nil || r.TagsURL == nil { - return "" - } - return *r.TagsURL -} - -// GetTeamID returns the TeamID field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamID() int { - if r == nil || r.TeamID == nil { - return 0 - } - return *r.TeamID -} - -// GetTeamsURL returns the TeamsURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTeamsURL() string { - if r == nil || r.TeamsURL == nil { - return "" - } - return *r.TeamsURL -} - -// GetTreesURL returns the TreesURL field if it's non-nil, zero value otherwise. -func (r *Repository) GetTreesURL() string { - if r == nil || r.TreesURL == nil { - return "" - } - return *r.TreesURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *Repository) GetUpdatedAt() Timestamp { - if r == nil || r.UpdatedAt == nil { - return Timestamp{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *Repository) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetWatchersCount returns the WatchersCount field if it's non-nil, zero value otherwise. -func (r *Repository) GetWatchersCount() int { - if r == nil || r.WatchersCount == nil { - return 0 - } - return *r.WatchersCount -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCommitID() string { - if r == nil || r.CommitID == nil { - return "" - } - return *r.CommitID -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetPosition returns the Position field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetPosition() int { - if r == nil || r.Position == nil { - return 0 - } - return *r.Position -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryComment) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetCommentsURL returns the CommentsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetCommentsURL() string { - if r == nil || r.CommentsURL == nil { - return "" - } - return *r.CommentsURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryCommit) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryContent) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBranch returns the Branch field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetBranch() string { - if r == nil || r.Branch == nil { - return "" - } - return *r.Branch -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetMessage() string { - if r == nil || r.Message == nil { - return "" - } - return *r.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryContentFileOptions) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (r *RepositoryEvent) GetAction() string { - if r == nil || r.Action == nil { - return "" - } - return *r.Action -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetPermissions() string { - if r == nil || r.Permissions == nil { - return "" - } - return *r.Permissions -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryInvitation) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetContent() string { - if r == nil || r.Content == nil { - return "" - } - return *r.Content -} - -// GetDownloadURL returns the DownloadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetDownloadURL() string { - if r == nil || r.DownloadURL == nil { - return "" - } - return *r.DownloadURL -} - -// GetEncoding returns the Encoding field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetEncoding() string { - if r == nil || r.Encoding == nil { - return "" - } - return *r.Encoding -} - -// GetGitURL returns the GitURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetGitURL() string { - if r == nil || r.GitURL == nil { - return "" - } - return *r.GitURL -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetPath() string { - if r == nil || r.Path == nil { - return "" - } - return *r.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSHA() string { - if r == nil || r.SHA == nil { - return "" - } - return *r.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetSize() int { - if r == nil || r.Size == nil { - return 0 - } - return *r.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetType() string { - if r == nil || r.Type == nil { - return "" - } - return *r.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryLicense) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetBase returns the Base field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetBase() string { - if r == nil || r.Base == nil { - return "" - } - return *r.Base -} - -// GetCommitMessage returns the CommitMessage field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetCommitMessage() string { - if r == nil || r.CommitMessage == nil { - return "" - } - return *r.CommitMessage -} - -// GetHead returns the Head field if it's non-nil, zero value otherwise. -func (r *RepositoryMergeRequest) GetHead() string { - if r == nil || r.Head == nil { - return "" - } - return *r.Head -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (r *RepositoryPermissionLevel) GetPermission() string { - if r == nil || r.Permission == nil { - return "" - } - return *r.Permission -} - -// GetAssetsURL returns the AssetsURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetAssetsURL() string { - if r == nil || r.AssetsURL == nil { - return "" - } - return *r.AssetsURL -} - -// GetBody returns the Body field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetBody() string { - if r == nil || r.Body == nil { - return "" - } - return *r.Body -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetCreatedAt() Timestamp { - if r == nil || r.CreatedAt == nil { - return Timestamp{} - } - return *r.CreatedAt -} - -// GetDraft returns the Draft field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetDraft() bool { - if r == nil || r.Draft == nil { - return false - } - return *r.Draft -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetHTMLURL() string { - if r == nil || r.HTMLURL == nil { - return "" - } - return *r.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetPrerelease returns the Prerelease field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPrerelease() bool { - if r == nil || r.Prerelease == nil { - return false - } - return *r.Prerelease -} - -// GetPublishedAt returns the PublishedAt field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetPublishedAt() Timestamp { - if r == nil || r.PublishedAt == nil { - return Timestamp{} - } - return *r.PublishedAt -} - -// GetTagName returns the TagName field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTagName() string { - if r == nil || r.TagName == nil { - return "" - } - return *r.TagName -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetTargetCommitish returns the TargetCommitish field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetTargetCommitish() string { - if r == nil || r.TargetCommitish == nil { - return "" - } - return *r.TargetCommitish -} - -// GetUploadURL returns the UploadURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetUploadURL() string { - if r == nil || r.UploadURL == nil { - return "" - } - return *r.UploadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryRelease) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetName() string { - if r == nil || r.Name == nil { - return "" - } - return *r.Name -} - -// GetTarballURL returns the TarballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetTarballURL() string { - if r == nil || r.TarballURL == nil { - return "" - } - return *r.TarballURL -} - -// GetZipballURL returns the ZipballURL field if it's non-nil, zero value otherwise. -func (r *RepositoryTag) GetZipballURL() string { - if r == nil || r.ZipballURL == nil { - return "" - } - return *r.ZipballURL -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetContext() string { - if r == nil || r.Context == nil { - return "" - } - return *r.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetCreatedAt() time.Time { - if r == nil || r.CreatedAt == nil { - return time.Time{} - } - return *r.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetDescription() string { - if r == nil || r.Description == nil { - return "" - } - return *r.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetID() int { - if r == nil || r.ID == nil { - return 0 - } - return *r.ID -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetState() string { - if r == nil || r.State == nil { - return "" - } - return *r.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetTargetURL() string { - if r == nil || r.TargetURL == nil { - return "" - } - return *r.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetUpdatedAt() time.Time { - if r == nil || r.UpdatedAt == nil { - return time.Time{} - } - return *r.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (r *RepoStatus) GetURL() string { - if r == nil || r.URL == nil { - return "" - } - return *r.URL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *ServiceHook) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetPayload returns the Payload field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetPayload() string { - if s == nil || s.Payload == nil { - return "" - } - return *s.Payload -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetSignature returns the Signature field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetSignature() string { - if s == nil || s.Signature == nil { - return "" - } - return *s.Signature -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (s *SignatureVerification) GetVerified() bool { - if s == nil || s.Verified == nil { - return false - } - return *s.Verified -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *Source) GetID() int { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Source) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetEmail() string { - if s == nil || s.Email == nil { - return "" - } - return *s.Email -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetID() int { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetImportURL returns the ImportURL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetImportURL() string { - if s == nil || s.ImportURL == nil { - return "" - } - return *s.ImportURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetRemoteID returns the RemoteID field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteID() string { - if s == nil || s.RemoteID == nil { - return "" - } - return *s.RemoteID -} - -// GetRemoteName returns the RemoteName field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetRemoteName() string { - if s == nil || s.RemoteName == nil { - return "" - } - return *s.RemoteName -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *SourceImportAuthor) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *Stargazer) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetStarredAt returns the StarredAt field if it's non-nil, zero value otherwise. -func (s *StarredRepository) GetStarredAt() Timestamp { - if s == nil || s.StarredAt == nil { - return Timestamp{} - } - return *s.StarredAt -} - -// GetExcludeAttachments returns the ExcludeAttachments field if it's non-nil, zero value otherwise. -func (s *startMigration) GetExcludeAttachments() bool { - if s == nil || s.ExcludeAttachments == nil { - return false - } - return *s.ExcludeAttachments -} - -// GetLockRepositories returns the LockRepositories field if it's non-nil, zero value otherwise. -func (s *startMigration) GetLockRepositories() bool { - if s == nil || s.LockRepositories == nil { - return false - } - return *s.LockRepositories -} - -// GetContext returns the Context field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetContext() string { - if s == nil || s.Context == nil { - return "" - } - return *s.Context -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetDescription() string { - if s == nil || s.Description == nil { - return "" - } - return *s.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetID() int { - if s == nil || s.ID == nil { - return 0 - } - return *s.ID -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetName() string { - if s == nil || s.Name == nil { - return "" - } - return *s.Name -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetSHA() string { - if s == nil || s.SHA == nil { - return "" - } - return *s.SHA -} - -// GetState returns the State field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetState() string { - if s == nil || s.State == nil { - return "" - } - return *s.State -} - -// GetTargetURL returns the TargetURL field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetTargetURL() string { - if s == nil || s.TargetURL == nil { - return "" - } - return *s.TargetURL -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (s *StatusEvent) GetUpdatedAt() Timestamp { - if s == nil || s.UpdatedAt == nil { - return Timestamp{} - } - return *s.UpdatedAt -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (s *Subscription) GetCreatedAt() Timestamp { - if s == nil || s.CreatedAt == nil { - return Timestamp{} - } - return *s.CreatedAt -} - -// GetIgnored returns the Ignored field if it's non-nil, zero value otherwise. -func (s *Subscription) GetIgnored() bool { - if s == nil || s.Ignored == nil { - return false - } - return *s.Ignored -} - -// GetReason returns the Reason field if it's non-nil, zero value otherwise. -func (s *Subscription) GetReason() string { - if s == nil || s.Reason == nil { - return "" - } - return *s.Reason -} - -// GetRepositoryURL returns the RepositoryURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetRepositoryURL() string { - if s == nil || s.RepositoryURL == nil { - return "" - } - return *s.RepositoryURL -} - -// GetSubscribed returns the Subscribed field if it's non-nil, zero value otherwise. -func (s *Subscription) GetSubscribed() bool { - if s == nil || s.Subscribed == nil { - return false - } - return *s.Subscribed -} - -// GetThreadURL returns the ThreadURL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetThreadURL() string { - if s == nil || s.ThreadURL == nil { - return "" - } - return *s.ThreadURL -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (s *Subscription) GetURL() string { - if s == nil || s.URL == nil { - return "" - } - return *s.URL -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (t *Tag) GetMessage() string { - if t == nil || t.Message == nil { - return "" - } - return *t.Message -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tag) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetTag returns the Tag field if it's non-nil, zero value otherwise. -func (t *Tag) GetTag() string { - if t == nil || t.Tag == nil { - return "" - } - return *t.Tag -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Tag) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *Team) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Team) GetID() int { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *Team) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersCount returns the MembersCount field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersCount() int { - if t == nil || t.MembersCount == nil { - return 0 - } - return *t.MembersCount -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *Team) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *Team) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *Team) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *Team) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetReposCount returns the ReposCount field if it's non-nil, zero value otherwise. -func (t *Team) GetReposCount() int { - if t == nil || t.ReposCount == nil { - return 0 - } - return *t.ReposCount -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *Team) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *Team) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Team) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (t *TeamEvent) GetAction() string { - if t == nil || t.Action == nil { - return "" - } - return *t.Action -} - -// GetDescription returns the Description field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetDescription() string { - if t == nil || t.Description == nil { - return "" - } - return *t.Description -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetID() int { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetLDAPDN() string { - if t == nil || t.LDAPDN == nil { - return "" - } - return *t.LDAPDN -} - -// GetMembersURL returns the MembersURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetMembersURL() string { - if t == nil || t.MembersURL == nil { - return "" - } - return *t.MembersURL -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetName() string { - if t == nil || t.Name == nil { - return "" - } - return *t.Name -} - -// GetPermission returns the Permission field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPermission() string { - if t == nil || t.Permission == nil { - return "" - } - return *t.Permission -} - -// GetPrivacy returns the Privacy field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetPrivacy() string { - if t == nil || t.Privacy == nil { - return "" - } - return *t.Privacy -} - -// GetRepositoriesURL returns the RepositoriesURL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetRepositoriesURL() string { - if t == nil || t.RepositoriesURL == nil { - return "" - } - return *t.RepositoriesURL -} - -// GetSlug returns the Slug field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetSlug() string { - if t == nil || t.Slug == nil { - return "" - } - return *t.Slug -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TeamLDAPMapping) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetFragment returns the Fragment field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetFragment() string { - if t == nil || t.Fragment == nil { - return "" - } - return *t.Fragment -} - -// GetObjectType returns the ObjectType field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectType() string { - if t == nil || t.ObjectType == nil { - return "" - } - return *t.ObjectType -} - -// GetObjectURL returns the ObjectURL field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetObjectURL() string { - if t == nil || t.ObjectURL == nil { - return "" - } - return *t.ObjectURL -} - -// GetProperty returns the Property field if it's non-nil, zero value otherwise. -func (t *TextMatch) GetProperty() string { - if t == nil || t.Property == nil { - return "" - } - return *t.Property -} - -// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitID() string { - if t == nil || t.CommitID == nil { - return "" - } - return *t.CommitID -} - -// GetCommitURL returns the CommitURL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCommitURL() string { - if t == nil || t.CommitURL == nil { - return "" - } - return *t.CommitURL -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (t *Timeline) GetCreatedAt() time.Time { - if t == nil || t.CreatedAt == nil { - return time.Time{} - } - return *t.CreatedAt -} - -// GetEvent returns the Event field if it's non-nil, zero value otherwise. -func (t *Timeline) GetEvent() string { - if t == nil || t.Event == nil { - return "" - } - return *t.Event -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (t *Timeline) GetID() int { - if t == nil || t.ID == nil { - return 0 - } - return *t.ID -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *Timeline) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficClones) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetTimestamp() Timestamp { - if t == nil || t.Timestamp == nil { - return Timestamp{} - } - return *t.Timestamp -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficData) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetTitle returns the Title field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetTitle() string { - if t == nil || t.Title == nil { - return "" - } - return *t.Title -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficPath) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetReferrer returns the Referrer field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetReferrer() string { - if t == nil || t.Referrer == nil { - return "" - } - return *t.Referrer -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficReferrer) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetCount returns the Count field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetCount() int { - if t == nil || t.Count == nil { - return 0 - } - return *t.Count -} - -// GetUniques returns the Uniques field if it's non-nil, zero value otherwise. -func (t *TrafficViews) GetUniques() int { - if t == nil || t.Uniques == nil { - return 0 - } - return *t.Uniques -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *Tree) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetContent returns the Content field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetContent() string { - if t == nil || t.Content == nil { - return "" - } - return *t.Content -} - -// GetMode returns the Mode field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetMode() string { - if t == nil || t.Mode == nil { - return "" - } - return *t.Mode -} - -// GetPath returns the Path field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetPath() string { - if t == nil || t.Path == nil { - return "" - } - return *t.Path -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSHA() string { - if t == nil || t.SHA == nil { - return "" - } - return *t.SHA -} - -// GetSize returns the Size field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetSize() int { - if t == nil || t.Size == nil { - return 0 - } - return *t.Size -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetType() string { - if t == nil || t.Type == nil { - return "" - } - return *t.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (t *TreeEntry) GetURL() string { - if t == nil || t.URL == nil { - return "" - } - return *t.URL -} - -// GetForce returns the Force field if it's non-nil, zero value otherwise. -func (u *updateRefRequest) GetForce() bool { - if u == nil || u.Force == nil { - return false - } - return *u.Force -} - -// GetSHA returns the SHA field if it's non-nil, zero value otherwise. -func (u *updateRefRequest) GetSHA() string { - if u == nil || u.SHA == nil { - return "" - } - return *u.SHA -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *User) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetBio returns the Bio field if it's non-nil, zero value otherwise. -func (u *User) GetBio() string { - if u == nil || u.Bio == nil { - return "" - } - return *u.Bio -} - -// GetBlog returns the Blog field if it's non-nil, zero value otherwise. -func (u *User) GetBlog() string { - if u == nil || u.Blog == nil { - return "" - } - return *u.Blog -} - -// GetCollaborators returns the Collaborators field if it's non-nil, zero value otherwise. -func (u *User) GetCollaborators() int { - if u == nil || u.Collaborators == nil { - return 0 - } - return *u.Collaborators -} - -// GetCompany returns the Company field if it's non-nil, zero value otherwise. -func (u *User) GetCompany() string { - if u == nil || u.Company == nil { - return "" - } - return *u.Company -} - -// GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetCreatedAt() Timestamp { - if u == nil || u.CreatedAt == nil { - return Timestamp{} - } - return *u.CreatedAt -} - -// GetDiskUsage returns the DiskUsage field if it's non-nil, zero value otherwise. -func (u *User) GetDiskUsage() int { - if u == nil || u.DiskUsage == nil { - return 0 - } - return *u.DiskUsage -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *User) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowers returns the Followers field if it's non-nil, zero value otherwise. -func (u *User) GetFollowers() int { - if u == nil || u.Followers == nil { - return 0 - } - return *u.Followers -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowing returns the Following field if it's non-nil, zero value otherwise. -func (u *User) GetFollowing() int { - if u == nil || u.Following == nil { - return 0 - } - return *u.Following -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *User) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *User) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *User) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetHireable returns the Hireable field if it's non-nil, zero value otherwise. -func (u *User) GetHireable() bool { - if u == nil || u.Hireable == nil { - return false - } - return *u.Hireable -} - -// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. -func (u *User) GetHTMLURL() string { - if u == nil || u.HTMLURL == nil { - return "" - } - return *u.HTMLURL -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *User) GetID() int { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLocation returns the Location field if it's non-nil, zero value otherwise. -func (u *User) GetLocation() string { - if u == nil || u.Location == nil { - return "" - } - return *u.Location -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *User) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (u *User) GetName() string { - if u == nil || u.Name == nil { - return "" - } - return *u.Name -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *User) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetOwnedPrivateRepos returns the OwnedPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetOwnedPrivateRepos() int { - if u == nil || u.OwnedPrivateRepos == nil { - return 0 - } - return *u.OwnedPrivateRepos -} - -// GetPermissions returns the Permissions field if it's non-nil, zero value otherwise. -func (u *User) GetPermissions() map[string]bool { - if u == nil || u.Permissions == nil { - return map[string]bool{} - } - return *u.Permissions -} - -// GetPrivateGists returns the PrivateGists field if it's non-nil, zero value otherwise. -func (u *User) GetPrivateGists() int { - if u == nil || u.PrivateGists == nil { - return 0 - } - return *u.PrivateGists -} - -// GetPublicGists returns the PublicGists field if it's non-nil, zero value otherwise. -func (u *User) GetPublicGists() int { - if u == nil || u.PublicGists == nil { - return 0 - } - return *u.PublicGists -} - -// GetPublicRepos returns the PublicRepos field if it's non-nil, zero value otherwise. -func (u *User) GetPublicRepos() int { - if u == nil || u.PublicRepos == nil { - return 0 - } - return *u.PublicRepos -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *User) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *User) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *User) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *User) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *User) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetSuspendedAt returns the SuspendedAt field if it's non-nil, zero value otherwise. -func (u *User) GetSuspendedAt() Timestamp { - if u == nil || u.SuspendedAt == nil { - return Timestamp{} - } - return *u.SuspendedAt -} - -// GetTotalPrivateRepos returns the TotalPrivateRepos field if it's non-nil, zero value otherwise. -func (u *User) GetTotalPrivateRepos() int { - if u == nil || u.TotalPrivateRepos == nil { - return 0 - } - return *u.TotalPrivateRepos -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *User) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. -func (u *User) GetUpdatedAt() Timestamp { - if u == nil || u.UpdatedAt == nil { - return Timestamp{} - } - return *u.UpdatedAt -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *User) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetEmail() string { - if u == nil || u.Email == nil { - return "" - } - return *u.Email -} - -// GetPrimary returns the Primary field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetPrimary() bool { - if u == nil || u.Primary == nil { - return false - } - return *u.Primary -} - -// GetVerified returns the Verified field if it's non-nil, zero value otherwise. -func (u *UserEmail) GetVerified() bool { - if u == nil || u.Verified == nil { - return false - } - return *u.Verified -} - -// GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetAvatarURL() string { - if u == nil || u.AvatarURL == nil { - return "" - } - return *u.AvatarURL -} - -// GetEventsURL returns the EventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetEventsURL() string { - if u == nil || u.EventsURL == nil { - return "" - } - return *u.EventsURL -} - -// GetFollowersURL returns the FollowersURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowersURL() string { - if u == nil || u.FollowersURL == nil { - return "" - } - return *u.FollowersURL -} - -// GetFollowingURL returns the FollowingURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetFollowingURL() string { - if u == nil || u.FollowingURL == nil { - return "" - } - return *u.FollowingURL -} - -// GetGistsURL returns the GistsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGistsURL() string { - if u == nil || u.GistsURL == nil { - return "" - } - return *u.GistsURL -} - -// GetGravatarID returns the GravatarID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetGravatarID() string { - if u == nil || u.GravatarID == nil { - return "" - } - return *u.GravatarID -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetID() int { - if u == nil || u.ID == nil { - return 0 - } - return *u.ID -} - -// GetLDAPDN returns the LDAPDN field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLDAPDN() string { - if u == nil || u.LDAPDN == nil { - return "" - } - return *u.LDAPDN -} - -// GetLogin returns the Login field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetLogin() string { - if u == nil || u.Login == nil { - return "" - } - return *u.Login -} - -// GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetOrganizationsURL() string { - if u == nil || u.OrganizationsURL == nil { - return "" - } - return *u.OrganizationsURL -} - -// GetReceivedEventsURL returns the ReceivedEventsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReceivedEventsURL() string { - if u == nil || u.ReceivedEventsURL == nil { - return "" - } - return *u.ReceivedEventsURL -} - -// GetReposURL returns the ReposURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetReposURL() string { - if u == nil || u.ReposURL == nil { - return "" - } - return *u.ReposURL -} - -// GetSiteAdmin returns the SiteAdmin field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSiteAdmin() bool { - if u == nil || u.SiteAdmin == nil { - return false - } - return *u.SiteAdmin -} - -// GetStarredURL returns the StarredURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetStarredURL() string { - if u == nil || u.StarredURL == nil { - return "" - } - return *u.StarredURL -} - -// GetSubscriptionsURL returns the SubscriptionsURL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetSubscriptionsURL() string { - if u == nil || u.SubscriptionsURL == nil { - return "" - } - return *u.SubscriptionsURL -} - -// GetType returns the Type field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetType() string { - if u == nil || u.Type == nil { - return "" - } - return *u.Type -} - -// GetURL returns the URL field if it's non-nil, zero value otherwise. -func (u *UserLDAPMapping) GetURL() string { - if u == nil || u.URL == nil { - return "" - } - return *u.URL -} - -// GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetIncompleteResults() bool { - if u == nil || u.IncompleteResults == nil { - return false - } - return *u.IncompleteResults -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (u *UsersSearchResult) GetTotal() int { - if u == nil || u.Total == nil { - return 0 - } - return *u.Total -} - -// GetAction returns the Action field if it's non-nil, zero value otherwise. -func (w *WatchEvent) GetAction() string { - if w == nil || w.Action == nil { - return "" - } - return *w.Action -} - -// GetEmail returns the Email field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetEmail() string { - if w == nil || w.Email == nil { - return "" - } - return *w.Email -} - -// GetName returns the Name field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetName() string { - if w == nil || w.Name == nil { - return "" - } - return *w.Name -} - -// GetUsername returns the Username field if it's non-nil, zero value otherwise. -func (w *WebHookAuthor) GetUsername() string { - if w == nil || w.Username == nil { - return "" - } - return *w.Username -} - -// GetDistinct returns the Distinct field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetDistinct() bool { - if w == nil || w.Distinct == nil { - return false - } - return *w.Distinct -} - -// GetID returns the ID field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetID() string { - if w == nil || w.ID == nil { - return "" - } - return *w.ID -} - -// GetMessage returns the Message field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetMessage() string { - if w == nil || w.Message == nil { - return "" - } - return *w.Message -} - -// GetTimestamp returns the Timestamp field if it's non-nil, zero value otherwise. -func (w *WebHookCommit) GetTimestamp() time.Time { - if w == nil || w.Timestamp == nil { - return time.Time{} - } - return *w.Timestamp -} - -// GetAfter returns the After field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetAfter() string { - if w == nil || w.After == nil { - return "" - } - return *w.After -} - -// GetBefore returns the Before field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetBefore() string { - if w == nil || w.Before == nil { - return "" - } - return *w.Before -} - -// GetCompare returns the Compare field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCompare() string { - if w == nil || w.Compare == nil { - return "" - } - return *w.Compare -} - -// GetCreated returns the Created field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetCreated() bool { - if w == nil || w.Created == nil { - return false - } - return *w.Created -} - -// GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetDeleted() bool { - if w == nil || w.Deleted == nil { - return false - } - return *w.Deleted -} - -// GetForced returns the Forced field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetForced() bool { - if w == nil || w.Forced == nil { - return false - } - return *w.Forced -} - -// GetRef returns the Ref field if it's non-nil, zero value otherwise. -func (w *WebHookPayload) GetRef() string { - if w == nil || w.Ref == nil { - return "" - } - return *w.Ref -} - -// GetTotal returns the Total field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetTotal() int { - if w == nil || w.Total == nil { - return 0 - } - return *w.Total -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyCommitActivity) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} - -// GetAdditions returns the Additions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetAdditions() int { - if w == nil || w.Additions == nil { - return 0 - } - return *w.Additions -} - -// GetCommits returns the Commits field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetCommits() int { - if w == nil || w.Commits == nil { - return 0 - } - return *w.Commits -} - -// GetDeletions returns the Deletions field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetDeletions() int { - if w == nil || w.Deletions == nil { - return 0 - } - return *w.Deletions -} - -// GetWeek returns the Week field if it's non-nil, zero value otherwise. -func (w *WeeklyStats) GetWeek() Timestamp { - if w == nil || w.Week == nil { - return Timestamp{} - } - return *w.Week -} diff --git a/vendor/github.com/google/go-github/github/github.go b/vendor/github.com/google/go-github/github/github.go deleted file mode 100644 index e86a0ebf00..0000000000 --- a/vendor/github.com/google/go-github/github/github.go +++ /dev/null @@ -1,918 +0,0 @@ -// Copyright 2013 The go-github 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 gen-accessors.go - -package github - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "sync" - "time" - - "github.com/google/go-querystring/query" -) - -const ( - libraryVersion = "8" - defaultBaseURL = "https://api.github.com/" - uploadBaseURL = "https://uploads.github.com/" - userAgent = "go-github/" + libraryVersion - - headerRateLimit = "X-RateLimit-Limit" - headerRateRemaining = "X-RateLimit-Remaining" - headerRateReset = "X-RateLimit-Reset" - headerOTP = "X-GitHub-OTP" - - mediaTypeV3 = "application/vnd.github.v3+json" - defaultMediaType = "application/octet-stream" - mediaTypeV3SHA = "application/vnd.github.v3.sha" - mediaTypeV3Diff = "application/vnd.github.v3.diff" - mediaTypeV3Patch = "application/vnd.github.v3.patch" - mediaTypeOrgPermissionRepo = "application/vnd.github.v3.repository+json" - - // Media Type values to access preview APIs - - // https://developer.github.com/changes/2015-03-09-licenses-api/ - mediaTypeLicensesPreview = "application/vnd.github.drax-preview+json" - - // https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/ - mediaTypeStarringPreview = "application/vnd.github.v3.star+json" - - // https://developer.github.com/changes/2015-11-11-protected-branches-api/ - mediaTypeProtectedBranchesPreview = "application/vnd.github.loki-preview+json" - - // https://help.github.com/enterprise/2.4/admin/guides/migrations/exporting-the-github-com-organization-s-repositories/ - mediaTypeMigrationsPreview = "application/vnd.github.wyandotte-preview+json" - - // https://developer.github.com/changes/2016-04-06-deployment-and-deployment-status-enhancements/ - mediaTypeDeploymentStatusPreview = "application/vnd.github.ant-man-preview+json" - - // https://developer.github.com/changes/2016-02-19-source-import-preview-api/ - mediaTypeImportPreview = "application/vnd.github.barred-rock-preview" - - // https://developer.github.com/changes/2016-05-12-reactions-api-preview/ - mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview" - - // https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ - mediaTypeGitSigningPreview = "application/vnd.github.cryptographer-preview+json" - - // https://developer.github.com/changes/2016-05-23-timeline-preview-api/ - mediaTypeTimelinePreview = "application/vnd.github.mockingbird-preview+json" - - // https://developer.github.com/changes/2016-06-14-repository-invitations/ - mediaTypeRepositoryInvitationsPreview = "application/vnd.github.swamp-thing-preview+json" - - // https://developer.github.com/changes/2016-07-06-github-pages-preiew-api/ - mediaTypePagesPreview = "application/vnd.github.mister-fantastic-preview+json" - - // https://developer.github.com/changes/2016-09-14-projects-api/ - mediaTypeProjectsPreview = "application/vnd.github.inertia-preview+json" - - // https://developer.github.com/changes/2016-09-14-Integrations-Early-Access/ - mediaTypeIntegrationPreview = "application/vnd.github.machine-man-preview+json" - - // https://developer.github.com/changes/2017-01-05-commit-search-api/ - mediaTypeCommitSearchPreview = "application/vnd.github.cloak-preview+json" - - // https://developer.github.com/changes/2017-02-28-user-blocking-apis-and-webhook/ - mediaTypeBlockUsersPreview = "application/vnd.github.giant-sentry-fist-preview+json" - - // https://developer.github.com/changes/2017-02-09-community-health/ - mediaTypeRepositoryCommunityHealthMetricsPreview = "application/vnd.github.black-panther-preview+json" - - // https://developer.github.com/changes/2017-05-23-coc-api/ - mediaTypeCodesOfConductPreview = "application/vnd.github.scarlet-witch-preview+json" - - // https://developer.github.com/changes/2017-07-17-update-topics-on-repositories/ - mediaTypeTopicsPreview = "application/vnd.github.mercy-preview+json" -) - -// A Client manages communication with the GitHub API. -type Client struct { - clientMu sync.Mutex // clientMu protects the client during calls that modify the CheckRedirect func. - client *http.Client // HTTP client used to communicate with the API. - - // Base URL for API requests. Defaults to the public GitHub API, but can be - // set to a domain endpoint to use with GitHub Enterprise. BaseURL should - // always be specified with a trailing slash. - BaseURL *url.URL - - // Base URL for uploading files. - UploadURL *url.URL - - // User agent used when communicating with the GitHub API. - UserAgent string - - rateMu sync.Mutex - rateLimits [categories]Rate // Rate limits for the client as determined by the most recent API calls. - - common service // Reuse a single struct instead of allocating one for each service on the heap. - - // Services used for talking to different parts of the GitHub API. - Activity *ActivityService - Admin *AdminService - Apps *AppsService - Authorizations *AuthorizationsService - Gists *GistsService - Git *GitService - Gitignores *GitignoresService - Issues *IssuesService - Organizations *OrganizationsService - Projects *ProjectsService - PullRequests *PullRequestsService - Repositories *RepositoriesService - Search *SearchService - Users *UsersService - Licenses *LicensesService - Migrations *MigrationService - Reactions *ReactionsService -} - -type service struct { - client *Client -} - -// ListOptions specifies the optional parameters to various List methods that -// support pagination. -type ListOptions struct { - // For paginated result sets, page of results to retrieve. - Page int `url:"page,omitempty"` - - // For paginated result sets, the number of results to include per page. - PerPage int `url:"per_page,omitempty"` -} - -// UploadOptions specifies the parameters to methods that support uploads. -type UploadOptions struct { - Name string `url:"name,omitempty"` -} - -// RawType represents type of raw format of a request instead of JSON. -type RawType uint8 - -const ( - // Diff format. - Diff RawType = 1 + iota - // Patch format. - Patch -) - -// RawOptions specifies parameters when user wants to get raw format of -// a response instead of JSON. -type RawOptions struct { - Type RawType -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) - if v.Kind() == reflect.Ptr && v.IsNil() { - return s, nil - } - - u, err := url.Parse(s) - if err != nil { - return s, err - } - - qs, err := query.Values(opt) - if err != nil { - return s, err - } - - u.RawQuery = qs.Encode() - return u.String(), nil -} - -// NewClient returns a new GitHub API client. If a nil httpClient is -// provided, http.DefaultClient will be used. To use API methods which require -// authentication, provide an http.Client that will perform the authentication -// for you (such as that provided by the golang.org/x/oauth2 library). -func NewClient(httpClient *http.Client) *Client { - if httpClient == nil { - httpClient = http.DefaultClient - } - baseURL, _ := url.Parse(defaultBaseURL) - uploadURL, _ := url.Parse(uploadBaseURL) - - c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent, UploadURL: uploadURL} - c.common.client = c - c.Activity = (*ActivityService)(&c.common) - c.Admin = (*AdminService)(&c.common) - c.Apps = (*AppsService)(&c.common) - c.Authorizations = (*AuthorizationsService)(&c.common) - c.Gists = (*GistsService)(&c.common) - c.Git = (*GitService)(&c.common) - c.Gitignores = (*GitignoresService)(&c.common) - c.Issues = (*IssuesService)(&c.common) - c.Licenses = (*LicensesService)(&c.common) - c.Migrations = (*MigrationService)(&c.common) - c.Organizations = (*OrganizationsService)(&c.common) - c.Projects = (*ProjectsService)(&c.common) - c.PullRequests = (*PullRequestsService)(&c.common) - c.Reactions = (*ReactionsService)(&c.common) - c.Repositories = (*RepositoriesService)(&c.common) - c.Search = (*SearchService)(&c.common) - c.Users = (*UsersService)(&c.common) - return c -} - -// NewRequest creates an API request. A relative URL can be provided in urlStr, -// in which case it is resolved relative to the BaseURL of the Client. -// Relative URLs should always be specified without a preceding slash. If -// specified, the value pointed to by body is JSON encoded and included as the -// request body. -func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { - rel, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - u := c.BaseURL.ResolveReference(rel) - - var buf io.ReadWriter - if body != nil { - buf = new(bytes.Buffer) - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, u.String(), buf) - if err != nil { - return nil, err - } - - if body != nil { - req.Header.Set("Content-Type", "application/json") - } - req.Header.Set("Accept", mediaTypeV3) - if c.UserAgent != "" { - req.Header.Set("User-Agent", c.UserAgent) - } - return req, nil -} - -// NewUploadRequest creates an upload request. A relative URL can be provided in -// urlStr, in which case it is resolved relative to the UploadURL of the Client. -// Relative URLs should always be specified without a preceding slash. -func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error) { - rel, err := url.Parse(urlStr) - if err != nil { - return nil, err - } - - u := c.UploadURL.ResolveReference(rel) - req, err := http.NewRequest("POST", u.String(), reader) - if err != nil { - return nil, err - } - req.ContentLength = size - - if mediaType == "" { - mediaType = defaultMediaType - } - req.Header.Set("Content-Type", mediaType) - req.Header.Set("Accept", mediaTypeV3) - req.Header.Set("User-Agent", c.UserAgent) - return req, nil -} - -// Response is a GitHub API response. This wraps the standard http.Response -// returned from GitHub and provides convenient access to things like -// pagination links. -type Response struct { - *http.Response - - // These fields provide the page values for paginating through a set of - // results. Any or all of these may be set to the zero value for - // responses that are not part of a paginated set, or for which there - // are no additional pages. - - NextPage int - PrevPage int - FirstPage int - LastPage int - - Rate -} - -// newResponse creates a new Response for the provided http.Response. -// r must not be nil. -func newResponse(r *http.Response) *Response { - response := &Response{Response: r} - response.populatePageValues() - response.Rate = parseRate(r) - return response -} - -// populatePageValues parses the HTTP Link response headers and populates the -// various pagination link values in the Response. -func (r *Response) populatePageValues() { - if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 { - for _, link := range strings.Split(links[0], ",") { - segments := strings.Split(strings.TrimSpace(link), ";") - - // link must at least have href and rel - if len(segments) < 2 { - continue - } - - // ensure href is properly formatted - if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") { - continue - } - - // try to pull out page parameter - url, err := url.Parse(segments[0][1 : len(segments[0])-1]) - if err != nil { - continue - } - page := url.Query().Get("page") - if page == "" { - continue - } - - for _, segment := range segments[1:] { - switch strings.TrimSpace(segment) { - case `rel="next"`: - r.NextPage, _ = strconv.Atoi(page) - case `rel="prev"`: - r.PrevPage, _ = strconv.Atoi(page) - case `rel="first"`: - r.FirstPage, _ = strconv.Atoi(page) - case `rel="last"`: - r.LastPage, _ = strconv.Atoi(page) - } - - } - } - } -} - -// parseRate parses the rate related headers. -func parseRate(r *http.Response) Rate { - var rate Rate - if limit := r.Header.Get(headerRateLimit); limit != "" { - rate.Limit, _ = strconv.Atoi(limit) - } - if remaining := r.Header.Get(headerRateRemaining); remaining != "" { - rate.Remaining, _ = strconv.Atoi(remaining) - } - if reset := r.Header.Get(headerRateReset); reset != "" { - if v, _ := strconv.ParseInt(reset, 10, 64); v != 0 { - rate.Reset = Timestamp{time.Unix(v, 0)} - } - } - return rate -} - -// Do sends an API request and returns the API response. The API response is -// JSON decoded and stored in the value pointed to by v, or returned as an -// error if an API error has occurred. If v implements the io.Writer -// interface, the raw response body will be written to v, without attempting to -// first decode it. If rate limit is exceeded and reset time is in the future, -// Do returns *RateLimitError immediately without making a network API call. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) { - ctx, req = withContext(ctx, req) - - rateLimitCategory := category(req.URL.Path) - - // If we've hit rate limit, don't make further requests before Reset time. - if err := c.checkRateLimitBeforeDo(req, rateLimitCategory); err != nil { - return &Response{ - Response: err.Response, - Rate: err.Rate, - }, err - } - - resp, err := c.client.Do(req) - if err != nil { - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - select { - case <-ctx.Done(): - return nil, ctx.Err() - default: - } - - // If the error type is *url.Error, sanitize its URL before returning. - if e, ok := err.(*url.Error); ok { - if url, err := url.Parse(e.URL); err == nil { - e.URL = sanitizeURL(url).String() - return nil, e - } - } - - return nil, err - } - - defer func() { - // Drain up to 512 bytes and close the body to let the Transport reuse the connection - io.CopyN(ioutil.Discard, resp.Body, 512) - resp.Body.Close() - }() - - response := newResponse(resp) - - c.rateMu.Lock() - c.rateLimits[rateLimitCategory] = response.Rate - c.rateMu.Unlock() - - err = CheckResponse(resp) - if err != nil { - // even though there was an error, we still return the response - // in case the caller wants to inspect it further - return response, err - } - - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(v) - if err == io.EOF { - err = nil // ignore EOF errors caused by empty response body - } - } - } - - return response, err -} - -// checkRateLimitBeforeDo does not make any network calls, but uses existing knowledge from -// current client state in order to quickly check if *RateLimitError can be immediately returned -// from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. -// Otherwise it returns nil, and Client.Do should proceed normally. -func (c *Client) checkRateLimitBeforeDo(req *http.Request, rateLimitCategory rateLimitCategory) *RateLimitError { - c.rateMu.Lock() - rate := c.rateLimits[rateLimitCategory] - c.rateMu.Unlock() - if !rate.Reset.Time.IsZero() && rate.Remaining == 0 && time.Now().Before(rate.Reset.Time) { - // Create a fake response. - resp := &http.Response{ - Status: http.StatusText(http.StatusForbidden), - StatusCode: http.StatusForbidden, - Request: req, - Header: make(http.Header), - Body: ioutil.NopCloser(strings.NewReader("")), - } - return &RateLimitError{ - Rate: rate, - Response: resp, - Message: fmt.Sprintf("API rate limit of %v still exceeded until %v, not making remote request.", rate.Limit, rate.Reset.Time), - } - } - - return nil -} - -/* -An ErrorResponse reports one or more errors caused by an API request. - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type ErrorResponse struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - Errors []Error `json:"errors"` // more detail on individual errors - // Block is only populated on certain types of errors such as code 451. - // See https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/ - // for more information. - Block *struct { - Reason string `json:"reason,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - } `json:"block,omitempty"` - // Most errors will also include a documentation_url field pointing - // to some content that might help you resolve the error, see - // https://developer.github.com/v3/#client-errors - DocumentationURL string `json:"documentation_url,omitempty"` -} - -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v %+v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, r.Errors) -} - -// TwoFactorAuthError occurs when using HTTP Basic Authentication for a user -// that has two-factor authentication enabled. The request can be reattempted -// by providing a one-time password in the request. -type TwoFactorAuthError ErrorResponse - -func (r *TwoFactorAuthError) Error() string { return (*ErrorResponse)(r).Error() } - -// RateLimitError occurs when GitHub returns 403 Forbidden response with a rate limit -// remaining value of 0, and error message starts with "API rate limit exceeded for ". -type RateLimitError struct { - Rate Rate // Rate specifies last known rate limit for the client - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message -} - -func (r *RateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, formatRateReset(r.Rate.Reset.Time.Sub(time.Now()))) -} - -// AcceptedError occurs when GitHub returns 202 Accepted response with an -// empty body, which means a job was scheduled on the GitHub side to process -// the information needed and cache it. -// Technically, 202 Accepted is not a real error, it's just used to -// indicate that results are not ready yet, but should be available soon. -// The request can be repeated after some time. -type AcceptedError struct{} - -func (*AcceptedError) Error() string { - return "job scheduled on GitHub side; try again later" -} - -// AbuseRateLimitError occurs when GitHub returns 403 Forbidden response with the -// "documentation_url" field value equal to "https://developer.github.com/v3#abuse-rate-limits". -type AbuseRateLimitError struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // error message - - // RetryAfter is provided with some abuse rate limit errors. If present, - // it is the amount of time that the client should wait before retrying. - // Otherwise, the client should try again later (after an unspecified amount of time). - RetryAfter *time.Duration -} - -func (r *AbuseRateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message) -} - -// sanitizeURL redacts the client_secret parameter from the URL which may be -// exposed to the user. -func sanitizeURL(uri *url.URL) *url.URL { - if uri == nil { - return nil - } - params := uri.Query() - if len(params.Get("client_secret")) > 0 { - params.Set("client_secret", "REDACTED") - uri.RawQuery = params.Encode() - } - return uri -} - -/* -An Error reports more details on an individual error in an ErrorResponse. -These are the possible validation error codes: - - missing: - resource does not exist - missing_field: - a required field on a resource has not been set - invalid: - the formatting of a field is invalid - already_exists: - another resource has the same valid as this field - custom: - some resources return this (e.g. github.User.CreateKey()), additional - information is set in the Message field of the Error - -GitHub API docs: https://developer.github.com/v3/#client-errors -*/ -type Error struct { - Resource string `json:"resource"` // resource on which the error occurred - Field string `json:"field"` // field on which the error occurred - Code string `json:"code"` // validation error code - Message string `json:"message"` // Message describing the error. Errors with Code == "custom" will always have this set. -} - -func (e *Error) Error() string { - return fmt.Sprintf("%v error caused by %v field on %v resource", - e.Code, e.Field, e.Resource) -} - -// CheckResponse checks the API response for errors, and returns them if -// present. A response is considered an error if it has a status code outside -// the 200 range or equal to 202 Accepted. -// API error responses are expected to have either no response -// body, or a JSON response body that maps to ErrorResponse. Any other -// response body will be silently ignored. -// -// The error type will be *RateLimitError for rate limit exceeded errors, -// *AcceptedError for 202 Accepted status codes, -// and *TwoFactorAuthError for two-factor authentication errors. -func CheckResponse(r *http.Response) error { - if r.StatusCode == http.StatusAccepted { - return &AcceptedError{} - } - if c := r.StatusCode; 200 <= c && c <= 299 { - return nil - } - errorResponse := &ErrorResponse{Response: r} - data, err := ioutil.ReadAll(r.Body) - if err == nil && data != nil { - json.Unmarshal(data, errorResponse) - } - switch { - case r.StatusCode == http.StatusUnauthorized && strings.HasPrefix(r.Header.Get(headerOTP), "required"): - return (*TwoFactorAuthError)(errorResponse) - case r.StatusCode == http.StatusForbidden && r.Header.Get(headerRateRemaining) == "0" && strings.HasPrefix(errorResponse.Message, "API rate limit exceeded for "): - return &RateLimitError{ - Rate: parseRate(r), - Response: errorResponse.Response, - Message: errorResponse.Message, - } - case r.StatusCode == http.StatusForbidden && errorResponse.DocumentationURL == "https://developer.github.com/v3#abuse-rate-limits": - abuseRateLimitError := &AbuseRateLimitError{ - Response: errorResponse.Response, - Message: errorResponse.Message, - } - if v := r.Header["Retry-After"]; len(v) > 0 { - // According to GitHub support, the "Retry-After" header value will be - // an integer which represents the number of seconds that one should - // wait before resuming making requests. - retryAfterSeconds, _ := strconv.ParseInt(v[0], 10, 64) // Error handling is noop. - retryAfter := time.Duration(retryAfterSeconds) * time.Second - abuseRateLimitError.RetryAfter = &retryAfter - } - return abuseRateLimitError - default: - return errorResponse - } -} - -// parseBoolResponse determines the boolean result from a GitHub API response. -// Several GitHub API methods return boolean responses indicated by the HTTP -// status code in the response (true indicated by a 204, false indicated by a -// 404). This helper function will determine that result and hide the 404 -// error if present. Any other error will be returned through as-is. -func parseBoolResponse(err error) (bool, error) { - if err == nil { - return true, nil - } - - if err, ok := err.(*ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { - // Simply false. In this one case, we do not pass the error through. - return false, nil - } - - // some other real error occurred - return false, err -} - -// Rate represents the rate limit for the current client. -type Rate struct { - // The number of requests per hour the client is currently limited to. - Limit int `json:"limit"` - - // The number of remaining requests the client can make this hour. - Remaining int `json:"remaining"` - - // The time at which the current rate limit will reset. - Reset Timestamp `json:"reset"` -} - -func (r Rate) String() string { - return Stringify(r) -} - -// RateLimits represents the rate limits for the current client. -type RateLimits struct { - // The rate limit for non-search API requests. Unauthenticated - // requests are limited to 60 per hour. Authenticated requests are - // limited to 5,000 per hour. - // - // GitHub API docs: https://developer.github.com/v3/#rate-limiting - Core *Rate `json:"core"` - - // The rate limit for search API requests. Unauthenticated requests - // are limited to 10 requests per minutes. Authenticated requests are - // limited to 30 per minute. - // - // GitHub API docs: https://developer.github.com/v3/search/#rate-limit - Search *Rate `json:"search"` -} - -func (r RateLimits) String() string { - return Stringify(r) -} - -type rateLimitCategory uint8 - -const ( - coreCategory rateLimitCategory = iota - searchCategory - - categories // An array of this length will be able to contain all rate limit categories. -) - -// category returns the rate limit category of the endpoint, determined by Request.URL.Path. -func category(path string) rateLimitCategory { - switch { - default: - return coreCategory - case strings.HasPrefix(path, "/search/"): - return searchCategory - } -} - -// RateLimits returns the rate limits for the current client. -func (c *Client) RateLimits(ctx context.Context) (*RateLimits, *Response, error) { - req, err := c.NewRequest("GET", "rate_limit", nil) - if err != nil { - return nil, nil, err - } - - response := new(struct { - Resources *RateLimits `json:"resources"` - }) - resp, err := c.Do(ctx, req, response) - if err != nil { - return nil, nil, err - } - - if response.Resources != nil { - c.rateMu.Lock() - if response.Resources.Core != nil { - c.rateLimits[coreCategory] = *response.Resources.Core - } - if response.Resources.Search != nil { - c.rateLimits[searchCategory] = *response.Resources.Search - } - c.rateMu.Unlock() - } - - return response.Resources, resp, nil -} - -/* -UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls -that need to use a higher rate limit associated with your OAuth application. - - t := &github.UnauthenticatedRateLimitedTransport{ - ClientID: "your app's client ID", - ClientSecret: "your app's client secret", - } - client := github.NewClient(t.Client()) - -This will append the querystring params client_id=xxx&client_secret=yyy to all -requests. - -See https://developer.github.com/v3/#unauthenticated-rate-limited-requests for -more information. -*/ -type UnauthenticatedRateLimitedTransport struct { - // ClientID is the GitHub OAuth client ID of the current application, which - // can be found by selecting its entry in the list at - // https://github.com/settings/applications. - ClientID string - - // ClientSecret is the GitHub OAuth client secret of the current - // application. - ClientSecret string - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if t.ClientID == "" { - return nil, errors.New("t.ClientID is empty") - } - if t.ClientSecret == "" { - return nil, errors.New("t.ClientSecret is empty") - } - - // To set extra querystring params, we must make a copy of the Request so - // that we don't modify the Request we were given. This is required by the - // specification of http.RoundTripper. - req = cloneRequest(req) - q := req.URL.Query() - q.Set("client_id", t.ClientID) - q.Set("client_secret", t.ClientSecret) - req.URL.RawQuery = q.Encode() - - // Make the HTTP request. - return t.transport().RoundTrip(req) -} - -// Client returns an *http.Client that makes requests which are subject to the -// rate limit of your OAuth application. -func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *UnauthenticatedRateLimitedTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// BasicAuthTransport is an http.RoundTripper that authenticates all requests -// using HTTP Basic Authentication with the provided username and password. It -// additionally supports users who have two-factor authentication enabled on -// their GitHub account. -type BasicAuthTransport struct { - Username string // GitHub username - Password string // GitHub password - OTP string // one-time password for users with two-factor auth enabled - - // Transport is the underlying HTTP transport to use when making requests. - // It will default to http.DefaultTransport if nil. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. -func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - req = cloneRequest(req) // per RoundTrip contract - req.SetBasicAuth(t.Username, t.Password) - if t.OTP != "" { - req.Header.Set(headerOTP, t.OTP) - } - return t.transport().RoundTrip(req) -} - -// Client returns an *http.Client that makes requests that are authenticated -// using HTTP Basic Authentication. -func (t *BasicAuthTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *BasicAuthTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// cloneRequest returns a clone of the provided *http.Request. The clone is a -// shallow copy of the struct and its Header map. -func cloneRequest(r *http.Request) *http.Request { - // shallow copy of the struct - r2 := new(http.Request) - *r2 = *r - // deep copy of the Header - r2.Header = make(http.Header, len(r.Header)) - for k, s := range r.Header { - r2.Header[k] = append([]string(nil), s...) - } - return r2 -} - -// formatRateReset formats d to look like "[rate reset in 2s]" or -// "[rate reset in 87m02s]" for the positive durations. And like "[rate limit was reset 87m02s ago]" -// for the negative cases. -func formatRateReset(d time.Duration) string { - isNegative := d < 0 - if isNegative { - d *= -1 - } - secondsTotal := int(0.5 + d.Seconds()) - minutes := secondsTotal / 60 - seconds := secondsTotal - minutes*60 - - var timeString string - if minutes > 0 { - timeString = fmt.Sprintf("%dm%02ds", minutes, seconds) - } else { - timeString = fmt.Sprintf("%ds", seconds) - } - - if isNegative { - return fmt.Sprintf("[rate limit was reset %v ago]", timeString) - } - return fmt.Sprintf("[rate reset in %v]", timeString) -} - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int is a helper routine that allocates a new int value -// to store v and returns a pointer to it. -func Int(v int) *int { return &v } - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/vendor/github.com/google/go-github/github/gitignore.go b/vendor/github.com/google/go-github/github/gitignore.go deleted file mode 100644 index 2f691bc323..0000000000 --- a/vendor/github.com/google/go-github/github/gitignore.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// GitignoresService provides access to the gitignore related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/ -type GitignoresService service - -// Gitignore represents a .gitignore file as returned by the GitHub API. -type Gitignore struct { - Name *string `json:"name,omitempty"` - Source *string `json:"source,omitempty"` -} - -func (g Gitignore) String() string { - return Stringify(g) -} - -// List all available Gitignore templates. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#listing-available-templates -func (s GitignoresService) List(ctx context.Context) ([]string, *Response, error) { - req, err := s.client.NewRequest("GET", "gitignore/templates", nil) - if err != nil { - return nil, nil, err - } - - var availableTemplates []string - resp, err := s.client.Do(ctx, req, &availableTemplates) - if err != nil { - return nil, resp, err - } - - return availableTemplates, resp, nil -} - -// Get a Gitignore by name. -// -// GitHub API docs: https://developer.github.com/v3/gitignore/#get-a-single-template -func (s GitignoresService) Get(ctx context.Context, name string) (*Gitignore, *Response, error) { - u := fmt.Sprintf("gitignore/templates/%v", name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - gitignore := new(Gitignore) - resp, err := s.client.Do(ctx, req, gitignore) - if err != nil { - return nil, resp, err - } - - return gitignore, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues.go b/vendor/github.com/google/go-github/github/issues.go deleted file mode 100644 index b437d5063a..0000000000 --- a/vendor/github.com/google/go-github/github/issues.go +++ /dev/null @@ -1,307 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// IssuesService handles communication with the issue related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/issues/ -type IssuesService service - -// Issue represents a GitHub issue on a repository. -// -// Note: As far as the GitHub API is concerned, every pull request is an issue, -// but not every issue is a pull request. Some endpoints, events, and webhooks -// may also return pull requests via this struct. If PullRequestLinks is nil, -// this is an issue, and if PullRequestLinks is not nil, this is a pull request. -type Issue struct { - ID *int `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Locked *bool `json:"locked,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Labels []Label `json:"labels,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Comments *int `json:"comments,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedBy *User `json:"closed_by,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"` - Repository *Repository `json:"repository,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (i Issue) String() string { - return Stringify(i) -} - -// IssueRequest represents a request to create/edit an issue. -// It is separate from Issue above because otherwise Labels -// and Assignee fail to serialize to the correct JSON. -type IssueRequest struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - Labels *[]string `json:"labels,omitempty"` - Assignee *string `json:"assignee,omitempty"` - State *string `json:"state,omitempty"` - Milestone *int `json:"milestone,omitempty"` - Assignees *[]string `json:"assignees,omitempty"` -} - -// IssueListOptions specifies the optional parameters to the IssuesService.List -// and IssuesService.ListByOrg methods. -type IssueListOptions struct { - // Filter specifies which issues to list. Possible values are: assigned, - // created, mentioned, subscribed, all. Default is "assigned". - Filter string `url:"filter,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,comma,omitempty"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// PullRequestLinks object is added to the Issue object when it's an issue included -// in the IssueCommentEvent webhook payload, if the webhooks is fired by a comment on a PR -type PullRequestLinks struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` -} - -// List the issues for the authenticated user. If all is true, list issues -// across all the user's visible repositories including owned, member, and -// organization repositories; if false, list only owned and member -// repositories. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) List(ctx context.Context, all bool, opt *IssueListOptions) ([]*Issue, *Response, error) { - var u string - if all { - u = "issues" - } else { - u = "user/issues" - } - return s.listIssues(ctx, u, opt) -} - -// ListByOrg fetches the issues in the specified organization for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) ListByOrg(ctx context.Context, org string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("orgs/%v/issues", org) - return s.listIssues(ctx, u, opt) -} - -func (s *IssuesService) listIssues(ctx context.Context, u string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// IssueListByRepoOptions specifies the optional parameters to the -// IssuesService.ListByRepo method. -type IssueListByRepoOptions struct { - // Milestone limits issues for the specified milestone. Possible values are - // a milestone number, "none" for issues with no milestone, "*" for issues - // with any milestone. - Milestone string `url:"milestone,omitempty"` - - // State filters issues based on their state. Possible values are: open, - // closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Assignee filters issues based on their assignee. Possible values are a - // user name, "none" for issues that are not assigned, "*" for issues with - // any assigned user. - Assignee string `url:"assignee,omitempty"` - - // Creator filters issues based on their creator. - Creator string `url:"creator,omitempty"` - - // Mentioned filters issues to those mentioned a specific user. - Mentioned string `url:"mentioned,omitempty"` - - // Labels filters issues based on their label. - Labels []string `url:"labels,omitempty,comma"` - - // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort issues. Possible values are: asc, desc. - // Default is "desc". - Direction string `url:"direction,omitempty"` - - // Since filters issues by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListByRepo lists the issues for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#list-issues-for-a-repository -func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var issues []*Issue - resp, err := s.client.Do(ctx, req, &issues) - if err != nil { - return nil, resp, err - } - - return issues, resp, nil -} - -// Get a single issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#get-a-single-issue -func (s *IssuesService) Get(ctx context.Context, owner string, repo string, number int) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - issue := new(Issue) - resp, err := s.client.Do(ctx, req, issue) - if err != nil { - return nil, resp, err - } - - return issue, resp, nil -} - -// Create a new issue on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/#create-an-issue -func (s *IssuesService) Create(ctx context.Context, owner string, repo string, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - req, err := s.client.NewRequest("POST", u, issue) - if err != nil { - return nil, nil, err - } - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// Edit an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/#edit-an-issue -func (s *IssuesService) Edit(ctx context.Context, owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, issue) - if err != nil { - return nil, nil, err - } - - i := new(Issue) - resp, err := s.client.Do(ctx, req, i) - if err != nil { - return nil, resp, err - } - - return i, resp, nil -} - -// Lock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue -func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unlock an issue's conversation. -// -// GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue -func (s *IssuesService) Unlock(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_assignees.go b/vendor/github.com/google/go-github/github/issues_assignees.go deleted file mode 100644 index 9cb366f50a..0000000000 --- a/vendor/github.com/google/go-github/github/issues_assignees.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListAssignees fetches all available assignees (owners and collaborators) to -// which issues may be assigned. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#list-assignees -func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var assignees []*User - resp, err := s.client.Do(ctx, req, &assignees) - if err != nil { - return nil, resp, err - } - - return assignees, resp, nil -} - -// IsAssignee checks if a user is an assignee for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#check-assignee -func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/assignees/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - resp, err := s.client.Do(ctx, req, nil) - assignee, err := parseBoolResponse(err) - return assignee, resp, err -} - -// AddAssignees adds the provided GitHub users as assignees to the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue -func (s *IssuesService) AddAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("POST", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} - -// RemoveAssignees removes the provided GitHub users as assignees from the issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue -func (s *IssuesService) RemoveAssignees(ctx context.Context, owner, repo string, number int, assignees []string) (*Issue, *Response, error) { - users := &struct { - Assignees []string `json:"assignees,omitempty"` - }{Assignees: assignees} - u := fmt.Sprintf("repos/%v/%v/issues/%v/assignees", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, users) - if err != nil { - return nil, nil, err - } - - issue := &Issue{} - resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err -} diff --git a/vendor/github.com/google/go-github/github/issues_comments.go b/vendor/github.com/google/go-github/github/issues_comments.go deleted file mode 100644 index fd72657cd4..0000000000 --- a/vendor/github.com/google/go-github/github/issues_comments.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// IssueComment represents a comment left on an issue. -type IssueComment struct { - ID *int `json:"id,omitempty"` - Body *string `json:"body,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` -} - -func (i IssueComment) String() string { - return Stringify(i) -} - -// IssueListCommentsOptions specifies the optional parameters to the -// IssuesService.ListComments method. -type IssueListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified issue. Specifying an issue -// number of 0 will return all comments on all issues for the repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue -func (s *IssuesService) ListComments(ctx context.Context, owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/issues/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*IssueComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#get-a-single-comment -func (s *IssuesService) GetComment(ctx context.Context, owner string, repo string, id int) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(IssueComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#create-a-comment -func (s *IssuesService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#edit-a-comment -func (s *IssuesService) EditComment(ctx context.Context, owner string, repo string, id int, comment *IssueComment) (*IssueComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - c := new(IssueComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/issues/comments/#delete-a-comment -func (s *IssuesService) DeleteComment(ctx context.Context, owner string, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_events.go b/vendor/github.com/google/go-github/github/issues_events.go deleted file mode 100644 index 93e5d66fb4..0000000000 --- a/vendor/github.com/google/go-github/github/issues_events.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// IssueEvent represents an event that occurred around an Issue or Pull Request. -type IssueEvent struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // The User that generated this event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible - // values are: - // - // closed - // The Actor closed the issue. - // If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit. - // - // merged - // The Actor merged into master a branch containing a commit mentioning the issue. - // CommitID holds the SHA1 of the merge commit. - // - // referenced - // The Actor committed to master a commit mentioning the issue in its commit message. - // CommitID holds the SHA1 of the commit. - // - // reopened, locked, unlocked - // The Actor did that to the issue. - // - // renamed - // The Actor changed the issue title from Rename.From to Rename.To. - // - // mentioned - // Someone unspecified @mentioned the Actor [sic] in an issue comment body. - // - // assigned, unassigned - // The Assigner assigned the issue to or removed the assignment from the Assignee. - // - // labeled, unlabeled - // The Actor added or removed the Label from the issue. - // - // milestoned, demilestoned - // The Actor added or removed the issue from the Milestone. - // - // subscribed, unsubscribed - // The Actor subscribed to or unsubscribed from notifications for an issue. - // - // head_ref_deleted, head_ref_restored - // The pull request’s branch was deleted or restored. - // - Event *string `json:"event,omitempty"` - - CreatedAt *time.Time `json:"created_at,omitempty"` - Issue *Issue `json:"issue,omitempty"` - - // Only present on certain events; see above. - Assignee *User `json:"assignee,omitempty"` - Assigner *User `json:"assigner,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - Label *Label `json:"label,omitempty"` - Rename *Rename `json:"rename,omitempty"` -} - -// ListIssueEvents lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue -func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/events", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// ListRepositoryEvents lists events for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository -func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var events []*IssueEvent - resp, err := s.client.Do(ctx, req, &events) - if err != nil { - return nil, resp, err - } - - return events, resp, nil -} - -// GetEvent returns the specified issue event. -// -// GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event -func (s *IssuesService) GetEvent(ctx context.Context, owner, repo string, id int) (*IssueEvent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/events/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - event := new(IssueEvent) - resp, err := s.client.Do(ctx, req, event) - if err != nil { - return nil, resp, err - } - - return event, resp, nil -} - -// Rename contains details for 'renamed' events. -type Rename struct { - From *string `json:"from,omitempty"` - To *string `json:"to,omitempty"` -} - -func (r Rename) String() string { - return Stringify(r) -} diff --git a/vendor/github.com/google/go-github/github/issues_labels.go b/vendor/github.com/google/go-github/github/issues_labels.go deleted file mode 100644 index b0e34c40f2..0000000000 --- a/vendor/github.com/google/go-github/github/issues_labels.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Label represents a GitHub label on an Issue -type Label struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Color *string `json:"color,omitempty"` -} - -func (l Label) String() string { - return Stringify(l) -} - -// ListLabels lists all labels for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository -func (s *IssuesService) ListLabels(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// GetLabel gets a single label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-a-single-label -func (s *IssuesService) GetLabel(ctx context.Context, owner string, repo string, name string) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - label := new(Label) - resp, err := s.client.Do(ctx, req, label) - if err != nil { - return nil, resp, err - } - - return label, resp, nil -} - -// CreateLabel creates a new label on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#create-a-label -func (s *IssuesService) CreateLabel(ctx context.Context, owner string, repo string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - req, err := s.client.NewRequest("POST", u, label) - if err != nil { - return nil, nil, err - } - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// EditLabel edits a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#update-a-label -func (s *IssuesService) EditLabel(ctx context.Context, owner string, repo string, name string, label *Label) (*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("PATCH", u, label) - if err != nil { - return nil, nil, err - } - - l := new(Label) - resp, err := s.client.Do(ctx, req, l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// DeleteLabel deletes a label. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#delete-a-label -func (s *IssuesService) DeleteLabel(ctx context.Context, owner string, repo string, name string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/labels/%v", owner, repo, name) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListLabelsByIssue lists all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#list-labels-on-an-issue -func (s *IssuesService) ListLabelsByIssue(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} - -// AddLabelsToIssue adds labels to an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#add-labels-to-an-issue -func (s *IssuesService) AddLabelsToIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("POST", u, labels) - if err != nil { - return nil, nil, err - } - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelForIssue removes a label for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue -func (s *IssuesService) RemoveLabelForIssue(ctx context.Context, owner string, repo string, number int, label string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels/%v", owner, repo, number, label) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ReplaceLabelsForIssue replaces all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#replace-all-labels-for-an-issue -func (s *IssuesService) ReplaceLabelsForIssue(ctx context.Context, owner string, repo string, number int, labels []string) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, labels) - if err != nil { - return nil, nil, err - } - - var l []*Label - resp, err := s.client.Do(ctx, req, &l) - if err != nil { - return nil, resp, err - } - - return l, resp, nil -} - -// RemoveLabelsForIssue removes all labels for an issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#remove-all-labels-from-an-issue -func (s *IssuesService) RemoveLabelsForIssue(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListLabelsForMilestone lists labels for every issue in a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone -func (s *IssuesService) ListLabelsForMilestone(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var labels []*Label - resp, err := s.client.Do(ctx, req, &labels) - if err != nil { - return nil, resp, err - } - - return labels, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/issues_milestones.go b/vendor/github.com/google/go-github/github/issues_milestones.go deleted file mode 100644 index e6e882d144..0000000000 --- a/vendor/github.com/google/go-github/github/issues_milestones.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// Milestone represents a GitHub repository milestone. -type Milestone struct { - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - ID *int `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - OpenIssues *int `json:"open_issues,omitempty"` - ClosedIssues *int `json:"closed_issues,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - DueOn *time.Time `json:"due_on,omitempty"` -} - -func (m Milestone) String() string { - return Stringify(m) -} - -// MilestoneListOptions specifies the optional parameters to the -// IssuesService.ListMilestones method. -type MilestoneListOptions struct { - // State filters milestones based on their state. Possible values are: - // open, closed, all. Default is "open". - State string `url:"state,omitempty"` - - // Sort specifies how to sort milestones. Possible values are: due_on, completeness. - // Default value is "due_on". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort milestones. Possible values are: asc, desc. - // Default is "asc". - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// ListMilestones lists all milestones for a repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository -func (s *IssuesService) ListMilestones(ctx context.Context, owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var milestones []*Milestone - resp, err := s.client.Do(ctx, req, &milestones) - if err != nil { - return nil, resp, err - } - - return milestones, resp, nil -} - -// GetMilestone gets a single milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone -func (s *IssuesService) GetMilestone(ctx context.Context, owner string, repo string, number int) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - milestone := new(Milestone) - resp, err := s.client.Do(ctx, req, milestone) - if err != nil { - return nil, resp, err - } - - return milestone, resp, nil -} - -// CreateMilestone creates a new milestone on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone -func (s *IssuesService) CreateMilestone(ctx context.Context, owner string, repo string, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - req, err := s.client.NewRequest("POST", u, milestone) - if err != nil { - return nil, nil, err - } - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// EditMilestone edits a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#update-a-milestone -func (s *IssuesService) EditMilestone(ctx context.Context, owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, milestone) - if err != nil { - return nil, nil, err - } - - m := new(Milestone) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteMilestone deletes a milestone. -// -// GitHub API docs: https://developer.github.com/v3/issues/milestones/#delete-a-milestone -func (s *IssuesService) DeleteMilestone(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/milestones/%d", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/issues_timeline.go b/vendor/github.com/google/go-github/github/issues_timeline.go deleted file mode 100644 index bc0b108990..0000000000 --- a/vendor/github.com/google/go-github/github/issues_timeline.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// Timeline represents an event that occurred around an Issue or Pull Request. -// -// It is similar to an IssueEvent but may contain more information. -// GitHub API docs: https://developer.github.com/v3/issues/timeline/ -type Timeline struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - CommitURL *string `json:"commit_url,omitempty"` - - // The User object that generated the event. - Actor *User `json:"actor,omitempty"` - - // Event identifies the actual type of Event that occurred. Possible values - // are: - // - // assigned - // The issue was assigned to the assignee. - // - // closed - // The issue was closed by the actor. When the commit_id is present, it - // identifies the commit that closed the issue using "closes / fixes #NN" - // syntax. - // - // commented - // A comment was added to the issue. - // - // committed - // A commit was added to the pull request's 'HEAD' branch. Only provided - // for pull requests. - // - // cross-referenced - // The issue was referenced from another issue. The 'source' attribute - // contains the 'id', 'actor', and 'url' of the reference's source. - // - // demilestoned - // The issue was removed from a milestone. - // - // head_ref_deleted - // The pull request's branch was deleted. - // - // head_ref_restored - // The pull request's branch was restored. - // - // labeled - // A label was added to the issue. - // - // locked - // The issue was locked by the actor. - // - // mentioned - // The actor was @mentioned in an issue body. - // - // merged - // The issue was merged by the actor. The 'commit_id' attribute is the - // SHA1 of the HEAD commit that was merged. - // - // milestoned - // The issue was added to a milestone. - // - // referenced - // The issue was referenced from a commit message. The 'commit_id' - // attribute is the commit SHA1 of where that happened. - // - // renamed - // The issue title was changed. - // - // reopened - // The issue was reopened by the actor. - // - // subscribed - // The actor subscribed to receive notifications for an issue. - // - // unassigned - // The assignee was unassigned from the issue. - // - // unlabeled - // A label was removed from the issue. - // - // unlocked - // The issue was unlocked by the actor. - // - // unsubscribed - // The actor unsubscribed to stop receiving notifications for an issue. - // - Event *string `json:"event,omitempty"` - - // The string SHA of a commit that referenced this Issue or Pull Request. - CommitID *string `json:"commit_id,omitempty"` - // The timestamp indicating when the event occurred. - CreatedAt *time.Time `json:"created_at,omitempty"` - // The Label object including `name` and `color` attributes. Only provided for - // 'labeled' and 'unlabeled' events. - Label *Label `json:"label,omitempty"` - // The User object which was assigned to (or unassigned from) this Issue or - // Pull Request. Only provided for 'assigned' and 'unassigned' events. - Assignee *User `json:"assignee,omitempty"` - // The Milestone object including a 'title' attribute. - // Only provided for 'milestoned' and 'demilestoned' events. - Milestone *Milestone `json:"milestone,omitempty"` - // The 'id', 'actor', and 'url' for the source of a reference from another issue. - // Only provided for 'cross-referenced' events. - Source *Source `json:"source,omitempty"` - // An object containing rename details including 'from' and 'to' attributes. - // Only provided for 'renamed' events. - Rename *Rename `json:"rename,omitempty"` -} - -// Source represents a reference's source. -type Source struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Actor *User `json:"actor,omitempty"` -} - -// ListIssueTimeline lists events for the specified issue. -// -// GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue -func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/timeline", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTimelinePreview) - - var events []*Timeline - resp, err := s.client.Do(ctx, req, &events) - return events, resp, err -} diff --git a/vendor/github.com/google/go-github/github/licenses.go b/vendor/github.com/google/go-github/github/licenses.go deleted file mode 100644 index e9cd1777af..0000000000 --- a/vendor/github.com/google/go-github/github/licenses.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// LicensesService handles communication with the license related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/licenses/ -type LicensesService service - -// RepositoryLicense represents the license for a repository. -type RepositoryLicense struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - - SHA *string `json:"sha,omitempty"` - Size *int `json:"size,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` - Type *string `json:"type,omitempty"` - Content *string `json:"content,omitempty"` - Encoding *string `json:"encoding,omitempty"` - License *License `json:"license,omitempty"` -} - -func (l RepositoryLicense) String() string { - return Stringify(l) -} - -// License represents an open source license. -type License struct { - Key *string `json:"key,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - - SPDXID *string `json:"spdx_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Featured *bool `json:"featured,omitempty"` - Description *string `json:"description,omitempty"` - Implementation *string `json:"implementation,omitempty"` - Permissions *[]string `json:"permissions,omitempty"` - Conditions *[]string `json:"conditions,omitempty"` - Limitations *[]string `json:"limitations,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (l License) String() string { - return Stringify(l) -} - -// List popular open source licenses. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses -func (s *LicensesService) List(ctx context.Context) ([]*License, *Response, error) { - req, err := s.client.NewRequest("GET", "licenses", nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) - - var licenses []*License - resp, err := s.client.Do(ctx, req, &licenses) - if err != nil { - return nil, resp, err - } - - return licenses, resp, nil -} - -// Get extended metadata for one license. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license -func (s *LicensesService) Get(ctx context.Context, licenseName string) (*License, *Response, error) { - u := fmt.Sprintf("licenses/%s", licenseName) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) - - license := new(License) - resp, err := s.client.Do(ctx, req, license) - if err != nil { - return nil, resp, err - } - - return license, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/messages.go b/vendor/github.com/google/go-github/github/messages.go deleted file mode 100644 index c0f315a778..0000000000 --- a/vendor/github.com/google/go-github/github/messages.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2016 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file provides functions for validating payloads from GitHub Webhooks. -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github - -package github - -import ( - "crypto/hmac" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "hash" - "io/ioutil" - "net/http" - "strings" -) - -const ( - // sha1Prefix is the prefix used by GitHub before the HMAC hexdigest. - sha1Prefix = "sha1" - // sha256Prefix and sha512Prefix are provided for future compatibility. - sha256Prefix = "sha256" - sha512Prefix = "sha512" - // signatureHeader is the GitHub header key used to pass the HMAC hexdigest. - signatureHeader = "X-Hub-Signature" - // eventTypeHeader is the GitHub header key used to pass the event type. - eventTypeHeader = "X-Github-Event" - // deliveryIDHeader is the GitHub header key used to pass the unique ID for the webhook event. - deliveryIDHeader = "X-Github-Delivery" -) - -var ( - // eventTypeMapping maps webhooks types to their corresponding go-github struct types. - eventTypeMapping = map[string]string{ - "commit_comment": "CommitCommentEvent", - "create": "CreateEvent", - "delete": "DeleteEvent", - "deployment": "DeploymentEvent", - "deployment_status": "DeploymentStatusEvent", - "fork": "ForkEvent", - "gollum": "GollumEvent", - "installation": "InstallationEvent", - "installation_repositories": "InstallationRepositoriesEvent", - "issue_comment": "IssueCommentEvent", - "issues": "IssuesEvent", - "label": "LabelEvent", - "member": "MemberEvent", - "membership": "MembershipEvent", - "milestone": "MilestoneEvent", - "organization": "OrganizationEvent", - "org_block": "OrgBlockEvent", - "page_build": "PageBuildEvent", - "ping": "PingEvent", - "project": "ProjectEvent", - "project_card": "ProjectCardEvent", - "project_column": "ProjectColumnEvent", - "public": "PublicEvent", - "pull_request_review": "PullRequestReviewEvent", - "pull_request_review_comment": "PullRequestReviewCommentEvent", - "pull_request": "PullRequestEvent", - "push": "PushEvent", - "repository": "RepositoryEvent", - "release": "ReleaseEvent", - "status": "StatusEvent", - "team": "TeamEvent", - "team_add": "TeamAddEvent", - "watch": "WatchEvent", - } -) - -// genMAC generates the HMAC signature for a message provided the secret key -// and hashFunc. -func genMAC(message, key []byte, hashFunc func() hash.Hash) []byte { - mac := hmac.New(hashFunc, key) - mac.Write(message) - return mac.Sum(nil) -} - -// checkMAC reports whether messageMAC is a valid HMAC tag for message. -func checkMAC(message, messageMAC, key []byte, hashFunc func() hash.Hash) bool { - expectedMAC := genMAC(message, key, hashFunc) - return hmac.Equal(messageMAC, expectedMAC) -} - -// messageMAC returns the hex-decoded HMAC tag from the signature and its -// corresponding hash function. -func messageMAC(signature string) ([]byte, func() hash.Hash, error) { - if signature == "" { - return nil, nil, errors.New("missing signature") - } - sigParts := strings.SplitN(signature, "=", 2) - if len(sigParts) != 2 { - return nil, nil, fmt.Errorf("error parsing signature %q", signature) - } - - var hashFunc func() hash.Hash - switch sigParts[0] { - case sha1Prefix: - hashFunc = sha1.New - case sha256Prefix: - hashFunc = sha256.New - case sha512Prefix: - hashFunc = sha512.New - default: - return nil, nil, fmt.Errorf("unknown hash type prefix: %q", sigParts[0]) - } - - buf, err := hex.DecodeString(sigParts[1]) - if err != nil { - return nil, nil, fmt.Errorf("error decoding signature %q: %v", signature, err) - } - return buf, hashFunc, nil -} - -// ValidatePayload validates an incoming GitHub Webhook event request -// and returns the (JSON) payload. -// secretKey is the GitHub Webhook secret message. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// // Process payload... -// } -// -func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error) { - payload, err = ioutil.ReadAll(r.Body) - if err != nil { - return nil, err - } - - sig := r.Header.Get(signatureHeader) - if err := validateSignature(sig, payload, secretKey); err != nil { - return nil, err - } - return payload, nil -} - -// validateSignature validates the signature for the given payload. -// signature is the GitHub hash signature delivered in the X-Hub-Signature header. -// payload is the JSON payload sent by GitHub Webhooks. -// secretKey is the GitHub Webhook secret message. -// -// GitHub API docs: https://developer.github.com/webhooks/securing/#validating-payloads-from-github -func validateSignature(signature string, payload, secretKey []byte) error { - messageMAC, hashFunc, err := messageMAC(signature) - if err != nil { - return err - } - if !checkMAC(payload, messageMAC, secretKey, hashFunc) { - return errors.New("payload signature check failed") - } - return nil -} - -// WebHookType returns the event type of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func WebHookType(r *http.Request) string { - return r.Header.Get(eventTypeHeader) -} - -// DeliveryID returns the unique delivery ID of webhook request r. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers -func DeliveryID(r *http.Request) string { - return r.Header.Get(deliveryIDHeader) -} - -// ParseWebHook parses the event payload. For recognized event types, a -// value of the corresponding struct type will be returned (as returned -// by Event.ParsePayload()). An error will be returned for unrecognized event -// types. -// -// Example usage: -// -// func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) { -// payload, err := github.ValidatePayload(r, s.webhookSecretKey) -// if err != nil { ... } -// event, err := github.ParseWebHook(github.WebHookType(r), payload) -// if err != nil { ... } -// switch event := event.(type) { -// case *github.CommitCommentEvent: -// processCommitCommentEvent(event) -// case *github.CreateEvent: -// processCreateEvent(event) -// ... -// } -// } -// -func ParseWebHook(messageType string, payload []byte) (interface{}, error) { - eventType, ok := eventTypeMapping[messageType] - if !ok { - return nil, fmt.Errorf("unknown X-Github-Event in message: %v", messageType) - } - - event := Event{ - Type: &eventType, - RawPayload: (*json.RawMessage)(&payload), - } - return event.ParsePayload() -} diff --git a/vendor/github.com/google/go-github/github/migrations.go b/vendor/github.com/google/go-github/github/migrations.go deleted file mode 100644 index 6793269cd3..0000000000 --- a/vendor/github.com/google/go-github/github/migrations.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "errors" - "fmt" - "net/http" - "strings" -) - -// MigrationService provides access to the migration related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/migration/ -type MigrationService service - -// Migration represents a GitHub migration (archival). -type Migration struct { - ID *int `json:"id,omitempty"` - GUID *string `json:"guid,omitempty"` - // State is the current state of a migration. - // Possible values are: - // "pending" which means the migration hasn't started yet, - // "exporting" which means the migration is in progress, - // "exported" which means the migration finished successfully, or - // "failed" which means the migration failed. - State *string `json:"state,omitempty"` - // LockRepositories indicates whether repositories are locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` - URL *string `json:"url,omitempty"` - CreatedAt *string `json:"created_at,omitempty"` - UpdatedAt *string `json:"updated_at,omitempty"` - Repositories []*Repository `json:"repositories,omitempty"` -} - -func (m Migration) String() string { - return Stringify(m) -} - -// MigrationOptions specifies the optional parameters to Migration methods. -type MigrationOptions struct { - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories bool - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments bool -} - -// startMigration represents the body of a StartMigration request. -type startMigration struct { - // Repositories is a slice of repository names to migrate. - Repositories []string `json:"repositories,omitempty"` - - // LockRepositories indicates whether repositories should be locked (to prevent - // manipulation) while migrating data. - LockRepositories *bool `json:"lock_repositories,omitempty"` - - // ExcludeAttachments indicates whether attachments should be excluded from - // the migration (to reduce migration archive file size). - ExcludeAttachments *bool `json:"exclude_attachments,omitempty"` -} - -// StartMigration starts the generation of a migration archive. -// repos is a slice of repository names to migrate. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration -func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - body := &startMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) - } - - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListMigrations lists the most recent migrations. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-a-list-of-migrations -func (s *MigrationService) ListMigrations(ctx context.Context, org string) ([]*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations", org) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - var m []*Migration - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationStatus gets the status of a specific migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-the-status-of-a-migration -func (s *MigrationService) MigrationStatus(ctx context.Context, org string, id int) (*Migration, *Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - m := &Migration{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// MigrationArchiveURL fetches a migration archive URL. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#download-a-migration-archive -func (s *MigrationService) MigrationArchiveURL(ctx context.Context, org string, id int) (url string, err error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - // Disable the redirect mechanism because AWS fails if the GitHub auth token is provided. - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - _, err = s.client.Do(ctx, req, nil) // expect error from disable redirect - if err == nil { - return "", errors.New("expected redirect, none provided") - } - if !strings.Contains(err.Error(), "disable redirect") { - return "", err - } - return loc, nil -} - -// DeleteMigration deletes a previous migration archive. -// id is the migration ID. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#delete-a-migration-archive -func (s *MigrationService) DeleteMigration(ctx context.Context, org string, id int) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnlockRepo unlocks a repository that was locked for migration. -// id is the migration ID. -// You should unlock each migrated repository and delete them when the migration -// is complete and you no longer need the source data. -// -// GitHub API docs: https://developer.github.com/v3/migration/migrations/#unlock-a-repository -func (s *MigrationService) UnlockRepo(ctx context.Context, org string, id int, repo string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/migrations/%v/repos/%v/lock", org, id, repo) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeMigrationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/migrations_source_import.go b/vendor/github.com/google/go-github/github/migrations_source_import.go deleted file mode 100644 index aa45a5a364..0000000000 --- a/vendor/github.com/google/go-github/github/migrations_source_import.go +++ /dev/null @@ -1,329 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Import represents a repository import request. -type Import struct { - // The URL of the originating repository. - VCSURL *string `json:"vcs_url,omitempty"` - // The originating VCS type. Can be one of 'subversion', 'git', - // 'mercurial', or 'tfvc'. Without this parameter, the import job will - // take additional time to detect the VCS type before beginning the - // import. This detection step will be reflected in the response. - VCS *string `json:"vcs,omitempty"` - // VCSUsername and VCSPassword are only used for StartImport calls that - // are importing a password-protected repository. - VCSUsername *string `json:"vcs_username,omitempty"` - VCSPassword *string `json:"vcs_password,omitempty"` - // For a tfvc import, the name of the project that is being imported. - TFVCProject *string `json:"tfvc_project,omitempty"` - - // LFS related fields that may be preset in the Import Progress response - - // Describes whether the import has been opted in or out of using Git - // LFS. The value can be 'opt_in', 'opt_out', or 'undecided' if no - // action has been taken. - UseLFS *string `json:"use_lfs,omitempty"` - // Describes whether files larger than 100MB were found during the - // importing step. - HasLargeFiles *bool `json:"has_large_files,omitempty"` - // The total size in gigabytes of files larger than 100MB found in the - // originating repository. - LargeFilesSize *int `json:"large_files_size,omitempty"` - // The total number of files larger than 100MB found in the originating - // repository. To see a list of these files, call LargeFiles. - LargeFilesCount *int `json:"large_files_count,omitempty"` - - // Identifies the current status of an import. An import that does not - // have errors will progress through these steps: - // - // detecting - the "detection" step of the import is in progress - // because the request did not include a VCS parameter. The - // import is identifying the type of source control present at - // the URL. - // importing - the "raw" step of the import is in progress. This is - // where commit data is fetched from the original repository. - // The import progress response will include CommitCount (the - // total number of raw commits that will be imported) and - // Percent (0 - 100, the current progress through the import). - // mapping - the "rewrite" step of the import is in progress. This - // is where SVN branches are converted to Git branches, and - // where author updates are applied. The import progress - // response does not include progress information. - // pushing - the "push" step of the import is in progress. This is - // where the importer updates the repository on GitHub. The - // import progress response will include PushPercent, which is - // the percent value reported by git push when it is "Writing - // objects". - // complete - the import is complete, and the repository is ready - // on GitHub. - // - // If there are problems, you will see one of these in the status field: - // - // auth_failed - the import requires authentication in order to - // connect to the original repository. Make an UpdateImport - // request, and include VCSUsername and VCSPassword. - // error - the import encountered an error. The import progress - // response will include the FailedStep and an error message. - // Contact GitHub support for more information. - // detection_needs_auth - the importer requires authentication for - // the originating repository to continue detection. Make an - // UpdatImport request, and include VCSUsername and - // VCSPassword. - // detection_found_nothing - the importer didn't recognize any - // source control at the URL. - // detection_found_multiple - the importer found several projects - // or repositories at the provided URL. When this is the case, - // the Import Progress response will also include a - // ProjectChoices field with the possible project choices as - // values. Make an UpdateImport request, and include VCS and - // (if applicable) TFVCProject. - Status *string `json:"status,omitempty"` - CommitCount *int `json:"commit_count,omitempty"` - StatusText *string `json:"status_text,omitempty"` - AuthorsCount *int `json:"authors_count,omitempty"` - Percent *int `json:"percent,omitempty"` - PushPercent *int `json:"push_percent,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AuthorsURL *string `json:"authors_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` - Message *string `json:"message,omitempty"` - FailedStep *string `json:"failed_step,omitempty"` - - // Human readable display name, provided when the Import appears as - // part of ProjectChoices. - HumanName *string `json:"human_name,omitempty"` - - // When the importer finds several projects or repositories at the - // provided URLs, this will identify the available choices. Call - // UpdateImport with the selected Import value. - ProjectChoices []Import `json:"project_choices,omitempty"` -} - -func (i Import) String() string { - return Stringify(i) -} - -// SourceImportAuthor identifies an author imported from a source repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -type SourceImportAuthor struct { - ID *int `json:"id,omitempty"` - RemoteID *string `json:"remote_id,omitempty"` - RemoteName *string `json:"remote_name,omitempty"` - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - ImportURL *string `json:"import_url,omitempty"` -} - -func (a SourceImportAuthor) String() string { - return Stringify(a) -} - -// LargeFile identifies a file larger than 100MB found during a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -type LargeFile struct { - RefName *string `json:"ref_name,omitempty"` - Path *string `json:"path,omitempty"` - OID *string `json:"oid,omitempty"` - Size *int `json:"size,omitempty"` -} - -func (f LargeFile) String() string { - return Stringify(f) -} - -// StartImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#start-an-import -func (s *MigrationService) StartImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PUT", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// ImportProgress queries for the status and progress of an ongoing repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-import-progress -func (s *MigrationService) ImportProgress(ctx context.Context, owner, repo string) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// UpdateImport initiates a repository import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#update-existing-import -func (s *MigrationService) UpdateImport(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// CommitAuthors gets the authors mapped from the original repository. -// -// Each type of source control system represents authors in a different way. -// For example, a Git commit author has a display name and an email address, -// but a Subversion commit author just has a username. The GitHub Importer will -// make the author information valid, but the author might not be correct. For -// example, it will change the bare Subversion username "hubot" into something -// like "hubot ". -// -// This method and MapCommitAuthor allow you to provide correct Git author -// information. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors -func (s *MigrationService) CommitAuthors(ctx context.Context, owner, repo string) ([]*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var authors []*SourceImportAuthor - resp, err := s.client.Do(ctx, req, &authors) - if err != nil { - return nil, resp, err - } - - return authors, resp, nil -} - -// MapCommitAuthor updates an author's identity for the import. Your -// application can continue updating authors any time before you push new -// commits to the repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#map-a-commit-author -func (s *MigrationService) MapCommitAuthor(ctx context.Context, owner, repo string, id int, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/authors/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, author) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(SourceImportAuthor) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// SetLFSPreference sets whether imported repositories should use Git LFS for -// files larger than 100MB. Only the UseLFS field on the provided Import is -// used. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#set-git-lfs-preference -func (s *MigrationService) SetLFSPreference(ctx context.Context, owner, repo string, in *Import) (*Import, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/lfs", owner, repo) - req, err := s.client.NewRequest("PATCH", u, in) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - out := new(Import) - resp, err := s.client.Do(ctx, req, out) - if err != nil { - return nil, resp, err - } - - return out, resp, nil -} - -// LargeFiles lists files larger than 100MB found during the import. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files -func (s *MigrationService) LargeFiles(ctx context.Context, owner, repo string) ([]*LargeFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/import/large_files", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - var files []*LargeFile - resp, err := s.client.Do(ctx, req, &files) - if err != nil { - return nil, resp, err - } - - return files, resp, nil -} - -// CancelImport stops an import for a repository. -// -// GitHub API docs: https://developer.github.com/v3/migration/source_imports/#cancel-an-import -func (s *MigrationService) CancelImport(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/import", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/misc.go b/vendor/github.com/google/go-github/github/misc.go deleted file mode 100644 index 5b8082d3ce..0000000000 --- a/vendor/github.com/google/go-github/github/misc.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "bytes" - "context" - "fmt" - "net/url" -) - -// MarkdownOptions specifies optional parameters to the Markdown method. -type MarkdownOptions struct { - // Mode identifies the rendering mode. Possible values are: - // markdown - render a document as plain Markdown, just like - // README files are rendered. - // - // gfm - to render a document as user-content, e.g. like user - // comments or issues are rendered. In GFM mode, hard line breaks are - // always taken into account, and issue and user mentions are linked - // accordingly. - // - // Default is "markdown". - Mode string - - // Context identifies the repository context. Only taken into account - // when rendering as "gfm". - Context string -} - -type markdownRequest struct { - Text *string `json:"text,omitempty"` - Mode *string `json:"mode,omitempty"` - Context *string `json:"context,omitempty"` -} - -// Markdown renders an arbitrary Markdown document. -// -// GitHub API docs: https://developer.github.com/v3/markdown/ -func (c *Client) Markdown(ctx context.Context, text string, opt *MarkdownOptions) (string, *Response, error) { - request := &markdownRequest{Text: String(text)} - if opt != nil { - if opt.Mode != "" { - request.Mode = String(opt.Mode) - } - if opt.Context != "" { - request.Context = String(opt.Context) - } - } - - req, err := c.NewRequest("POST", "markdown", request) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ListEmojis returns the emojis available to use on GitHub. -// -// GitHub API docs: https://developer.github.com/v3/emojis/ -func (c *Client) ListEmojis(ctx context.Context) (map[string]string, *Response, error) { - req, err := c.NewRequest("GET", "emojis", nil) - if err != nil { - return nil, nil, err - } - - var emoji map[string]string - resp, err := c.Do(ctx, req, &emoji) - if err != nil { - return nil, resp, err - } - - return emoji, resp, nil -} - -// CodeOfConduct represents a code of conduct. -type CodeOfConduct struct { - Name *string `json:"name,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c *CodeOfConduct) String() string { - return Stringify(c) -} - -// ListCodesOfConduct returns all codes of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#list-all-codes-of-conduct -func (c *Client) ListCodesOfConduct(ctx context.Context) ([]*CodeOfConduct, *Response, error) { - req, err := c.NewRequest("GET", "codes_of_conduct", nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - var cs []*CodeOfConduct - resp, err := c.Do(ctx, req, &cs) - if err != nil { - return nil, resp, err - } - - return cs, resp, nil -} - -// GetCodeOfConduct returns an individual code of conduct. -// -// https://developer.github.com/v3/codes_of_conduct/#get-an-individual-code-of-conduct -func (c *Client) GetCodeOfConduct(ctx context.Context, key string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("codes_of_conduct/%s", key) - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := c.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// APIMeta represents metadata about the GitHub API. -type APIMeta struct { - // An Array of IP addresses in CIDR format specifying the addresses - // that incoming service hooks will originate from on GitHub.com. - Hooks []string `json:"hooks,omitempty"` - - // An Array of IP addresses in CIDR format specifying the Git servers - // for GitHub.com. - Git []string `json:"git,omitempty"` - - // Whether authentication with username and password is supported. - // (GitHub Enterprise instances using CAS or OAuth for authentication - // will return false. Features like Basic Authentication with a - // username and password, sudo mode, and two-factor authentication are - // not supported on these servers.) - VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"` - - // An array of IP addresses in CIDR format specifying the addresses - // which serve GitHub Pages websites. - Pages []string `json:"pages,omitempty"` -} - -// APIMeta returns information about GitHub.com, the service. Or, if you access -// this endpoint on your organization’s GitHub Enterprise installation, this -// endpoint provides information about that installation. -// -// GitHub API docs: https://developer.github.com/v3/meta/ -func (c *Client) APIMeta(ctx context.Context) (*APIMeta, *Response, error) { - req, err := c.NewRequest("GET", "meta", nil) - if err != nil { - return nil, nil, err - } - - meta := new(APIMeta) - resp, err := c.Do(ctx, req, meta) - if err != nil { - return nil, resp, err - } - - return meta, resp, nil -} - -// Octocat returns an ASCII art octocat with the specified message in a speech -// bubble. If message is empty, a random zen phrase is used. -func (c *Client) Octocat(ctx context.Context, message string) (string, *Response, error) { - u := "octocat" - if message != "" { - u = fmt.Sprintf("%s?s=%s", u, url.QueryEscape(message)) - } - - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// Zen returns a random line from The Zen of GitHub. -// -// see also: http://warpspire.com/posts/taste/ -func (c *Client) Zen(ctx context.Context) (string, *Response, error) { - req, err := c.NewRequest("GET", "zen", nil) - if err != nil { - return "", nil, err - } - - buf := new(bytes.Buffer) - resp, err := c.Do(ctx, req, buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// ServiceHook represents a hook that has configuration settings, a list of -// available events, and default events. -type ServiceHook struct { - Name *string `json:"name,omitempty"` - Events []string `json:"events,omitempty"` - SupportedEvents []string `json:"supported_events,omitempty"` - Schema [][]string `json:"schema,omitempty"` -} - -func (s *ServiceHook) String() string { - return Stringify(s) -} - -// ListServiceHooks lists all of the available service hooks. -// -// GitHub API docs: https://developer.github.com/webhooks/#services -func (c *Client) ListServiceHooks(ctx context.Context) ([]*ServiceHook, *Response, error) { - u := "hooks" - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*ServiceHook - resp, err := c.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs.go b/vendor/github.com/google/go-github/github/orgs.go deleted file mode 100644 index e6947c96cf..0000000000 --- a/vendor/github.com/google/go-github/github/orgs.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// OrganizationsService provides access to the organization related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/orgs/ -type OrganizationsService service - -// Organization represents a GitHub organization account. -type Organization struct { - Login *string `json:"login,omitempty"` - ID *int `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Description *string `json:"description,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - BillingEmail *string `json:"billing_email,omitempty"` - Type *string `json:"type,omitempty"` - Plan *Plan `json:"plan,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - PublicMembersURL *string `json:"public_members_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` -} - -func (o Organization) String() string { - return Stringify(o) -} - -// Plan represents the payment plan for an account. See plans at https://github.com/plans. -type Plan struct { - Name *string `json:"name,omitempty"` - Space *int `json:"space,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - PrivateRepos *int `json:"private_repos,omitempty"` -} - -func (p Plan) String() string { - return Stringify(p) -} - -// OrganizationsListOptions specifies the optional parameters to the -// OrganizationsService.ListAll method. -type OrganizationsListOptions struct { - // Since filters Organizations by ID. - Since int `url:"since,omitempty"` - - ListOptions -} - -// ListAll lists all organizations, in the order that they were created on GitHub. -// -// Note: Pagination is powered exclusively by the since parameter. To continue -// listing the next set of organizations, use the ID of the last-returned organization -// as the opts.Since parameter for the next call. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations -func (s *OrganizationsService) ListAll(ctx context.Context, opt *OrganizationsListOptions) ([]*Organization, *Response, error) { - u, err := addOptions("organizations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - orgs := []*Organization{} - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - return orgs, resp, nil -} - -// List the organizations for a user. Passing the empty string will list -// organizations for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#list-user-organizations -func (s *OrganizationsService) List(ctx context.Context, user string, opt *ListOptions) ([]*Organization, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/orgs", user) - } else { - u = "user/orgs" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var orgs []*Organization - resp, err := s.client.Do(ctx, req, &orgs) - if err != nil { - return nil, resp, err - } - - return orgs, resp, nil -} - -// Get fetches an organization by name. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#get-an-organization -func (s *OrganizationsService) Get(ctx context.Context, org string) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", org) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// GetByID fetches an organization. -// -// Note: GetByID uses the undocumented GitHub API endpoint /organizations/:id. -func (s *OrganizationsService) GetByID(ctx context.Context, id int) (*Organization, *Response, error) { - u := fmt.Sprintf("organizations/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - organization := new(Organization) - resp, err := s.client.Do(ctx, req, organization) - if err != nil { - return nil, resp, err - } - - return organization, resp, nil -} - -// Edit an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/#edit-an-organization -func (s *OrganizationsService) Edit(ctx context.Context, name string, org *Organization) (*Organization, *Response, error) { - u := fmt.Sprintf("orgs/%v", name) - req, err := s.client.NewRequest("PATCH", u, org) - if err != nil { - return nil, nil, err - } - - o := new(Organization) - resp, err := s.client.Do(ctx, req, o) - if err != nil { - return nil, resp, err - } - - return o, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_hooks.go b/vendor/github.com/google/go-github/github/orgs_hooks.go deleted file mode 100644 index 4fc692e0f6..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_hooks.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListHooks lists all Hooks for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks -func (s *OrganizationsService) ListHooks(ctx context.Context, org string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook -func (s *OrganizationsService) GetHook(ctx context.Context, org string, id int) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - hook := new(Hook) - resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err -} - -// CreateHook creates a Hook for the specified org. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook -func (s *OrganizationsService) CreateHook(ctx context.Context, org string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks", org) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook -func (s *OrganizationsService) EditHook(ctx context.Context, org string, id int, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - return h, resp, err -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook -func (s *OrganizationsService) PingHook(ctx context.Context, org string, id int) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d/pings", org, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook -func (s *OrganizationsService) DeleteHook(ctx context.Context, org string, id int) (*Response, error) { - u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/orgs_members.go b/vendor/github.com/google/go-github/github/orgs_members.go deleted file mode 100644 index f1209c7c41..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_members.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Membership represents the status of a user's membership in an organization or team. -type Membership struct { - URL *string `json:"url,omitempty"` - - // State is the user's status within the organization or team. - // Possible values are: "active", "pending" - State *string `json:"state,omitempty"` - - // Role identifies the user's role within the organization or team. - // Possible values for organization membership: - // member - non-owner organization member - // admin - organization owner - // - // Possible values for team membership are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - Role *string `json:"role,omitempty"` - - // For organization membership, the API URL of the organization. - OrganizationURL *string `json:"organization_url,omitempty"` - - // For organization membership, the organization the membership is for. - Organization *Organization `json:"organization,omitempty"` - - // For organization membership, the user the membership is for. - User *User `json:"user,omitempty"` -} - -func (m Membership) String() string { - return Stringify(m) -} - -// ListMembersOptions specifies optional parameters to the -// OrganizationsService.ListMembers method. -type ListMembersOptions struct { - // If true (or if the authenticated user is not an owner of the - // organization), list only publicly visible members. - PublicOnly bool `url:"-"` - - // Filter members returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - // Role filters members returned by their role in the organization. - // Possible values are: - // all - all members of the organization, regardless of role - // admin - organization owners - // member - non-organization members - // - // Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListMembers lists the members for an organization. If the authenticated -// user is an owner of the organization, this will return both concealed and -// public members, otherwise it will only return public members. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#members-list -func (s *OrganizationsService) ListMembers(ctx context.Context, org string, opt *ListMembersOptions) ([]*User, *Response, error) { - var u string - if opt != nil && opt.PublicOnly { - u = fmt.Sprintf("orgs/%v/public_members", org) - } else { - u = fmt.Sprintf("orgs/%v/members", org) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsMember checks if a user is a member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-membership -func (s *OrganizationsService) IsMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// IsPublicMember checks if a user is a public member of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#check-public-membership -func (s *OrganizationsService) IsPublicMember(ctx context.Context, org, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// RemoveMember removes a user from all teams of an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-a-member -func (s *OrganizationsService) RemoveMember(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// PublicizeMembership publicizes a user's membership in an organization. (A -// user cannot publicize the membership for another user.) -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#publicize-a-users-membership -func (s *OrganizationsService) PublicizeMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ConcealMembership conceals a user's membership in an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#conceal-a-users-membership -func (s *OrganizationsService) ConcealMembership(ctx context.Context, org, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/public_members/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListOrgMembershipsOptions specifies optional parameters to the -// OrganizationsService.ListOrgMemberships method. -type ListOrgMembershipsOptions struct { - // Filter memberships to include only those with the specified state. - // Possible values are: "active", "pending". - State string `url:"state,omitempty"` - - ListOptions -} - -// ListOrgMemberships lists the organization memberships for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships -func (s *OrganizationsService) ListOrgMemberships(ctx context.Context, opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error) { - u := "user/memberships/orgs" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var memberships []*Membership - resp, err := s.client.Do(ctx, req, &memberships) - if err != nil { - return nil, resp, err - } - - return memberships, resp, nil -} - -// GetOrgMembership gets the membership for a user in a specified organization. -// Passing an empty string for user will get the membership for the -// authenticated user. -// -// GitHub API docs: -// https://developer.github.com/v3/orgs/members/#get-organization-membership -// https://developer.github.com/v3/orgs/members/#get-your-organization-membership -func (s *OrganizationsService) GetOrgMembership(ctx context.Context, user, org string) (*Membership, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - membership := new(Membership) - resp, err := s.client.Do(ctx, req, membership) - if err != nil { - return nil, resp, err - } - - return membership, resp, nil -} - -// EditOrgMembership edits the membership for user in specified organization. -// Passing an empty string for user will edit the membership for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership -// GitHub API docs: https://developer.github.com/v3/orgs/members/#edit-your-organization-membership -func (s *OrganizationsService) EditOrgMembership(ctx context.Context, user, org string, membership *Membership) (*Membership, *Response, error) { - var u, method string - if user != "" { - u = fmt.Sprintf("orgs/%v/memberships/%v", org, user) - method = "PUT" - } else { - u = fmt.Sprintf("user/memberships/orgs/%v", org) - method = "PATCH" - } - - req, err := s.client.NewRequest(method, u, membership) - if err != nil { - return nil, nil, err - } - - m := new(Membership) - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// RemoveOrgMembership removes user from the specified organization. If the -// user has been invited to the organization, this will cancel their invitation. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-organization-membership -func (s *OrganizationsService) RemoveOrgMembership(ctx context.Context, user, org string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/memberships/%v", org, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingOrgInvitations returns a list of pending invitations. -// -// GitHub API docs: https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations -func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, org int, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("orgs/%v/invitations", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - return pendingInvitations, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go b/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go deleted file mode 100644 index e34f8653b5..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_outside_collaborators.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListOutsideCollaboratorsOptions specifies optional parameters to the -// OrganizationsService.ListOutsideCollaborators method. -type ListOutsideCollaboratorsOptions struct { - // Filter outside collaborators returned in the list. Possible values are: - // 2fa_disabled, all. Default is "all". - Filter string `url:"filter,omitempty"` - - ListOptions -} - -// ListOutsideCollaborators lists outside collaborators of organization's repositories. -// This will only work if the authenticated -// user is an owner of the organization. -// -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#list-outside-collaborators -func (s *OrganizationsService) ListOutsideCollaborators(ctx context.Context, org string, opt *ListOutsideCollaboratorsOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/outside_collaborators", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_projects.go b/vendor/github.com/google/go-github/github/orgs_projects.go deleted file mode 100644 index e57cba9782..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_projects.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListProjects lists the projects for an organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-organization-projects -func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified organization. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-an-organization-project -func (s *OrganizationsService) CreateProject(ctx context.Context, org string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("orgs/%v/projects", org) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_teams.go b/vendor/github.com/google/go-github/github/orgs_teams.go deleted file mode 100644 index 684e2dafff..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_teams.go +++ /dev/null @@ -1,431 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// Team represents a team within a GitHub organization. Teams are used to -// manage access to an organization's repositories. -type Team struct { - ID *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - Description *string `json:"description,omitempty"` - URL *string `json:"url,omitempty"` - Slug *string `json:"slug,omitempty"` - - // Permission is deprecated when creating or editing a team in an org - // using the new GitHub permission model. It no longer identifies the - // permission a team has on its repos, but only specifies the default - // permission a repo is initially added with. Avoid confusion by - // specifying a permission value when calling AddTeamRepo. - Permission *string `json:"permission,omitempty"` - - // Privacy identifies the level of privacy this team should have. - // Possible values are: - // secret - only visible to organization owners and members of this team - // closed - visible to all members of this organization - // Default is "secret". - Privacy *string `json:"privacy,omitempty"` - - MembersCount *int `json:"members_count,omitempty"` - ReposCount *int `json:"repos_count,omitempty"` - Organization *Organization `json:"organization,omitempty"` - MembersURL *string `json:"members_url,omitempty"` - RepositoriesURL *string `json:"repositories_url,omitempty"` - - // LDAPDN is only available in GitHub Enterprise and when the team - // membership is synchronized with LDAP. - LDAPDN *string `json:"ldap_dn,omitempty"` -} - -func (t Team) String() string { - return Stringify(t) -} - -// Invitation represents a team member's invitation status. -type Invitation struct { - ID *int `json:"id,omitempty"` - Login *string `json:"login,omitempty"` - Email *string `json:"email,omitempty"` - // Role can be one of the values - 'direct_member', 'admin', 'billing_manager', 'hiring_manager', or 'reinstate'. - Role *string `json:"role,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - Inviter *User `json:"inviter,omitempty"` -} - -func (i Invitation) String() string { - return Stringify(i) -} - -// ListTeams lists all of the teams for an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-teams -func (s *OrganizationsService) ListTeams(ctx context.Context, org string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// GetTeam fetches a team by ID. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team -func (s *OrganizationsService) GetTeam(ctx context.Context, team int) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// CreateTeam creates a new team within an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#create-team -func (s *OrganizationsService) CreateTeam(ctx context.Context, org string, team *Team) (*Team, *Response, error) { - u := fmt.Sprintf("orgs/%v/teams", org) - req, err := s.client.NewRequest("POST", u, team) - if err != nil { - return nil, nil, err - } - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// EditTeam edits a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#edit-team -func (s *OrganizationsService) EditTeam(ctx context.Context, id int, team *Team) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", id) - req, err := s.client.NewRequest("PATCH", u, team) - if err != nil { - return nil, nil, err - } - - t := new(Team) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// DeleteTeam deletes a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#delete-team -func (s *OrganizationsService) DeleteTeam(ctx context.Context, team int) (*Response, error) { - u := fmt.Sprintf("teams/%v", team) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// OrganizationListTeamMembersOptions specifies the optional parameters to the -// OrganizationsService.ListTeamMembers method. -type OrganizationListTeamMembersOptions struct { - // Role filters members returned by their role in the team. Possible - // values are "all", "member", "maintainer". Default is "all". - Role string `url:"role,omitempty"` - - ListOptions -} - -// ListTeamMembers lists all of the users who are members of the specified -// team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-team-members -func (s *OrganizationsService) ListTeamMembers(ctx context.Context, team int, opt *OrganizationListTeamMembersOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("teams/%v/members", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var members []*User - resp, err := s.client.Do(ctx, req, &members) - if err != nil { - return nil, resp, err - } - - return members, resp, nil -} - -// IsTeamMember checks if a user is a member of the specified team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-member -func (s *OrganizationsService) IsTeamMember(ctx context.Context, team int, user string) (bool, *Response, error) { - u := fmt.Sprintf("teams/%v/members/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - member, err := parseBoolResponse(err) - return member, resp, err -} - -// ListTeamRepos lists the repositories that the specified team has access to. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-team-repos -func (s *OrganizationsService) ListTeamRepos(ctx context.Context, team int, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// IsTeamRepo checks if a team manages the specified repository. If the -// repository is managed by team, a Repository is returned which includes the -// permissions team has for that repo. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#check-if-a-team-manages-a-repository -func (s *OrganizationsService) IsTeamRepo(ctx context.Context, team int, owner string, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - req.Header.Set("Accept", mediaTypeOrgPermissionRepo) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// OrganizationAddTeamRepoOptions specifies the optional parameters to the -// OrganizationsService.AddTeamRepo method. -type OrganizationAddTeamRepoOptions struct { - // Permission specifies the permission to grant the team on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // If not specified, the team's permission attribute will be used. - Permission string `json:"permission,omitempty"` -} - -// AddTeamRepo adds a repository to be managed by the specified team. The -// specified repository must be owned by the organization to which the team -// belongs, or a direct fork of a repository owned by the organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-repo -func (s *OrganizationsService) AddTeamRepo(ctx context.Context, team int, owner string, repo string, opt *OrganizationAddTeamRepoOptions) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// RemoveTeamRepo removes a repository from being managed by the specified -// team. Note that this does not delete the repository, it just removes it -// from the team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-repo -func (s *OrganizationsService) RemoveTeamRepo(ctx context.Context, team int, owner string, repo string) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListUserTeams lists a user's teams -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-user-teams -func (s *OrganizationsService) ListUserTeams(ctx context.Context, opt *ListOptions) ([]*Team, *Response, error) { - u := "user/teams" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// GetTeamMembership returns the membership status for a user in a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-membership -func (s *OrganizationsService) GetTeamMembership(ctx context.Context, team int, user string) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// OrganizationAddTeamMembershipOptions does stuff specifies the optional -// parameters to the OrganizationsService.AddTeamMembership method. -type OrganizationAddTeamMembershipOptions struct { - // Role specifies the role the user should have in the team. Possible - // values are: - // member - a normal member of the team - // maintainer - a team maintainer. Able to add/remove other team - // members, promote other team members to team - // maintainer, and edit the team’s name and description - // - // Default value is "member". - Role string `json:"role,omitempty"` -} - -// AddTeamMembership adds or invites a user to a team. -// -// In order to add a membership between a user and a team, the authenticated -// user must have 'admin' permissions to the team or be an owner of the -// organization that the team is associated with. -// -// If the user is already a part of the team's organization (meaning they're on -// at least one other team in the organization), this endpoint will add the -// user to the team. -// -// If the user is completely unaffiliated with the team's organization (meaning -// they're on none of the organization's teams), this endpoint will send an -// invitation to the user via email. This newly-created membership will be in -// the "pending" state until the user accepts the invitation, at which point -// the membership will transition to the "active" state and the user will be -// added as a member of the team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-membership -func (s *OrganizationsService) AddTeamMembership(ctx context.Context, team int, user string, opt *OrganizationAddTeamMembershipOptions) (*Membership, *Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - - t := new(Membership) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} - -// RemoveTeamMembership removes a user from a team. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-membership -func (s *OrganizationsService) RemoveTeamMembership(ctx context.Context, team int, user string) (*Response, error) { - u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// ListPendingTeamInvitations get pending invitaion list in team. -// Warning: The API may change without advance notice during the preview period. -// Preview features are not supported for production use. -// -// GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-pending-team-invitations -func (s *OrganizationsService) ListPendingTeamInvitations(ctx context.Context, team int, opt *ListOptions) ([]*Invitation, *Response, error) { - u := fmt.Sprintf("teams/%v/invitations", team) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pendingInvitations []*Invitation - resp, err := s.client.Do(ctx, req, &pendingInvitations) - if err != nil { - return nil, resp, err - } - - return pendingInvitations, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/orgs_users_blocking.go b/vendor/github.com/google/go-github/github/orgs_users_blocking.go deleted file mode 100644 index b1aecf4453..0000000000 --- a/vendor/github.com/google/go-github/github/orgs_users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the users blocked by an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#list-blocked-users -func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#check-whether-a-user-is-blocked-from-an-organization -func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user string) (bool, *Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#block-a-user -func (s *OrganizationsService) BlockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user from an organization. -// -// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#unblock-a-user -func (s *OrganizationsService) UnblockUser(ctx context.Context, org string, user string) (*Response, error) { - u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/projects.go b/vendor/github.com/google/go-github/github/projects.go deleted file mode 100644 index 11c885f99d..0000000000 --- a/vendor/github.com/google/go-github/github/projects.go +++ /dev/null @@ -1,425 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ProjectsService provides access to the projects functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/projects/ -type ProjectsService service - -// Project represents a GitHub Project. -type Project struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - OwnerURL *string `json:"owner_url,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Number *int `json:"number,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - - // The User object that generated the project. - Creator *User `json:"creator,omitempty"` -} - -func (p Project) String() string { - return Stringify(p) -} - -// GetProject gets a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#get-a-project -func (s *ProjectsService) GetProject(ctx context.Context, id int) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// ProjectOptions specifies the parameters to the -// RepositoriesService.CreateProject and -// ProjectsService.UpdateProject methods. -type ProjectOptions struct { - // The name of the project. (Required for creation; optional for update.) - Name string `json:"name,omitempty"` - // The body of the project. (Optional.) - Body string `json:"body,omitempty"` -} - -// UpdateProject updates a repository project. -// -// GitHub API docs: https://developer.github.com/v3/projects/#update-a-project -func (s *ProjectsService) UpdateProject(ctx context.Context, id int, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} - -// DeleteProject deletes a GitHub Project from a repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#delete-a-project -func (s *ProjectsService) DeleteProject(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumn represents a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/repos/projects/ -type ProjectColumn struct { - ID *int `json:"id,omitempty"` - Name *string `json:"name,omitempty"` - ProjectURL *string `json:"project_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// ListProjectColumns lists the columns of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#list-project-columns -func (s *ProjectsService) ListProjectColumns(ctx context.Context, projectID int, opt *ListOptions) ([]*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - columns := []*ProjectColumn{} - resp, err := s.client.Do(ctx, req, &columns) - if err != nil { - return nil, resp, err - } - - return columns, resp, nil -} - -// GetProjectColumn gets a column of a GitHub Project for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#get-a-project-column -func (s *ProjectsService) GetProjectColumn(ctx context.Context, id int) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// ProjectColumnOptions specifies the parameters to the -// ProjectsService.CreateProjectColumn and -// ProjectsService.UpdateProjectColumn methods. -type ProjectColumnOptions struct { - // The name of the project column. (Required for creation and update.) - Name string `json:"name"` -} - -// CreateProjectColumn creates a column for the specified (by number) project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#create-a-project-column -func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/%v/columns", projectID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// UpdateProjectColumn updates a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#update-a-project-column -func (s *ProjectsService) UpdateProjectColumn(ctx context.Context, columnID int, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - column := &ProjectColumn{} - resp, err := s.client.Do(ctx, req, column) - if err != nil { - return nil, resp, err - } - - return column, resp, nil -} - -// DeleteProjectColumn deletes a column from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#delete-a-project-column -func (s *ProjectsService) DeleteProjectColumn(ctx context.Context, columnID int) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectColumnMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectColumn method. -type ProjectColumnMoveOptions struct { - // Position can be one of "first", "last", or "after:", where - // is the ID of a column in the same project. (Required.) - Position string `json:"position"` -} - -// MoveProjectColumn moves a column within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/columns/#move-a-project-column -func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int, opt *ProjectColumnMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/%v/moves", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCard represents a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -type ProjectCard struct { - URL *string `json:"url,omitempty"` - ColumnURL *string `json:"column_url,omitempty"` - ContentURL *string `json:"content_url,omitempty"` - ID *int `json:"id,omitempty"` - Note *string `json:"note,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - - // The following fields are only populated by Webhook events. - ColumnID *int `json:"column_id,omitempty"` -} - -// ListProjectCards lists the cards in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#list-project-cards -func (s *ProjectsService) ListProjectCards(ctx context.Context, columnID int, opt *ListOptions) ([]*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - cards := []*ProjectCard{} - resp, err := s.client.Do(ctx, req, &cards) - if err != nil { - return nil, resp, err - } - - return cards, resp, nil -} - -// GetProjectCard gets a card in a column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card -func (s *ProjectsService) GetProjectCard(ctx context.Context, columnID int) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", columnID) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// ProjectCardOptions specifies the parameters to the -// ProjectsService.CreateProjectCard and -// ProjectsService.UpdateProjectCard methods. -type ProjectCardOptions struct { - // The note of the card. Note and ContentID are mutually exclusive. - Note string `json:"note,omitempty"` - // The ID (not Number) of the Issue or Pull Request to associate with this card. - // Note and ContentID are mutually exclusive. - ContentID int `json:"content_id,omitempty"` - // The type of content to associate with this card. Possible values are: "Issue", "PullRequest". - ContentType string `json:"content_type,omitempty"` -} - -// CreateProjectCard creates a card in the specified column of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#create-a-project-card -func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/%v/cards", columnID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// UpdateProjectCard updates a card of a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#update-a-project-card -func (s *ProjectsService) UpdateProjectCard(ctx context.Context, cardID int, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("PATCH", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - card := &ProjectCard{} - resp, err := s.client.Do(ctx, req, card) - if err != nil { - return nil, resp, err - } - - return card, resp, nil -} - -// DeleteProjectCard deletes a card from a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#delete-a-project-card -func (s *ProjectsService) DeleteProjectCard(ctx context.Context, cardID int) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} - -// ProjectCardMoveOptions specifies the parameters to the -// ProjectsService.MoveProjectCard method. -type ProjectCardMoveOptions struct { - // Position can be one of "top", "bottom", or "after:", where - // is the ID of a card in the same project. - Position string `json:"position"` - // ColumnID is the ID of a column in the same project. Note that ColumnID - // is required when using Position "after:" when that card is in - // another column; otherwise it is optional. - ColumnID int `json:"column_id,omitempty"` -} - -// MoveProjectCard moves a card within a GitHub Project. -// -// GitHub API docs: https://developer.github.com/v3/projects/cards/#move-a-project-card -func (s *ProjectsService) MoveProjectCard(ctx context.Context, cardID int, opt *ProjectCardMoveOptions) (*Response, error) { - u := fmt.Sprintf("projects/columns/cards/%v/moves", cardID) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls.go b/vendor/github.com/google/go-github/github/pulls.go deleted file mode 100644 index b5a611b0be..0000000000 --- a/vendor/github.com/google/go-github/github/pulls.go +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "bytes" - "context" - "fmt" - "time" -) - -// PullRequestsService handles communication with the pull request related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/pulls/ -type PullRequestsService service - -// PullRequest represents a GitHub pull request on a repository. -type PullRequest struct { - ID *int `json:"id,omitempty"` - Number *int `json:"number,omitempty"` - State *string `json:"state,omitempty"` - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - ClosedAt *time.Time `json:"closed_at,omitempty"` - MergedAt *time.Time `json:"merged_at,omitempty"` - User *User `json:"user,omitempty"` - Merged *bool `json:"merged,omitempty"` - Mergeable *bool `json:"mergeable,omitempty"` - MergedBy *User `json:"merged_by,omitempty"` - MergeCommitSHA *string `json:"merge_commit_sha,omitempty"` - Comments *int `json:"comments,omitempty"` - Commits *int `json:"commits,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - ChangedFiles *int `json:"changed_files,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - IssueURL *string `json:"issue_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - ReviewCommentsURL *string `json:"review_comments_url,omitempty"` - ReviewCommentURL *string `json:"review_comment_url,omitempty"` - Assignee *User `json:"assignee,omitempty"` - Assignees []*User `json:"assignees,omitempty"` - Milestone *Milestone `json:"milestone,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` - - Head *PullRequestBranch `json:"head,omitempty"` - Base *PullRequestBranch `json:"base,omitempty"` -} - -func (p PullRequest) String() string { - return Stringify(p) -} - -// PullRequestBranch represents a base or head branch in a GitHub pull request. -type PullRequestBranch struct { - Label *string `json:"label,omitempty"` - Ref *string `json:"ref,omitempty"` - SHA *string `json:"sha,omitempty"` - Repo *Repository `json:"repo,omitempty"` - User *User `json:"user,omitempty"` -} - -// PullRequestListOptions specifies the optional parameters to the -// PullRequestsService.List method. -type PullRequestListOptions struct { - // State filters pull requests based on their state. Possible values are: - // open, closed. Default is "open". - State string `url:"state,omitempty"` - - // Head filters pull requests by head user and branch name in the format of: - // "user:ref-name". - Head string `url:"head,omitempty"` - - // Base filters pull requests by base branch name. - Base string `url:"base,omitempty"` - - // Sort specifies how to sort pull requests. Possible values are: created, - // updated, popularity, long-running. Default is "created". - Sort string `url:"sort,omitempty"` - - // Direction in which to sort pull requests. Possible values are: asc, desc. - // If Sort is "created" or not specified, Default is "desc", otherwise Default - // is "asc" - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the pull requests for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests -func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pulls []*PullRequest - resp, err := s.client.Do(ctx, req, &pulls) - if err != nil { - return nil, resp, err - } - - return pulls, resp, nil -} - -// Get a single pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-a-single-pull-request -func (s *PullRequestsService) Get(ctx context.Context, owner string, repo string, number int) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - pull := new(PullRequest) - resp, err := s.client.Do(ctx, req, pull) - if err != nil { - return nil, resp, err - } - - return pull, resp, nil -} - -// GetRaw gets raw (diff or patch) format of a pull request. -func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opt RawOptions) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - - switch opt.Type { - case Diff: - req.Header.Set("Accept", mediaTypeV3Diff) - case Patch: - req.Header.Set("Accept", mediaTypeV3Patch) - default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) - } - - ret := new(bytes.Buffer) - resp, err := s.client.Do(ctx, req, ret) - if err != nil { - return "", resp, err - } - - return ret.String(), resp, nil -} - -// NewPullRequest represents a new pull request to be created. -type NewPullRequest struct { - Title *string `json:"title,omitempty"` - Head *string `json:"head,omitempty"` - Base *string `json:"base,omitempty"` - Body *string `json:"body,omitempty"` - Issue *int `json:"issue,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Create a new pull request on the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#create-a-pull-request -func (s *PullRequestsService) Create(ctx context.Context, owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - req, err := s.client.NewRequest("POST", u, pull) - if err != nil { - return nil, nil, err - } - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -type pullRequestUpdate struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - State *string `json:"state,omitempty"` - Base *string `json:"base,omitempty"` - MaintainerCanModify *bool `json:"maintainer_can_modify,omitempty"` -} - -// Edit a pull request. -// pull must not be nil. -// -// The following fields are editable: Title, Body, State, Base.Ref and MaintainerCanModify. -// Base.Ref updates the base branch of the pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#update-a-pull-request -func (s *PullRequestsService) Edit(ctx context.Context, owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error) { - if pull == nil { - return nil, nil, fmt.Errorf("pull must be provided") - } - - u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) - - update := &pullRequestUpdate{ - Title: pull.Title, - Body: pull.Body, - State: pull.State, - MaintainerCanModify: pull.MaintainerCanModify, - } - if pull.Base != nil { - update.Base = pull.Base.Ref - } - - req, err := s.client.NewRequest("PATCH", u, update) - if err != nil { - return nil, nil, err - } - - p := new(PullRequest) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListCommits lists the commits in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request -func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/commits", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// ListFiles lists the files in a pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files -func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/files", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var commitFiles []*CommitFile - resp, err := s.client.Do(ctx, req, &commitFiles) - if err != nil { - return nil, resp, err - } - - return commitFiles, resp, nil -} - -// IsMerged checks if a pull request has been merged. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged -func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo string, number int) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - merged, err := parseBoolResponse(err) - return merged, resp, err -} - -// PullRequestMergeResult represents the result of merging a pull request. -type PullRequestMergeResult struct { - SHA *string `json:"sha,omitempty"` - Merged *bool `json:"merged,omitempty"` - Message *string `json:"message,omitempty"` -} - -// PullRequestOptions lets you define how a pull request will be merged. -type PullRequestOptions struct { - CommitTitle string // Extra detail to append to automatic commit message. (Optional.) - SHA string // SHA that pull request head must match to allow merge. (Optional.) - - // The merge method to use. Possible values include: "merge", "squash", and "rebase" with the default being merge. (Optional.) - MergeMethod string -} - -type pullRequestMergeRequest struct { - CommitMessage string `json:"commit_message"` - CommitTitle string `json:"commit_title,omitempty"` - MergeMethod string `json:"merge_method,omitempty"` - SHA string `json:"sha,omitempty"` -} - -// Merge a pull request (Merge Button™). -// commitMessage is the title for the automatic commit message. -// -// GitHub API docs: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade -func (s *PullRequestsService) Merge(ctx context.Context, owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/merge", owner, repo, number) - - pullRequestBody := &pullRequestMergeRequest{CommitMessage: commitMessage} - if options != nil { - pullRequestBody.CommitTitle = options.CommitTitle - pullRequestBody.MergeMethod = options.MergeMethod - pullRequestBody.SHA = options.SHA - } - req, err := s.client.NewRequest("PUT", u, pullRequestBody) - if err != nil { - return nil, nil, err - } - - mergeResult := new(PullRequestMergeResult) - resp, err := s.client.Do(ctx, req, mergeResult) - if err != nil { - return nil, resp, err - } - - return mergeResult, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/pulls_comments.go b/vendor/github.com/google/go-github/github/pulls_comments.go deleted file mode 100644 index bc0bc2d4a2..0000000000 --- a/vendor/github.com/google/go-github/github/pulls_comments.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestComment represents a comment left on a pull request. -type PullRequestComment struct { - ID *int `json:"id,omitempty"` - InReplyTo *int `json:"in_reply_to,omitempty"` - Body *string `json:"body,omitempty"` - Path *string `json:"path,omitempty"` - DiffHunk *string `json:"diff_hunk,omitempty"` - Position *int `json:"position,omitempty"` - OriginalPosition *int `json:"original_position,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - OriginalCommitID *string `json:"original_commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` -} - -func (p PullRequestComment) String() string { - return Stringify(p) -} - -// PullRequestListCommentsOptions specifies the optional parameters to the -// PullRequestsService.ListComments method. -type PullRequestListCommentsOptions struct { - // Sort specifies how to sort comments. Possible values are: created, updated. - Sort string `url:"sort,omitempty"` - - // Direction in which to sort comments. Possible values are: asc, desc. - Direction string `url:"direction,omitempty"` - - // Since filters comments by time. - Since time.Time `url:"since,omitempty"` - - ListOptions -} - -// ListComments lists all comments on the specified pull request. Specifying a -// pull request number of 0 will return all comments on all pull requests for -// the repository. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request -func (s *PullRequestsService) ListComments(ctx context.Context, owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error) { - var u string - if number == 0 { - u = fmt.Sprintf("repos/%v/%v/pulls/comments", owner, repo) - } else { - u = fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// GetComment fetches the specified pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment -func (s *PullRequestsService) GetComment(ctx context.Context, owner string, repo string, number int) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - comment := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, comment) - if err != nil { - return nil, resp, err - } - - return comment, resp, nil -} - -// CreateComment creates a new comment on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment -func (s *PullRequestsService) CreateComment(ctx context.Context, owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// EditComment updates a pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#edit-a-comment -func (s *PullRequestsService) EditComment(ctx context.Context, owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(PullRequestComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a pull request comment. -// -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#delete-a-comment -func (s *PullRequestsService) DeleteComment(ctx context.Context, owner string, repo string, number int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%d", owner, repo, number) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviewers.go b/vendor/github.com/google/go-github/github/pulls_reviewers.go deleted file mode 100644 index bd94a6599b..0000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviewers.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// RequestReviewers creates a review request for the provided GitHub users for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#create-a-review-request -func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo string, number int, logins []string) (*PullRequest, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - - reviewers := struct { - Reviewers []string `json:"reviewers,omitempty"` - }{ - Reviewers: logins, - } - req, err := s.client.NewRequest("POST", u, &reviewers) - if err != nil { - return nil, nil, err - } - - r := new(PullRequest) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// ListReviewers lists users whose reviews have been requested on the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#list-review-requests -func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/requested_reviewers", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// RemoveReviewers removes the review request for the provided GitHub users for the specified pull request. -// -// GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#delete-a-review-request -func (s *PullRequestsService) RemoveReviewers(ctx context.Context, owner, repo string, number int, logins []string) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - - reviewers := struct { - Reviewers []string `json:"reviewers,omitempty"` - }{ - Reviewers: logins, - } - req, err := s.client.NewRequest("DELETE", u, &reviewers) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, reviewers) -} diff --git a/vendor/github.com/google/go-github/github/pulls_reviews.go b/vendor/github.com/google/go-github/github/pulls_reviews.go deleted file mode 100644 index c071338dab..0000000000 --- a/vendor/github.com/google/go-github/github/pulls_reviews.go +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// PullRequestReview represents a review of a pull request. -type PullRequestReview struct { - ID *int `json:"id,omitempty"` - User *User `json:"user,omitempty"` - Body *string `json:"body,omitempty"` - SubmittedAt *time.Time `json:"submitted_at,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - PullRequestURL *string `json:"pull_request_url,omitempty"` - State *string `json:"state,omitempty"` -} - -func (p PullRequestReview) String() string { - return Stringify(p) -} - -// DraftReviewComment represents a comment part of the review. -type DraftReviewComment struct { - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` - Body *string `json:"body,omitempty"` -} - -func (c DraftReviewComment) String() string { - return Stringify(c) -} - -// PullRequestReviewRequest represents a request to create a review. -type PullRequestReviewRequest struct { - Body *string `json:"body,omitempty"` - Event *string `json:"event,omitempty"` - Comments []*DraftReviewComment `json:"comments,omitempty"` -} - -func (r PullRequestReviewRequest) String() string { - return Stringify(r) -} - -// PullRequestReviewDismissalRequest represents a request to dismiss a review. -type PullRequestReviewDismissalRequest struct { - Message *string `json:"message,omitempty"` -} - -func (r PullRequestReviewDismissalRequest) String() string { - return Stringify(r) -} - -// ListReviews lists all reviews on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request -func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var reviews []*PullRequestReview - resp, err := s.client.Do(ctx, req, &reviews) - if err != nil { - return nil, resp, err - } - - return reviews, resp, nil -} - -// GetReview fetches the specified pull request review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-a-single-review -func (s *PullRequestsService) GetReview(ctx context.Context, owner, repo string, number, reviewID int) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// DeletePendingReview deletes the specified pull request pending review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#delete-a-pending-review -func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, repo string, number, reviewID int) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, nil, err - } - - review := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, review) - if err != nil { - return nil, resp, err - } - - return review, resp, nil -} - -// ListReviewComments lists all the comments for the specified review. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review -func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number, reviewID int, opt *ListOptions) ([]*PullRequestComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/comments", owner, repo, number, reviewID) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var comments []*PullRequestComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateReview creates a new review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#create-a-pull-request-review -func (s *PullRequestsService) CreateReview(ctx context.Context, owner, repo string, number int, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// SubmitReview submits a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#submit-a-pull-request-review -func (s *PullRequestsService) SubmitReview(ctx context.Context, owner, repo string, number, reviewID int, review *PullRequestReviewRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/events", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("POST", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// DismissReview dismisses a specified review on the specified pull request. -// -// TODO: Follow up with GitHub support about an issue with this method's -// returned error format and remove this comment once it's fixed. -// Read more about it here - https://github.com/google/go-github/issues/540 -// -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#dismiss-a-pull-request-review -func (s *PullRequestsService) DismissReview(ctx context.Context, owner, repo string, number, reviewID int, review *PullRequestReviewDismissalRequest) (*PullRequestReview, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/dismissals", owner, repo, number, reviewID) - - req, err := s.client.NewRequest("PUT", u, review) - if err != nil { - return nil, nil, err - } - - r := new(PullRequestReview) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/reactions.go b/vendor/github.com/google/go-github/github/reactions.go deleted file mode 100644 index 739413d716..0000000000 --- a/vendor/github.com/google/go-github/github/reactions.go +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ReactionsService provides access to the reactions-related functions in the -// GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/reactions/ -type ReactionsService service - -// Reaction represents a GitHub reaction. -type Reaction struct { - // ID is the Reaction ID. - ID *int `json:"id,omitempty"` - User *User `json:"user,omitempty"` - // Content is the type of reaction. - // Possible values are: - // "+1", "-1", "laugh", "confused", "heart", "hooray". - Content *string `json:"content,omitempty"` -} - -// Reactions represents a summary of GitHub reactions. -type Reactions struct { - TotalCount *int `json:"total_count,omitempty"` - PlusOne *int `json:"+1,omitempty"` - MinusOne *int `json:"-1,omitempty"` - Laugh *int `json:"laugh,omitempty"` - Confused *int `json:"confused,omitempty"` - Heart *int `json:"heart,omitempty"` - Hooray *int `json:"hooray,omitempty"` - URL *string `json:"url,omitempty"` -} - -func (r Reaction) String() string { - return Stringify(r) -} - -// ListCommentReactions lists the reactions for a commit comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment -func (s *ReactionsService) ListCommentReactions(ctx context.Context, owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateCommentReaction creates a reaction for a commit comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-commit-comment -func (s ReactionsService) CreateCommentReaction(ctx context.Context, owner, repo string, id int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueReactions lists the reactions for an issue. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue -func (s *ReactionsService) ListIssueReactions(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueReaction creates a reaction for an issue. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue -func (s ReactionsService) CreateIssueReaction(ctx context.Context, owner, repo string, number int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListIssueCommentReactions lists the reactions for an issue comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListIssueCommentReactions(ctx context.Context, owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreateIssueCommentReaction creates a reaction for an issue comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreateIssueCommentReaction(ctx context.Context, owner, repo string, id int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// ListPullRequestCommentReactions lists the reactions for a pull request review comment. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListPullRequestCommentReactions(ctx context.Context, owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var m []*Reaction - resp, err := s.client.Do(ctx, req, &m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// CreatePullRequestCommentReaction creates a reaction for a pull request review comment. -// Note that if you have already created a reaction of type content, the -// previously created reaction will be returned with Status: 200 OK. -// -// GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment -func (s ReactionsService) CreatePullRequestCommentReaction(ctx context.Context, owner, repo string, id int, content string) (*Reaction, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - - body := &Reaction{Content: String(content)} - req, err := s.client.NewRequest("POST", u, body) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - m := &Reaction{} - resp, err := s.client.Do(ctx, req, m) - if err != nil { - return nil, resp, err - } - - return m, resp, nil -} - -// DeleteReaction deletes a reaction. -// -// GitHub API docs: https://developer.github.com/v3/reaction/reactions/#delete-a-reaction-archive -func (s *ReactionsService) DeleteReaction(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("reactions/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos.go b/vendor/github.com/google/go-github/github/repos.go deleted file mode 100644 index 10e46f42d9..0000000000 --- a/vendor/github.com/google/go-github/github/repos.go +++ /dev/null @@ -1,1023 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "encoding/json" - "fmt" - "strings" -) - -// RepositoriesService handles communication with the repository related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/repos/ -type RepositoriesService service - -// Repository represents a GitHub repository. -type Repository struct { - ID *int `json:"id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Description *string `json:"description,omitempty"` - Homepage *string `json:"homepage,omitempty"` - CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - MirrorURL *string `json:"mirror_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` - Language *string `json:"language,omitempty"` - Fork *bool `json:"fork"` - ForksCount *int `json:"forks_count,omitempty"` - NetworkCount *int `json:"network_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - SubscribersCount *int `json:"subscribers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Size *int `json:"size,omitempty"` - AutoInit *bool `json:"auto_init,omitempty"` - Parent *Repository `json:"parent,omitempty"` - Source *Repository `json:"source,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Permissions *map[string]bool `json:"permissions,omitempty"` - AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` - AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` - AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` - Topics []string `json:"topics,omitempty"` - - // Only provided when using RepositoriesService.Get while in preview - License *License `json:"license,omitempty"` - - // Additional mutable fields when creating and editing a repository - Private *bool `json:"private"` - HasIssues *bool `json:"has_issues"` - HasWiki *bool `json:"has_wiki"` - HasPages *bool `json:"has_pages"` - HasDownloads *bool `json:"has_downloads"` - LicenseTemplate *string `json:"license_template,omitempty"` - GitignoreTemplate *string `json:"gitignore_template,omitempty"` - - // Creating an organization repository. Required for non-owners. - TeamID *int `json:"team_id"` - - // API URLs - URL *string `json:"url,omitempty"` - ArchiveURL *string `json:"archive_url,omitempty"` - AssigneesURL *string `json:"assignees_url,omitempty"` - BlobsURL *string `json:"blobs_url,omitempty"` - BranchesURL *string `json:"branches_url,omitempty"` - CollaboratorsURL *string `json:"collaborators_url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - CommitsURL *string `json:"commits_url,omitempty"` - CompareURL *string `json:"compare_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` - ContributorsURL *string `json:"contributors_url,omitempty"` - DeploymentsURL *string `json:"deployments_url,omitempty"` - DownloadsURL *string `json:"downloads_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ForksURL *string `json:"forks_url,omitempty"` - GitCommitsURL *string `json:"git_commits_url,omitempty"` - GitRefsURL *string `json:"git_refs_url,omitempty"` - GitTagsURL *string `json:"git_tags_url,omitempty"` - HooksURL *string `json:"hooks_url,omitempty"` - IssueCommentURL *string `json:"issue_comment_url,omitempty"` - IssueEventsURL *string `json:"issue_events_url,omitempty"` - IssuesURL *string `json:"issues_url,omitempty"` - KeysURL *string `json:"keys_url,omitempty"` - LabelsURL *string `json:"labels_url,omitempty"` - LanguagesURL *string `json:"languages_url,omitempty"` - MergesURL *string `json:"merges_url,omitempty"` - MilestonesURL *string `json:"milestones_url,omitempty"` - NotificationsURL *string `json:"notifications_url,omitempty"` - PullsURL *string `json:"pulls_url,omitempty"` - ReleasesURL *string `json:"releases_url,omitempty"` - StargazersURL *string `json:"stargazers_url,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - SubscribersURL *string `json:"subscribers_url,omitempty"` - SubscriptionURL *string `json:"subscription_url,omitempty"` - TagsURL *string `json:"tags_url,omitempty"` - TreesURL *string `json:"trees_url,omitempty"` - TeamsURL *string `json:"teams_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (r Repository) String() string { - return Stringify(r) -} - -// RepositoryListOptions specifies the optional parameters to the -// RepositoriesService.List method. -type RepositoryListOptions struct { - // Visibility of repositories to list. Can be one of all, public, or private. - // Default: all - Visibility string `url:"visibility,omitempty"` - - // List repos of given affiliation[s]. - // Comma-separated list of values. Can include: - // * owner: Repositories that are owned by the authenticated user. - // * collaborator: Repositories that the user has been added to as a - // collaborator. - // * organization_member: Repositories that the user has access to through - // being a member of an organization. This includes every repository on - // every team that the user is on. - // Default: owner,collaborator,organization_member - Affiliation string `url:"affiliation,omitempty"` - - // Type of repositories to list. - // Can be one of all, owner, public, private, member. Default: all - // Will cause a 422 error if used in the same request as visibility or - // affiliation. - Type string `url:"type,omitempty"` - - // How to sort the repository list. Can be one of created, updated, pushed, - // full_name. Default: full_name - Sort string `url:"sort,omitempty"` - - // Direction in which to sort repositories. Can be one of asc or desc. - // Default: when using full_name: asc; otherwise desc - Direction string `url:"direction,omitempty"` - - ListOptions -} - -// List the repositories for a user. Passing the empty string will list -// repositories for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-user-repositories -func (s *RepositoriesService) List(ctx context.Context, user string, opt *RepositoryListOptions) ([]*Repository, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/repos", user) - } else { - u = "user/repos" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListByOrgOptions specifies the optional parameters to the -// RepositoriesService.ListByOrg method. -type RepositoryListByOrgOptions struct { - // Type of repositories to list. Possible values are: all, public, private, - // forks, sources, member. Default is "all". - Type string `url:"type,omitempty"` - - ListOptions -} - -// ListByOrg lists the repositories for an organization. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-organization-repositories -func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("orgs/%v/repos", org) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept headers when APIs fully launch. - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryListAllOptions specifies the optional parameters to the -// RepositoriesService.ListAll method. -type RepositoryListAllOptions struct { - // ID of the last repository seen - Since int `url:"since,omitempty"` - - ListOptions -} - -// ListAll lists all GitHub repositories in the order that they were created. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-public-repositories -func (s *RepositoriesService) ListAll(ctx context.Context, opt *RepositoryListAllOptions) ([]*Repository, *Response, error) { - u, err := addOptions("repositories", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// Create a new repository. If an organization is specified, the new -// repository will be created under that org. If the empty string is -// specified, it will be created for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/#create -func (s *RepositoriesService) Create(ctx context.Context, org string, repo *Repository) (*Repository, *Response, error) { - var u string - if org != "" { - u = fmt.Sprintf("orgs/%v/repos", org) - } else { - u = "user/repos" - } - - req, err := s.client.NewRequest("POST", u, repo) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Get fetches a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get -func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when the license support fully launches - // https://developer.github.com/v3/licenses/#get-a-repositorys-license - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} - req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// GetCodeOfConduct gets the contents of a repository's code of conduct. -// -// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#get-the-contents-of-a-repositorys-code-of-conduct -func (s *RepositoriesService) GetCodeOfConduct(ctx context.Context, owner, repo string) (*CodeOfConduct, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/code_of_conduct", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCodesOfConductPreview) - - coc := new(CodeOfConduct) - resp, err := s.client.Do(ctx, req, coc) - if err != nil { - return nil, resp, err - } - - return coc, resp, nil -} - -// GetByID fetches a repository. -// -// Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. -func (s *RepositoriesService) GetByID(ctx context.Context, id int) (*Repository, *Response, error) { - u := fmt.Sprintf("repositories/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when the license support fully launches - // https://developer.github.com/v3/licenses/#get-a-repositorys-license - req.Header.Set("Accept", mediaTypeLicensesPreview) - - repository := new(Repository) - resp, err := s.client.Do(ctx, req, repository) - if err != nil { - return nil, resp, err - } - - return repository, resp, nil -} - -// Edit updates a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#edit -func (s *RepositoriesService) Edit(ctx context.Context, owner, repo string, repository *Repository) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("PATCH", u, repository) - if err != nil { - return nil, nil, err - } - - r := new(Repository) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// Delete a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#delete-a-repository -func (s *RepositoriesService) Delete(ctx context.Context, owner, repo string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v", owner, repo) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Contributor represents a repository contributor -type Contributor struct { - Login *string `json:"login,omitempty"` - ID *int `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin"` - Contributions *int `json:"contributions,omitempty"` -} - -// ListContributorsOptions specifies the optional parameters to the -// RepositoriesService.ListContributors method. -type ListContributorsOptions struct { - // Include anonymous contributors in results or not - Anon string `url:"anon,omitempty"` - - ListOptions -} - -// ListContributors lists contributors for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-contributors -func (s *RepositoriesService) ListContributors(ctx context.Context, owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/contributors", owner, repository) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributor []*Contributor - resp, err := s.client.Do(ctx, req, &contributor) - if err != nil { - return nil, nil, err - } - - return contributor, resp, nil -} - -// ListLanguages lists languages for the specified repository. The returned map -// specifies the languages and the number of bytes of code written in that -// language. For example: -// -// { -// "C": 78769, -// "Python": 7769 -// } -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-languages -func (s *RepositoriesService) ListLanguages(ctx context.Context, owner string, repo string) (map[string]int, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/languages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - languages := make(map[string]int) - resp, err := s.client.Do(ctx, req, &languages) - if err != nil { - return nil, resp, err - } - - return languages, resp, nil -} - -// ListTeams lists the teams for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-teams -func (s *RepositoriesService) ListTeams(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/teams", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var teams []*Team - resp, err := s.client.Do(ctx, req, &teams) - if err != nil { - return nil, resp, err - } - - return teams, resp, nil -} - -// RepositoryTag represents a repository tag. -type RepositoryTag struct { - Name *string `json:"name,omitempty"` - Commit *Commit `json:"commit,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` -} - -// ListTags lists tags for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-tags -func (s *RepositoriesService) ListTags(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/tags", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var tags []*RepositoryTag - resp, err := s.client.Do(ctx, req, &tags) - if err != nil { - return nil, resp, err - } - - return tags, resp, nil -} - -// Branch represents a repository branch -type Branch struct { - Name *string `json:"name,omitempty"` - Commit *RepositoryCommit `json:"commit,omitempty"` - Protected *bool `json:"protected,omitempty"` -} - -// Protection represents a repository branch's protection. -type Protection struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcement `json:"required_pull_request_reviews"` - EnforceAdmins *AdminEnforcement `json:"enforce_admins"` - Restrictions *BranchRestrictions `json:"restrictions"` -} - -// ProtectionRequest represents a request to create/edit a branch's protection. -type ProtectionRequest struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *PullRequestReviewsEnforcementRequest `json:"required_pull_request_reviews"` - EnforceAdmins bool `json:"enforce_admins"` - Restrictions *BranchRestrictionsRequest `json:"restrictions"` -} - -// RequiredStatusChecks represents the protection status of a individual branch. -type RequiredStatusChecks struct { - // Require branches to be up to date before merging. (Required.) - Strict bool `json:"strict"` - // The list of status checks to require in order to merge into this - // branch. (Required; use []string{} instead of nil for empty list.) - Contexts []string `json:"contexts"` -} - -// PullRequestReviewsEnforcement represents the pull request reviews enforcement of a protected branch. -type PullRequestReviewsEnforcement struct { - // Specifies which users and teams can dismiss pull requets reviews. - DismissalRestrictions DismissalRestrictions `json:"dismissal_restrictions"` - // Specifies if approved reviews are dismissed automatically, when a new commit is pushed. - DismissStaleReviews bool `json:"dismiss_stale_reviews"` -} - -// PullRequestReviewsEnforcementRequest represents request to set the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcement above -// because the request structure is different from the response structure. -type PullRequestReviewsEnforcementRequest struct { - // Specifies which users and teams should be allowed to dismiss pull requets reviews. Can be nil to disable the restrictions. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. (Required) - DismissStaleReviews bool `json:"dismiss_stale_reviews"` -} - -// MarshalJSON implements the json.Marshaler interface. -// Converts nil value of PullRequestReviewsEnforcementRequest.DismissalRestrictionsRequest to empty array -func (req PullRequestReviewsEnforcementRequest) MarshalJSON() ([]byte, error) { - if req.DismissalRestrictionsRequest == nil { - newReq := struct { - R []interface{} `json:"dismissal_restrictions"` - D bool `json:"dismiss_stale_reviews"` - }{ - R: []interface{}{}, - D: req.DismissStaleReviews, - } - return json.Marshal(newReq) - } - newReq := struct { - R *DismissalRestrictionsRequest `json:"dismissal_restrictions"` - D bool `json:"dismiss_stale_reviews"` - }{ - R: req.DismissalRestrictionsRequest, - D: req.DismissStaleReviews, - } - return json.Marshal(newReq) -} - -// PullRequestReviewsEnforcementUpdate represents request to patch the pull request review -// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcementRequest above -// because the patch request does not require all fields to be initialized. -type PullRequestReviewsEnforcementUpdate struct { - // Specifies which users and teams can dismiss pull requets reviews. Can be ommitted. - DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions,omitempty"` - // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. Can be ommited. - DismissStaleReviews *bool `json:"dismiss_stale_reviews,omitempty"` -} - -// AdminEnforcement represents the configuration to enforce required status checks for repository administrators. -type AdminEnforcement struct { - URL *string `json:"url,omitempty"` - Enabled bool `json:"enabled"` -} - -// BranchRestrictions represents the restriction that only certain users or -// teams may push to a branch. -type BranchRestrictions struct { - // The list of user logins with push access. - Users []*User `json:"users"` - // The list of team slugs with push access. - Teams []*Team `json:"teams"` -} - -// BranchRestrictionsRequest represents the request to create/edit the -// restriction that only certain users or teams may push to a branch. It is -// separate from BranchRestrictions above because the request structure is -// different from the response structure. -type BranchRestrictionsRequest struct { - // The list of user logins with push access. (Required; use []string{} instead of nil for empty list.) - Users []string `json:"users"` - // The list of team slugs with push access. (Required; use []string{} instead of nil for empty list.) - Teams []string `json:"teams"` -} - -// DismissalRestrictions specifies which users and teams can dismiss pull request reviews. -type DismissalRestrictions struct { - // The list of users who can dimiss pull request reviews. - Users []*User `json:"users"` - // The list of teams which can dismiss pull request reviews. - Teams []*Team `json:"teams"` -} - -// DismissalRestrictionsRequest represents the request to create/edit the -// restriction to allows only specific users or teams to dimiss pull request reviews. It is -// separate from DismissalRestrictions above because the request structure is -// different from the response structure. -type DismissalRestrictionsRequest struct { - // The list of user logins who can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) - Users []string `json:"users"` - // The list of team slugs which can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) - Teams []string `json:"teams"` -} - -// ListBranches lists branches for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-branches -func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - var branches []*Branch - resp, err := s.client.Do(ctx, req, &branches) - if err != nil { - return nil, resp, err - } - - return branches, resp, nil -} - -// GetBranch gets the specified branch for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#get-branch -func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch string) (*Branch, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - b := new(Branch) - resp, err := s.client.Do(ctx, req, b) - if err != nil { - return nil, resp, err - } - - return b, resp, nil -} - -// GetBranchProtection gets the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-branch-protection -func (s *RepositoriesService) GetBranchProtection(ctx context.Context, owner, repo, branch string) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// GetRequiredStatusChecks gets the required status checks for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-required-status-checks-of-protected-branch -func (s *RepositoriesService) GetRequiredStatusChecks(ctx context.Context, owner, repo, branch string) (*RequiredStatusChecks, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(RequiredStatusChecks) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// ListRequiredStatusChecksContexts lists the required status checks contexts for a given protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#list-required-status-checks-contexts-of-protected-branch -func (s *RepositoriesService) ListRequiredStatusChecksContexts(ctx context.Context, owner, repo, branch string) (contexts []string, resp *Response, err error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_status_checks/contexts", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - resp, err = s.client.Do(ctx, req, &contexts) - if err != nil { - return nil, resp, err - } - - return contexts, resp, nil -} - -// UpdateBranchProtection updates the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-branch-protection -func (s *RepositoriesService) UpdateBranchProtection(ctx context.Context, owner, repo, branch string, preq *ProtectionRequest) (*Protection, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("PUT", u, preq) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - p := new(Protection) - resp, err := s.client.Do(ctx, req, p) - if err != nil { - return nil, resp, err - } - - return p, resp, nil -} - -// RemoveBranchProtection removes the protection of a given branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-branch-protection -func (s *RepositoriesService) RemoveBranchProtection(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// License gets the contents of a repository's license if one is detected. -// -// GitHub API docs: https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license -func (s *RepositoriesService) License(ctx context.Context, owner, repo string) (*RepositoryLicense, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/license", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - r := &RepositoryLicense{} - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// GetPullRequestReviewEnforcement gets pull request review enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) GetPullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// UpdatePullRequestReviewEnforcement patches pull request review enforcement of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) UpdatePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string, patch *PullRequestReviewsEnforcementUpdate) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("PATCH", u, patch) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// DisableDismissalRestrictions disables dismissal restrictions of a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) DisableDismissalRestrictions(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - - data := struct { - R []interface{} `json:"dismissal_restrictions"` - }{[]interface{}{}} - - req, err := s.client.NewRequest("PATCH", u, data) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(PullRequestReviewsEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemovePullRequestReviewEnforcement removes pull request enforcement of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch -func (s *RepositoriesService) RemovePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// GetAdminEnforcement gets admin enforcement information of a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch -func (s *RepositoriesService) GetAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, nil -} - -// AddAdminEnforcement adds admin enforcement to a protected branch. -// It requires admin access and branch protection to be enabled. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch -func (s *RepositoriesService) AddAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - r := new(AdminEnforcement) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - - return r, resp, err -} - -// RemoveAdminEnforcement removes admin enforcement from a protected branch. -// -// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch -func (s *RepositoriesService) RemoveAdminEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) - - return s.client.Do(ctx, req, nil) -} - -// Topics represents a collection of repository topics. -type Topics struct { - Names []string `json:"names,omitempty"` -} - -// ListAllTopics lists topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#list-all-topics-for-a-repository -func (s *RepositoriesService) ListAllTopics(ctx context.Context, owner, repo string) (*Topics, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - topics := new(Topics) - resp, err := s.client.Do(ctx, req, topics) - if err != nil { - return nil, resp, err - } - - return topics, resp, nil -} - -// ReplaceAllTopics replaces topics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository -func (s *RepositoriesService) ReplaceAllTopics(ctx context.Context, owner, repo string, topics *Topics) (*Topics, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) - req, err := s.client.NewRequest("PUT", u, topics) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - t := new(Topics) - resp, err := s.client.Do(ctx, req, t) - if err != nil { - return nil, resp, err - } - - return t, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_collaborators.go b/vendor/github.com/google/go-github/github/repos_collaborators.go deleted file mode 100644 index 61b63318f4..0000000000 --- a/vendor/github.com/google/go-github/github/repos_collaborators.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListCollaborators lists the GitHub users that have access to the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list -func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsCollaborator checks whether the specified GitHub user has collaborator -// access to the given repo. -// Note: This will return false if the user is not a collaborator OR the user -// is not a GitHub user. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#get -func (s *RepositoriesService) IsCollaborator(ctx context.Context, owner, repo, user string) (bool, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - isCollab, err := parseBoolResponse(err) - return isCollab, resp, err -} - -// RepositoryPermissionLevel represents the permission level an organization -// member has for a given repository. -type RepositoryPermissionLevel struct { - // Possible values: "admin", "write", "read", "none" - Permission *string `json:"permission,omitempty"` - - User *User `json:"user,omitempty"` -} - -// GetPermissionLevel retrieves the specific permission level a collaborator has for a given repository. -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level -func (s *RepositoriesService) GetPermissionLevel(ctx context.Context, owner, repo, user string) (*RepositoryPermissionLevel, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v/permission", owner, repo, user) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - rpl := new(RepositoryPermissionLevel) - resp, err := s.client.Do(ctx, req, rpl) - if err != nil { - return nil, resp, err - } - return rpl, resp, nil -} - -// RepositoryAddCollaboratorOptions specifies the optional parameters to the -// RepositoriesService.AddCollaborator method. -type RepositoryAddCollaboratorOptions struct { - // Permission specifies the permission to grant the user on this repository. - // Possible values are: - // pull - team members can pull, but not push to or administer this repository - // push - team members can pull and push, but not administer this repository - // admin - team members can pull, push and administer this repository - // - // Default value is "push". This option is only valid for organization-owned repositories. - Permission string `json:"permission,omitempty"` -} - -// AddCollaborator sends an invitation to the specified GitHub user -// to become a collaborator to the given repo. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator -func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// RemoveCollaborator removes the specified GitHub user as collaborator from the given repo. -// Note: Does not return error if a valid user that is not a collaborator is removed. -// -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#remove-collaborator -func (s *RepositoriesService) RemoveCollaborator(ctx context.Context, owner, repo, user string) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_comments.go b/vendor/github.com/google/go-github/github/repos_comments.go deleted file mode 100644 index 4830ee2206..0000000000 --- a/vendor/github.com/google/go-github/github/repos_comments.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// RepositoryComment represents a comment for a commit, file, or line in a repository. -type RepositoryComment struct { - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - ID *int `json:"id,omitempty"` - CommitID *string `json:"commit_id,omitempty"` - User *User `json:"user,omitempty"` - Reactions *Reactions `json:"reactions,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - - // User-mutable fields - Body *string `json:"body"` - // User-initialized fields - Path *string `json:"path,omitempty"` - Position *int `json:"position,omitempty"` -} - -func (r RepositoryComment) String() string { - return Stringify(r) -} - -// ListComments lists all the comments for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository -func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// ListCommitComments lists all the comments for a given commit SHA. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit -func (s *RepositoriesService) ListCommitComments(ctx context.Context, owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - var comments []*RepositoryComment - resp, err := s.client.Do(ctx, req, &comments) - if err != nil { - return nil, resp, err - } - - return comments, resp, nil -} - -// CreateComment creates a comment for the given commit. -// Note: GitHub allows for comments to be created for non-existing files and positions. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#create-a-commit-comment -func (s *RepositoriesService) CreateComment(ctx context.Context, owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - req, err := s.client.NewRequest("POST", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// GetComment gets a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#get-a-single-commit-comment -func (s *RepositoriesService) GetComment(ctx context.Context, owner, repo string, id int) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeReactionsPreview) - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// UpdateComment updates the body of a single comment. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#update-a-commit-comment -func (s *RepositoriesService) UpdateComment(ctx context.Context, owner, repo string, id int, comment *RepositoryComment) (*RepositoryComment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, comment) - if err != nil { - return nil, nil, err - } - - c := new(RepositoryComment) - resp, err := s.client.Do(ctx, req, c) - if err != nil { - return nil, resp, err - } - - return c, resp, nil -} - -// DeleteComment deletes a single comment from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/comments/#delete-a-commit-comment -func (s *RepositoriesService) DeleteComment(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/comments/%v", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_commits.go b/vendor/github.com/google/go-github/github/repos_commits.go deleted file mode 100644 index 7ecf531046..0000000000 --- a/vendor/github.com/google/go-github/github/repos_commits.go +++ /dev/null @@ -1,209 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "bytes" - "context" - "fmt" - "time" -) - -// RepositoryCommit represents a commit in a repo. -// Note that it's wrapping a Commit, so author/committer information is in two places, -// but contain different details about them: in RepositoryCommit "github details", in Commit - "git details". -type RepositoryCommit struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - // Details about how many changes were made in this commit. Only filled in during GetCommit! - Stats *CommitStats `json:"stats,omitempty"` - // Details about which files, and how this commit touched. Only filled in during GetCommit! - Files []CommitFile `json:"files,omitempty"` -} - -func (r RepositoryCommit) String() string { - return Stringify(r) -} - -// CommitStats represents the number of additions / deletions from a file in a given RepositoryCommit or GistCommit. -type CommitStats struct { - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Total *int `json:"total,omitempty"` -} - -func (c CommitStats) String() string { - return Stringify(c) -} - -// CommitFile represents a file modified in a commit. -type CommitFile struct { - SHA *string `json:"sha,omitempty"` - Filename *string `json:"filename,omitempty"` - Additions *int `json:"additions,omitempty"` - Deletions *int `json:"deletions,omitempty"` - Changes *int `json:"changes,omitempty"` - Status *string `json:"status,omitempty"` - Patch *string `json:"patch,omitempty"` - BlobURL *string `json:"blob_url,omitempty"` - RawURL *string `json:"raw_url,omitempty"` - ContentsURL *string `json:"contents_url,omitempty"` -} - -func (c CommitFile) String() string { - return Stringify(c) -} - -// CommitsComparison is the result of comparing two commits. -// See CompareCommits() for details. -type CommitsComparison struct { - BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` - MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"` - - // Head can be 'behind' or 'ahead' - Status *string `json:"status,omitempty"` - AheadBy *int `json:"ahead_by,omitempty"` - BehindBy *int `json:"behind_by,omitempty"` - TotalCommits *int `json:"total_commits,omitempty"` - - Commits []RepositoryCommit `json:"commits,omitempty"` - - Files []CommitFile `json:"files,omitempty"` - - HTMLURL *string `json:"html_url,omitempty"` - PermalinkURL *string `json:"permalink_url,omitempty"` - DiffURL *string `json:"diff_url,omitempty"` - PatchURL *string `json:"patch_url,omitempty"` - URL *string `json:"url,omitempty"` // API URL. -} - -func (c CommitsComparison) String() string { - return Stringify(c) -} - -// CommitsListOptions specifies the optional parameters to the -// RepositoriesService.ListCommits method. -type CommitsListOptions struct { - // SHA or branch to start listing Commits from. - SHA string `url:"sha,omitempty"` - - // Path that should be touched by the returned Commits. - Path string `url:"path,omitempty"` - - // Author of by which to filter Commits. - Author string `url:"author,omitempty"` - - // Since when should Commits be included in the response. - Since time.Time `url:"since,omitempty"` - - // Until when should Commits be included in the response. - Until time.Time `url:"until,omitempty"` - - ListOptions -} - -// ListCommits lists the commits of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#list -func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var commits []*RepositoryCommit - resp, err := s.client.Do(ctx, req, &commits) - if err != nil { - return nil, resp, err - } - - return commits, resp, nil -} - -// GetCommit fetches the specified commit, including all details about it. -// todo: support media formats - https://github.com/google/go-github/issues/6 -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-a-single-commit -// See also: https://developer.github.com//v3/git/commits/#get-a-single-commit provides the same functionality -func (s *RepositoriesService) GetCommit(ctx context.Context, owner, repo, sha string) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} - -// GetCommitSHA1 gets the SHA-1 of a commit reference. If a last-known SHA1 is -// supplied and no new commits have occurred, a 304 Unmodified response is returned. -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference -func (s *RepositoriesService) GetCommitSHA1(ctx context.Context, owner, repo, ref, lastSHA string) (string, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, ref) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return "", nil, err - } - if lastSHA != "" { - req.Header.Set("If-None-Match", `"`+lastSHA+`"`) - } - - req.Header.Set("Accept", mediaTypeV3SHA) - - var buf bytes.Buffer - resp, err := s.client.Do(ctx, req, &buf) - if err != nil { - return "", resp, err - } - - return buf.String(), resp, nil -} - -// CompareCommits compares a range of commits with each other. -// todo: support media formats - https://github.com/google/go-github/issues/6 -// -// GitHub API docs: https://developer.github.com/v3/repos/commits/index.html#compare-two-commits -func (s *RepositoriesService) CompareCommits(ctx context.Context, owner, repo string, base, head string) (*CommitsComparison, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/compare/%v...%v", owner, repo, base, head) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - comp := new(CommitsComparison) - resp, err := s.client.Do(ctx, req, comp) - if err != nil { - return nil, resp, err - } - - return comp, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_community_health.go b/vendor/github.com/google/go-github/github/repos_community_health.go deleted file mode 100644 index b5c75d6f56..0000000000 --- a/vendor/github.com/google/go-github/github/repos_community_health.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// Metric represents the different fields for one file in community health files. -type Metric struct { - Name *string `json:"name"` - Key *string `json:"key"` - URL *string `json:"url"` - HTMLURL *string `json:"html_url"` -} - -// CommunityHealthFiles represents the different files in the community health metrics response. -type CommunityHealthFiles struct { - CodeOfConduct *Metric `json:"code_of_conduct"` - Contributing *Metric `json:"contributing"` - License *Metric `json:"license"` - Readme *Metric `json:"readme"` -} - -// CommunityHealthMetrics represents a response containing the community metrics of a repository. -type CommunityHealthMetrics struct { - HealthPercentage *int `json:"health_percentage"` - Files *CommunityHealthFiles `json:"files"` - UpdatedAt *time.Time `json:"updated_at"` -} - -// GetCommunityHealthMetrics retrieves all the community health metrics for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/community/#retrieve-community-health-metrics -func (s *RepositoriesService) GetCommunityHealthMetrics(ctx context.Context, owner, repo string) (*CommunityHealthMetrics, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/community/profile", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryCommunityHealthMetricsPreview) - - metrics := &CommunityHealthMetrics{} - resp, err := s.client.Do(ctx, req, metrics) - if err != nil { - return nil, resp, err - } - - return metrics, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_contents.go b/vendor/github.com/google/go-github/github/repos_contents.go deleted file mode 100644 index f9adaf7a03..0000000000 --- a/vendor/github.com/google/go-github/github/repos_contents.go +++ /dev/null @@ -1,266 +0,0 @@ -// Copyright 2013 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Repository contents API methods. -// GitHub API docs: https://developer.github.com/v3/repos/contents/ - -package github - -import ( - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "path" -) - -// RepositoryContent represents a file or directory in a github repository. -type RepositoryContent struct { - Type *string `json:"type,omitempty"` - Encoding *string `json:"encoding,omitempty"` - Size *int `json:"size,omitempty"` - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - // Content contains the actual file content, which may be encoded. - // Callers should call GetContent which will decode the content if - // necessary. - Content *string `json:"content,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - DownloadURL *string `json:"download_url,omitempty"` -} - -// RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentResponse struct { - Content *RepositoryContent `json:"content,omitempty"` - Commit `json:"commit,omitempty"` -} - -// RepositoryContentFileOptions specifies optional parameters for CreateFile, UpdateFile, and DeleteFile. -type RepositoryContentFileOptions struct { - Message *string `json:"message,omitempty"` - Content []byte `json:"content,omitempty"` // unencoded - SHA *string `json:"sha,omitempty"` - Branch *string `json:"branch,omitempty"` - Author *CommitAuthor `json:"author,omitempty"` - Committer *CommitAuthor `json:"committer,omitempty"` -} - -// RepositoryContentGetOptions represents an optional ref parameter, which can be a SHA, -// branch, or tag -type RepositoryContentGetOptions struct { - Ref string `url:"ref,omitempty"` -} - -// String converts RepositoryContent to a string. It's primarily for testing. -func (r RepositoryContent) String() string { - return Stringify(r) -} - -// GetContent returns the content of r, decoding it if necessary. -func (r *RepositoryContent) GetContent() (string, error) { - var encoding string - if r.Encoding != nil { - encoding = *r.Encoding - } - - switch encoding { - case "base64": - c, err := base64.StdEncoding.DecodeString(*r.Content) - return string(c), err - case "": - if r.Content == nil { - return "", nil - } - return *r.Content, nil - default: - return "", fmt.Errorf("unsupported content encoding: %v", encoding) - } -} - -// GetReadme gets the Readme file for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-the-readme -func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/readme", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - readme := new(RepositoryContent) - resp, err := s.client.Do(ctx, req, readme) - if err != nil { - return nil, resp, err - } - return readme, resp, nil -} - -// DownloadContents returns an io.ReadCloser that reads the contents of the -// specified file. This function will work with files of any size, as opposed -// to GetContents which is limited to 1 Mb files. It is the caller's -// responsibility to close the ReadCloser. -func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) { - dir := path.Dir(filepath) - filename := path.Base(filepath) - _, dirContents, _, err := s.GetContents(ctx, owner, repo, dir, opt) - if err != nil { - return nil, err - } - for _, contents := range dirContents { - if *contents.Name == filename { - if contents.DownloadURL == nil || *contents.DownloadURL == "" { - return nil, fmt.Errorf("No download link found for %s", filepath) - } - resp, err := s.client.client.Get(*contents.DownloadURL) - if err != nil { - return nil, err - } - return resp.Body, nil - } - } - return nil, fmt.Errorf("No file named %s found in %s", filename, dir) -} - -// GetContents can return either the metadata and content of a single file -// (when path references a file) or the metadata of all the files and/or -// subdirectories of a directory (when path references a directory). To make it -// easy to distinguish between both result types and to mimic the API as much -// as possible, both result types will be returned but only one will contain a -// value and the other will be nil. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-contents -func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error) { - escapedPath := (&url.URL{Path: path}).String() - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, escapedPath) - u, err = addOptions(u, opt) - if err != nil { - return nil, nil, nil, err - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, nil, err - } - var rawJSON json.RawMessage - resp, err = s.client.Do(ctx, req, &rawJSON) - if err != nil { - return nil, nil, resp, err - } - fileUnmarshalError := json.Unmarshal(rawJSON, &fileContent) - if fileUnmarshalError == nil { - return fileContent, nil, resp, nil - } - directoryUnmarshalError := json.Unmarshal(rawJSON, &directoryContent) - if directoryUnmarshalError == nil { - return nil, directoryContent, resp, nil - } - return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s", fileUnmarshalError, directoryUnmarshalError) -} - -// CreateFile creates a new file in a repository at the given path and returns -// the commit and file metadata. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#create-a-file -func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - createResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, createResponse) - if err != nil { - return nil, resp, err - } - return createResponse, resp, nil -} - -// UpdateFile updates a file in a repository at the given path and returns the -// commit and file metadata. Requires the blob SHA of the file being updated. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#update-a-file -func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) - if err != nil { - return nil, nil, err - } - updateResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, updateResponse) - if err != nil { - return nil, resp, err - } - return updateResponse, resp, nil -} - -// DeleteFile deletes a file from a repository and returns the commit. -// Requires the blob SHA of the file to be deleted. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#delete-a-file -func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("DELETE", u, opt) - if err != nil { - return nil, nil, err - } - deleteResponse := new(RepositoryContentResponse) - resp, err := s.client.Do(ctx, req, deleteResponse) - if err != nil { - return nil, resp, err - } - return deleteResponse, resp, nil -} - -// archiveFormat is used to define the archive type when calling GetArchiveLink. -type archiveFormat string - -const ( - // Tarball specifies an archive in gzipped tar format. - Tarball archiveFormat = "tarball" - - // Zipball specifies an archive in zip format. - Zipball archiveFormat = "zipball" -) - -// GetArchiveLink returns an URL to download a tarball or zipball archive for a -// repository. The archiveFormat can be specified by either the github.Tarball -// or github.Zipball constant. -// -// GitHub API docs: https://developer.github.com/v3/repos/contents/#get-archive-link -func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/%s", owner, repo, archiveformat) - if opt != nil && opt.Ref != "" { - u += fmt.Sprintf("/%s", opt.Ref) - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - ctx, req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, nil, err - } - resp.Body.Close() - if resp.StatusCode != http.StatusFound { - return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) - } - parsedURL, err := url.Parse(resp.Header.Get("Location")) - return parsedURL, newResponse(resp), err -} diff --git a/vendor/github.com/google/go-github/github/repos_deployments.go b/vendor/github.com/google/go-github/github/repos_deployments.go deleted file mode 100644 index 9054ca9472..0000000000 --- a/vendor/github.com/google/go-github/github/repos_deployments.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "encoding/json" - "fmt" -) - -// Deployment represents a deployment in a repo -type Deployment struct { - URL *string `json:"url,omitempty"` - ID *int `json:"id,omitempty"` - SHA *string `json:"sha,omitempty"` - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - Payload json.RawMessage `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - Creator *User `json:"creator,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"pushed_at,omitempty"` - StatusesURL *string `json:"statuses_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` -} - -// DeploymentRequest represents a deployment request -type DeploymentRequest struct { - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - AutoMerge *bool `json:"auto_merge,omitempty"` - RequiredContexts *[]string `json:"required_contexts,omitempty"` - Payload *string `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` - TransientEnvironment *bool `json:"transient_environment,omitempty"` - ProductionEnvironment *bool `json:"production_environment,omitempty"` -} - -// DeploymentsListOptions specifies the optional parameters to the -// RepositoriesService.ListDeployments method. -type DeploymentsListOptions struct { - // SHA of the Deployment. - SHA string `url:"sha,omitempty"` - - // List deployments for a given ref. - Ref string `url:"ref,omitempty"` - - // List deployments for a given task. - Task string `url:"task,omitempty"` - - // List deployments for a given environment. - Environment string `url:"environment,omitempty"` - - ListOptions -} - -// ListDeployments lists the deployments of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments -func (s *RepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var deployments []*Deployment - resp, err := s.client.Do(ctx, req, &deployments) - if err != nil { - return nil, resp, err - } - - return deployments, resp, nil -} - -// GetDeployment returns a single deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment -func (s *RepositoriesService) GetDeployment(ctx context.Context, owner, repo string, deploymentID int) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v", owner, repo, deploymentID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - deployment := new(Deployment) - resp, err := s.client.Do(ctx, req, deployment) - if err != nil { - return nil, resp, err - } - - return deployment, resp, nil -} - -// CreateDeployment creates a new deployment for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment -func (s *RepositoriesService) CreateDeployment(ctx context.Context, owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when deployment support fully launches - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(Deployment) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// DeploymentStatus represents the status of a -// particular deployment. -type DeploymentStatus struct { - ID *int `json:"id,omitempty"` - // State is the deployment state. - // Possible values are: "pending", "success", "failure", "error", "inactive". - State *string `json:"state,omitempty"` - Creator *User `json:"creator,omitempty"` - Description *string `json:"description,omitempty"` - TargetURL *string `json:"target_url,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"pushed_at,omitempty"` - DeploymentURL *string `json:"deployment_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` -} - -// DeploymentStatusRequest represents a deployment request -type DeploymentStatusRequest struct { - State *string `json:"state,omitempty"` - LogURL *string `json:"log_url,omitempty"` - Description *string `json:"description,omitempty"` - EnvironmentURL *string `json:"environment_url,omitempty"` - AutoInactive *bool `json:"auto_inactive,omitempty"` -} - -// ListDeploymentStatuses lists the statuses of a given deployment of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses -func (s *RepositoriesService) ListDeploymentStatuses(ctx context.Context, owner, repo string, deployment int, opt *ListOptions) ([]*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var statuses []*DeploymentStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// GetDeploymentStatus returns a single deployment status of a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#get-a-single-deployment-status -func (s *RepositoriesService) GetDeploymentStatus(ctx context.Context, owner, repo string, deploymentID, deploymentStatusID int) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses/%v", owner, repo, deploymentID, deploymentStatusID) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when deployment support fully launches - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} - -// CreateDeploymentStatus creates a new status for a deployment. -// -// GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment-status -func (s *RepositoriesService) CreateDeploymentStatus(ctx context.Context, owner, repo string, deployment int, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when deployment support fully launches - req.Header.Set("Accept", mediaTypeDeploymentStatusPreview) - - d := new(DeploymentStatus) - resp, err := s.client.Do(ctx, req, d) - if err != nil { - return nil, resp, err - } - - return d, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_forks.go b/vendor/github.com/google/go-github/github/repos_forks.go deleted file mode 100644 index 4ca19a42dc..0000000000 --- a/vendor/github.com/google/go-github/github/repos_forks.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// RepositoryListForksOptions specifies the optional parameters to the -// RepositoriesService.ListForks method. -type RepositoryListForksOptions struct { - // How to sort the forks list. Possible values are: newest, oldest, - // watchers. Default is "newest". - Sort string `url:"sort,omitempty"` - - ListOptions -} - -// ListForks lists the forks of the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#list-forks -func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when topics API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - - var repos []*Repository - resp, err := s.client.Do(ctx, req, &repos) - if err != nil { - return nil, resp, err - } - - return repos, resp, nil -} - -// RepositoryCreateForkOptions specifies the optional parameters to the -// RepositoriesService.CreateFork method. -type RepositoryCreateForkOptions struct { - // The organization to fork the repository into. - Organization string `url:"organization,omitempty"` -} - -// CreateFork creates a fork of the specified repository. -// -// This method might return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing creating the fork in a background task. -// A follow up request, after a delay of a second or so, should result -// in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/forks/#create-a-fork -func (s *RepositoriesService) CreateFork(ctx context.Context, owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - fork := new(Repository) - resp, err := s.client.Do(ctx, req, fork) - if err != nil { - return nil, resp, err - } - - return fork, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_hooks.go b/vendor/github.com/google/go-github/github/repos_hooks.go deleted file mode 100644 index 67ce96ac34..0000000000 --- a/vendor/github.com/google/go-github/github/repos_hooks.go +++ /dev/null @@ -1,192 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// WebHookPayload represents the data that is received from GitHub when a push -// event hook is triggered. The format of these payloads pre-date most of the -// GitHub v3 API, so there are lots of minor incompatibilities with the types -// defined in the rest of the API. Therefore, several types are duplicated -// here to account for these differences. -// -// GitHub API docs: https://help.github.com/articles/post-receive-hooks -type WebHookPayload struct { - After *string `json:"after,omitempty"` - Before *string `json:"before,omitempty"` - Commits []WebHookCommit `json:"commits,omitempty"` - Compare *string `json:"compare,omitempty"` - Created *bool `json:"created,omitempty"` - Deleted *bool `json:"deleted,omitempty"` - Forced *bool `json:"forced,omitempty"` - HeadCommit *WebHookCommit `json:"head_commit,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Ref *string `json:"ref,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Sender *User `json:"sender,omitempty"` -} - -func (w WebHookPayload) String() string { - return Stringify(w) -} - -// WebHookCommit represents the commit variant we receive from GitHub in a -// WebHookPayload. -type WebHookCommit struct { - Added []string `json:"added,omitempty"` - Author *WebHookAuthor `json:"author,omitempty"` - Committer *WebHookAuthor `json:"committer,omitempty"` - Distinct *bool `json:"distinct,omitempty"` - ID *string `json:"id,omitempty"` - Message *string `json:"message,omitempty"` - Modified []string `json:"modified,omitempty"` - Removed []string `json:"removed,omitempty"` - Timestamp *time.Time `json:"timestamp,omitempty"` -} - -func (w WebHookCommit) String() string { - return Stringify(w) -} - -// WebHookAuthor represents the author or committer of a commit, as specified -// in a WebHookCommit. The commit author may not correspond to a GitHub User. -type WebHookAuthor struct { - Email *string `json:"email,omitempty"` - Name *string `json:"name,omitempty"` - Username *string `json:"username,omitempty"` -} - -func (w WebHookAuthor) String() string { - return Stringify(w) -} - -// Hook represents a GitHub (web and service) hook for a repository. -type Hook struct { - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` - Name *string `json:"name,omitempty"` - URL *string `json:"url,omitempty"` - Events []string `json:"events,omitempty"` - Active *bool `json:"active,omitempty"` - Config map[string]interface{} `json:"config,omitempty"` - ID *int `json:"id,omitempty"` -} - -func (h Hook) String() string { - return Stringify(h) -} - -// CreateHook creates a Hook for the specified repository. -// Name and Config are required fields. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#create-a-hook -func (s *RepositoriesService) CreateHook(ctx context.Context, owner, repo string, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - req, err := s.client.NewRequest("POST", u, hook) - if err != nil { - return nil, nil, err - } - - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - if err != nil { - return nil, resp, err - } - - return h, resp, nil -} - -// ListHooks lists all Hooks for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#list -func (s *RepositoriesService) ListHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var hooks []*Hook - resp, err := s.client.Do(ctx, req, &hooks) - if err != nil { - return nil, resp, err - } - - return hooks, resp, nil -} - -// GetHook returns a single specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#get-single-hook -func (s *RepositoriesService) GetHook(ctx context.Context, owner, repo string, id int) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - hook := new(Hook) - resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err -} - -// EditHook updates a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#edit-a-hook -func (s *RepositoriesService) EditHook(ctx context.Context, owner, repo string, id int, hook *Hook) (*Hook, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("PATCH", u, hook) - if err != nil { - return nil, nil, err - } - h := new(Hook) - resp, err := s.client.Do(ctx, req, h) - return h, resp, err -} - -// DeleteHook deletes a specified Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#delete-a-hook -func (s *RepositoriesService) DeleteHook(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d", owner, repo, id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// PingHook triggers a 'ping' event to be sent to the Hook. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook -func (s *RepositoriesService) PingHook(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/pings", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// TestHook triggers a test Hook by github. -// -// GitHub API docs: https://developer.github.com/v3/repos/hooks/#test-a-push-hook -func (s *RepositoriesService) TestHook(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/hooks/%d/tests", owner, repo, id) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_invitations.go b/vendor/github.com/google/go-github/github/repos_invitations.go deleted file mode 100644 index 0a2b7c1987..0000000000 --- a/vendor/github.com/google/go-github/github/repos_invitations.go +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// RepositoryInvitation represents an invitation to collaborate on a repo. -type RepositoryInvitation struct { - ID *int `json:"id,omitempty"` - Repo *Repository `json:"repository,omitempty"` - Invitee *User `json:"invitee,omitempty"` - Inviter *User `json:"inviter,omitempty"` - - // Permissions represents the permissions that the associated user will have - // on the repository. Possible values are: "read", "write", "admin". - Permissions *string `json:"permissions,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// ListInvitations lists all currently-open repository invitations. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository -func (s *RepositoriesService) ListInvitations(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// DeleteInvitation deletes a repository invitation. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#delete-a-repository-invitation -func (s *RepositoriesService) DeleteInvitation(ctx context.Context, owner, repo string, invitationID int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// UpdateInvitation updates the permissions associated with a repository -// invitation. -// -// permissions represents the permissions that the associated user will have -// on the repository. Possible values are: "read", "write", "admin". -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#update-a-repository-invitation -func (s *RepositoriesService) UpdateInvitation(ctx context.Context, owner, repo string, invitationID int, permissions string) (*RepositoryInvitation, *Response, error) { - opts := &struct { - Permissions string `json:"permissions"` - }{Permissions: permissions} - u := fmt.Sprintf("repos/%v/%v/invitations/%v", owner, repo, invitationID) - req, err := s.client.NewRequest("PATCH", u, opts) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invite := &RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, invite) - if err != nil { - return nil, resp, err - } - - return invite, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_keys.go b/vendor/github.com/google/go-github/github/repos_keys.go deleted file mode 100644 index f5a865813a..0000000000 --- a/vendor/github.com/google/go-github/github/repos_keys.go +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// The Key type is defined in users_keys.go - -// ListKeys lists the deploy keys for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#list -func (s *RepositoriesService) ListKeys(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#get -func (s *RepositoriesService) GetKey(ctx context.Context, owner string, repo string, id int) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a deploy key for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#create -func (s *RepositoriesService) CreateKey(ctx context.Context, owner string, repo string, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// EditKey edits a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#edit -func (s *RepositoriesService) EditKey(ctx context.Context, owner string, repo string, id int, key *Key) (*Key, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a deploy key. -// -// GitHub API docs: https://developer.github.com/v3/repos/keys/#delete -func (s *RepositoriesService) DeleteKey(ctx context.Context, owner string, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%v/%v/keys/%v", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/repos_merging.go b/vendor/github.com/google/go-github/github/repos_merging.go deleted file mode 100644 index 04383c1ae3..0000000000 --- a/vendor/github.com/google/go-github/github/repos_merging.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" -) - -// RepositoryMergeRequest represents a request to merge a branch in a -// repository. -type RepositoryMergeRequest struct { - Base *string `json:"base,omitempty"` - Head *string `json:"head,omitempty"` - CommitMessage *string `json:"commit_message,omitempty"` -} - -// Merge a branch in the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/merging/#perform-a-merge -func (s *RepositoriesService) Merge(ctx context.Context, owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/merges", owner, repo) - req, err := s.client.NewRequest("POST", u, request) - if err != nil { - return nil, nil, err - } - - commit := new(RepositoryCommit) - resp, err := s.client.Do(ctx, req, commit) - if err != nil { - return nil, resp, err - } - - return commit, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_pages.go b/vendor/github.com/google/go-github/github/repos_pages.go deleted file mode 100644 index 075f5742d1..0000000000 --- a/vendor/github.com/google/go-github/github/repos_pages.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Pages represents a GitHub Pages site configuration. -type Pages struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - CNAME *string `json:"cname,omitempty"` - Custom404 *bool `json:"custom_404,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` -} - -// PagesError represents a build error for a GitHub Pages site. -type PagesError struct { - Message *string `json:"message,omitempty"` -} - -// PagesBuild represents the build information for a GitHub Pages site. -type PagesBuild struct { - URL *string `json:"url,omitempty"` - Status *string `json:"status,omitempty"` - Error *PagesError `json:"error,omitempty"` - Pusher *User `json:"pusher,omitempty"` - Commit *string `json:"commit,omitempty"` - Duration *int `json:"duration,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` -} - -// GetPagesInfo fetches information about a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#get-information-about-a-pages-site -func (s *RepositoriesService) GetPagesInfo(ctx context.Context, owner, repo string) (*Pages, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - site := new(Pages) - resp, err := s.client.Do(ctx, req, site) - if err != nil { - return nil, resp, err - } - - return site, resp, nil -} - -// ListPagesBuilds lists the builds for a GitHub Pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds -func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var pages []*PagesBuild - resp, err := s.client.Do(ctx, req, &pages) - if err != nil { - return nil, resp, err - } - - return pages, resp, nil -} - -// GetLatestPagesBuild fetches the latest build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-latest-pages-build -func (s *RepositoriesService) GetLatestPagesBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/latest", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// GetPageBuild fetches the specific build information for a GitHub pages site. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#list-a-specific-pages-build -func (s *RepositoriesService) GetPageBuild(ctx context.Context, owner, repo string, id int) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds/%v", owner, repo, id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} - -// RequestPageBuild requests a build of a GitHub Pages site without needing to push new commit. -// -// GitHub API docs: https://developer.github.com/v3/repos/pages/#request-a-page-build -func (s *RepositoriesService) RequestPageBuild(ctx context.Context, owner, repo string) (*PagesBuild, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - req, err := s.client.NewRequest("POST", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypePagesPreview) - - build := new(PagesBuild) - resp, err := s.client.Do(ctx, req, build) - if err != nil { - return nil, resp, err - } - - return build, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_projects.go b/vendor/github.com/google/go-github/github/repos_projects.go deleted file mode 100644 index 770ffc76fa..0000000000 --- a/vendor/github.com/google/go-github/github/repos_projects.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ProjectListOptions specifies the optional parameters to the -// OrganizationsService.ListProjects and RepositoriesService.ListProjects methods. -type ProjectListOptions struct { - // Indicates the state of the projects to return. Can be either open, closed, or all. Default: open - State string `url:"state,omitempty"` - - ListOptions -} - -// ListProjects lists the projects for a repo. -// -// GitHub API docs: https://developer.github.com/v3/projects/#list-repository-projects -func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo string, opt *ProjectListOptions) ([]*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - var projects []*Project - resp, err := s.client.Do(ctx, req, &projects) - if err != nil { - return nil, resp, err - } - - return projects, resp, nil -} - -// CreateProject creates a GitHub Project for the specified repository. -// -// GitHub API docs: https://developer.github.com/v3/projects/#create-a-repository-project -func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opt *ProjectOptions) (*Project, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeProjectsPreview) - - project := &Project{} - resp, err := s.client.Do(ctx, req, project) - if err != nil { - return nil, resp, err - } - - return project, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_releases.go b/vendor/github.com/google/go-github/github/repos_releases.go deleted file mode 100644 index 5c27565510..0000000000 --- a/vendor/github.com/google/go-github/github/repos_releases.go +++ /dev/null @@ -1,327 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "errors" - "fmt" - "io" - "mime" - "net/http" - "os" - "path/filepath" - "strings" -) - -// RepositoryRelease represents a GitHub release in a repository. -type RepositoryRelease struct { - ID *int `json:"id,omitempty"` - TagName *string `json:"tag_name,omitempty"` - TargetCommitish *string `json:"target_commitish,omitempty"` - Name *string `json:"name,omitempty"` - Body *string `json:"body,omitempty"` - Draft *bool `json:"draft,omitempty"` - Prerelease *bool `json:"prerelease,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PublishedAt *Timestamp `json:"published_at,omitempty"` - URL *string `json:"url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - AssetsURL *string `json:"assets_url,omitempty"` - Assets []ReleaseAsset `json:"assets,omitempty"` - UploadURL *string `json:"upload_url,omitempty"` - ZipballURL *string `json:"zipball_url,omitempty"` - TarballURL *string `json:"tarball_url,omitempty"` - Author *User `json:"author,omitempty"` -} - -func (r RepositoryRelease) String() string { - return Stringify(r) -} - -// ReleaseAsset represents a GitHub release asset in a repository. -type ReleaseAsset struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - Name *string `json:"name,omitempty"` - Label *string `json:"label,omitempty"` - State *string `json:"state,omitempty"` - ContentType *string `json:"content_type,omitempty"` - Size *int `json:"size,omitempty"` - DownloadCount *int `json:"download_count,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - BrowserDownloadURL *string `json:"browser_download_url,omitempty"` - Uploader *User `json:"uploader,omitempty"` -} - -func (r ReleaseAsset) String() string { - return Stringify(r) -} - -// ListReleases lists the releases for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository -func (s *RepositoriesService) ListReleases(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var releases []*RepositoryRelease - resp, err := s.client.Do(ctx, req, &releases) - if err != nil { - return nil, resp, err - } - return releases, resp, nil -} - -// GetRelease fetches a single release. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release -func (s *RepositoriesService) GetRelease(ctx context.Context, owner, repo string, id int) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - return s.getSingleRelease(ctx, u) -} - -// GetLatestRelease fetches the latest published release for the repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release -func (s *RepositoriesService) GetLatestRelease(ctx context.Context, owner, repo string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/latest", owner, repo) - return s.getSingleRelease(ctx, u) -} - -// GetReleaseByTag fetches a release with the specified tag. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name -func (s *RepositoriesService) GetReleaseByTag(ctx context.Context, owner, repo, tag string) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/tags/%s", owner, repo, tag) - return s.getSingleRelease(ctx, u) -} - -func (s *RepositoriesService) getSingleRelease(ctx context.Context, url string) (*RepositoryRelease, *Response, error) { - req, err := s.client.NewRequest("GET", url, nil) - if err != nil { - return nil, nil, err - } - - release := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, release) - if err != nil { - return nil, resp, err - } - return release, resp, nil -} - -// CreateRelease adds a new release for a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#create-a-release -func (s *RepositoriesService) CreateRelease(ctx context.Context, owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - - req, err := s.client.NewRequest("POST", u, release) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// EditRelease edits a repository release. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release -func (s *RepositoriesService) EditRelease(ctx context.Context, owner, repo string, id int, release *RepositoryRelease) (*RepositoryRelease, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, release) - if err != nil { - return nil, nil, err - } - - r := new(RepositoryRelease) - resp, err := s.client.Do(ctx, req, r) - if err != nil { - return nil, resp, err - } - return r, resp, nil -} - -// DeleteRelease delete a single release from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release -func (s *RepositoriesService) DeleteRelease(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// ListReleaseAssets lists the release's assets. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#list-assets-for-a-release -func (s *RepositoriesService) ListReleaseAssets(ctx context.Context, owner, repo string, id int, opt *ListOptions) ([]*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var assets []*ReleaseAsset - resp, err := s.client.Do(ctx, req, &assets) - if err != nil { - return nil, resp, err - } - return assets, resp, nil -} - -// GetReleaseAsset fetches a single release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) GetReleaseAsset(ctx context.Context, owner, repo string, id int) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DownloadReleaseAsset downloads a release asset or returns a redirect URL. -// -// DownloadReleaseAsset returns an io.ReadCloser that reads the contents of the -// specified release asset. It is the caller's responsibility to close the ReadCloser. -// If a redirect is returned, the redirect URL will be returned as a string instead -// of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, repo string, id int) (rc io.ReadCloser, redirectURL string, err error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, "", err - } - req.Header.Set("Accept", defaultMediaType) - - s.client.clientMu.Lock() - defer s.client.clientMu.Unlock() - - var loc string - saveRedirect := s.client.client.CheckRedirect - s.client.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - loc = req.URL.String() - return errors.New("disable redirect") - } - defer func() { s.client.client.CheckRedirect = saveRedirect }() - - ctx, req = withContext(ctx, req) - resp, err := s.client.client.Do(req) - if err != nil { - if !strings.Contains(err.Error(), "disable redirect") { - return nil, "", err - } - return nil, loc, nil // Intentionally return no error with valid redirect URL. - } - - if err := CheckResponse(resp); err != nil { - resp.Body.Close() - return nil, "", err - } - - return resp.Body, "", nil -} - -// EditReleaseAsset edits a repository release asset. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release-asset -func (s *RepositoriesService) EditReleaseAsset(ctx context.Context, owner, repo string, id int, release *ReleaseAsset) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("PATCH", u, release) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} - -// DeleteReleaseAsset delete a single release asset from a repository. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#delete-a-release-asset -func (s *RepositoriesService) DeleteReleaseAsset(ctx context.Context, owner, repo string, id int) (*Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - return s.client.Do(ctx, req, nil) -} - -// UploadReleaseAsset creates an asset by uploading a file into a release repository. -// To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. -// -// GitHub API docs: https://developer.github.com/v3/repos/releases/#upload-a-release-asset -func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) { - u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - stat, err := file.Stat() - if err != nil { - return nil, nil, err - } - if stat.IsDir() { - return nil, nil, errors.New("the asset to upload can't be a directory") - } - - mediaType := mime.TypeByExtension(filepath.Ext(file.Name())) - req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType) - if err != nil { - return nil, nil, err - } - - asset := new(ReleaseAsset) - resp, err := s.client.Do(ctx, req, asset) - if err != nil { - return nil, resp, err - } - return asset, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_stats.go b/vendor/github.com/google/go-github/github/repos_stats.go deleted file mode 100644 index 30fc7bd340..0000000000 --- a/vendor/github.com/google/go-github/github/repos_stats.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// ContributorStats represents a contributor to a repository and their -// weekly contributions to a given repo. -type ContributorStats struct { - Author *Contributor `json:"author,omitempty"` - Total *int `json:"total,omitempty"` - Weeks []WeeklyStats `json:"weeks,omitempty"` -} - -func (c ContributorStats) String() string { - return Stringify(c) -} - -// WeeklyStats represents the number of additions, deletions and commits -// a Contributor made in a given week. -type WeeklyStats struct { - Week *Timestamp `json:"w,omitempty"` - Additions *int `json:"a,omitempty"` - Deletions *int `json:"d,omitempty"` - Commits *int `json:"c,omitempty"` -} - -func (w WeeklyStats) String() string { - return Stringify(w) -} - -// ListContributorsStats gets a repo's contributor list with additions, -// deletions and commit counts. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#contributors -func (s *RepositoriesService) ListContributorsStats(ctx context.Context, owner, repo string) ([]*ContributorStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/contributors", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var contributorStats []*ContributorStats - resp, err := s.client.Do(ctx, req, &contributorStats) - if err != nil { - return nil, resp, err - } - - return contributorStats, resp, nil -} - -// WeeklyCommitActivity represents the weekly commit activity for a repository. -// The days array is a group of commits per day, starting on Sunday. -type WeeklyCommitActivity struct { - Days []int `json:"days,omitempty"` - Total *int `json:"total,omitempty"` - Week *Timestamp `json:"week,omitempty"` -} - -func (w WeeklyCommitActivity) String() string { - return Stringify(w) -} - -// ListCommitActivity returns the last year of commit activity -// grouped by week. The days array is a group of commits per day, -// starting on Sunday. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#commit-activity -func (s *RepositoriesService) ListCommitActivity(ctx context.Context, owner, repo string) ([]*WeeklyCommitActivity, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/commit_activity", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeklyCommitActivity []*WeeklyCommitActivity - resp, err := s.client.Do(ctx, req, &weeklyCommitActivity) - if err != nil { - return nil, resp, err - } - - return weeklyCommitActivity, resp, nil -} - -// ListCodeFrequency returns a weekly aggregate of the number of additions and -// deletions pushed to a repository. Returned WeeklyStats will contain -// additions and deletions, but not total commits. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#code-frequency -func (s *RepositoriesService) ListCodeFrequency(ctx context.Context, owner, repo string) ([]*WeeklyStats, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/code_frequency", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var weeks [][]int - resp, err := s.client.Do(ctx, req, &weeks) - - // convert int slices into WeeklyStats - var stats []*WeeklyStats - for _, week := range weeks { - if len(week) != 3 { - continue - } - stat := &WeeklyStats{ - Week: &Timestamp{time.Unix(int64(week[0]), 0)}, - Additions: Int(week[1]), - Deletions: Int(week[2]), - } - stats = append(stats, stat) - } - - return stats, resp, err -} - -// RepositoryParticipation is the number of commits by everyone -// who has contributed to the repository (including the owner) -// as well as the number of commits by the owner themself. -type RepositoryParticipation struct { - All []int `json:"all,omitempty"` - Owner []int `json:"owner,omitempty"` -} - -func (r RepositoryParticipation) String() string { - return Stringify(r) -} - -// ListParticipation returns the total commit counts for the 'owner' -// and total commit counts in 'all'. 'all' is everyone combined, -// including the 'owner' in the last 52 weeks. If you’d like to get -// the commit counts for non-owners, you can subtract 'all' from 'owner'. -// -// The array order is oldest week (index 0) to most recent week. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#participation -func (s *RepositoriesService) ListParticipation(ctx context.Context, owner, repo string) (*RepositoryParticipation, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/participation", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - participation := new(RepositoryParticipation) - resp, err := s.client.Do(ctx, req, participation) - if err != nil { - return nil, resp, err - } - - return participation, resp, nil -} - -// PunchCard represents the number of commits made during a given hour of a -// day of thew eek. -type PunchCard struct { - Day *int // Day of the week (0-6: =Sunday - Saturday). - Hour *int // Hour of day (0-23). - Commits *int // Number of commits. -} - -// ListPunchCard returns the number of commits per hour in each day. -// -// If this is the first time these statistics are requested for the given -// repository, this method will return an *AcceptedError and a status code of -// 202. This is because this is the status that GitHub returns to signify that -// it is now computing the requested statistics. A follow up request, after a -// delay of a second or so, should result in a successful request. -// -// GitHub API docs: https://developer.github.com/v3/repos/statistics/#punch-card -func (s *RepositoriesService) ListPunchCard(ctx context.Context, owner, repo string) ([]*PunchCard, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/stats/punch_card", owner, repo) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var results [][]int - resp, err := s.client.Do(ctx, req, &results) - - // convert int slices into Punchcards - var cards []*PunchCard - for _, result := range results { - if len(result) != 3 { - continue - } - card := &PunchCard{ - Day: Int(result[0]), - Hour: Int(result[1]), - Commits: Int(result[2]), - } - cards = append(cards, card) - } - - return cards, resp, err -} diff --git a/vendor/github.com/google/go-github/github/repos_statuses.go b/vendor/github.com/google/go-github/github/repos_statuses.go deleted file mode 100644 index 6db501076c..0000000000 --- a/vendor/github.com/google/go-github/github/repos_statuses.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// RepoStatus represents the status of a repository at a particular reference. -type RepoStatus struct { - ID *int `json:"id,omitempty"` - URL *string `json:"url,omitempty"` - - // State is the current state of the repository. Possible values are: - // pending, success, error, or failure. - State *string `json:"state,omitempty"` - - // TargetURL is the URL of the page representing this status. It will be - // linked from the GitHub UI to allow users to see the source of the status. - TargetURL *string `json:"target_url,omitempty"` - - // Description is a short high level summary of the status. - Description *string `json:"description,omitempty"` - - // A string label to differentiate this status from the statuses of other systems. - Context *string `json:"context,omitempty"` - - Creator *User `json:"creator,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - UpdatedAt *time.Time `json:"updated_at,omitempty"` -} - -func (r RepoStatus) String() string { - return Stringify(r) -} - -// ListStatuses lists the statuses of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref -func (s *RepositoriesService) ListStatuses(ctx context.Context, owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/statuses", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var statuses []*RepoStatus - resp, err := s.client.Do(ctx, req, &statuses) - if err != nil { - return nil, resp, err - } - - return statuses, resp, nil -} - -// CreateStatus creates a new status for a repository at the specified -// reference. Ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#create-a-status -func (s *RepositoriesService) CreateStatus(ctx context.Context, owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/statuses/%v", owner, repo, ref) - req, err := s.client.NewRequest("POST", u, status) - if err != nil { - return nil, nil, err - } - - repoStatus := new(RepoStatus) - resp, err := s.client.Do(ctx, req, repoStatus) - if err != nil { - return nil, resp, err - } - - return repoStatus, resp, nil -} - -// CombinedStatus represents the combined status of a repository at a particular reference. -type CombinedStatus struct { - // State is the combined state of the repository. Possible values are: - // failure, pending, or success. - State *string `json:"state,omitempty"` - - Name *string `json:"name,omitempty"` - SHA *string `json:"sha,omitempty"` - TotalCount *int `json:"total_count,omitempty"` - Statuses []RepoStatus `json:"statuses,omitempty"` - - CommitURL *string `json:"commit_url,omitempty"` - RepositoryURL *string `json:"repository_url,omitempty"` -} - -func (s CombinedStatus) String() string { - return Stringify(s) -} - -// GetCombinedStatus returns the combined status of a repository at the specified -// reference. ref can be a SHA, a branch name, or a tag name. -// -// GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref -func (s *RepositoriesService) GetCombinedStatus(ctx context.Context, owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/commits/%v/status", owner, repo, ref) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - status := new(CombinedStatus) - resp, err := s.client.Do(ctx, req, status) - if err != nil { - return nil, resp, err - } - - return status, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/repos_traffic.go b/vendor/github.com/google/go-github/github/repos_traffic.go deleted file mode 100644 index fb1c97648a..0000000000 --- a/vendor/github.com/google/go-github/github/repos_traffic.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" -) - -// TrafficReferrer represent information about traffic from a referrer . -type TrafficReferrer struct { - Referrer *string `json:"referrer,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficPath represent information about the traffic on a path of the repo. -type TrafficPath struct { - Path *string `json:"path,omitempty"` - Title *string `json:"title,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficData represent information about a specific timestamp in views or clones list. -type TrafficData struct { - Timestamp *Timestamp `json:"timestamp,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficViews represent information about the number of views in the last 14 days. -type TrafficViews struct { - Views []*TrafficData `json:"views,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficClones represent information about the number of clones in the last 14 days. -type TrafficClones struct { - Clones []*TrafficData `json:"clones,omitempty"` - Count *int `json:"count,omitempty"` - Uniques *int `json:"uniques,omitempty"` -} - -// TrafficBreakdownOptions specifies the parameters to methods that support breakdown per day or week. -// Can be one of: day, week. Default: day. -type TrafficBreakdownOptions struct { - Per string `url:"per,omitempty"` -} - -// ListTrafficReferrers list the top 10 referrers over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-referrers -func (s *RepositoriesService) ListTrafficReferrers(ctx context.Context, owner, repo string) ([]*TrafficReferrer, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/referrers", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var trafficReferrers []*TrafficReferrer - resp, err := s.client.Do(ctx, req, &trafficReferrers) - if err != nil { - return nil, resp, err - } - - return trafficReferrers, resp, nil -} - -// ListTrafficPaths list the top 10 popular content over the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#list-paths -func (s *RepositoriesService) ListTrafficPaths(ctx context.Context, owner, repo string) ([]*TrafficPath, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/popular/paths", owner, repo) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var paths []*TrafficPath - resp, err := s.client.Do(ctx, req, &paths) - if err != nil { - return nil, resp, err - } - - return paths, resp, nil -} - -// ListTrafficViews get total number of views for the last 14 days and breaks it down either per day or week. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficViews, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/views", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficViews := new(TrafficViews) - resp, err := s.client.Do(ctx, req, &trafficViews) - if err != nil { - return nil, resp, err - } - - return trafficViews, resp, nil -} - -// ListTrafficClones get total number of clones for the last 14 days and breaks it down either per day or week for the last 14 days. -// -// GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficClones(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficClones, *Response, error) { - u := fmt.Sprintf("repos/%v/%v/traffic/clones", owner, repo) - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - trafficClones := new(TrafficClones) - resp, err := s.client.Do(ctx, req, &trafficClones) - if err != nil { - return nil, resp, err - } - - return trafficClones, resp, nil -} diff --git a/vendor/github.com/google/go-github/github/search.go b/vendor/github.com/google/go-github/github/search.go deleted file mode 100644 index cc7c45cf39..0000000000 --- a/vendor/github.com/google/go-github/github/search.go +++ /dev/null @@ -1,202 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" - - qs "github.com/google/go-querystring/query" -) - -// SearchService provides access to the search related functions -// in the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/search/ -type SearchService service - -// SearchOptions specifies optional parameters to the SearchService methods. -type SearchOptions struct { - // How to sort the search results. Possible values are: - // - for repositories: stars, fork, updated - // - for commits: author-date, committer-date - // - for code: indexed - // - for issues: comments, created, updated - // - for users: followers, repositories, joined - // - // Default is to sort by best match. - Sort string `url:"sort,omitempty"` - - // Sort order if sort parameter is provided. Possible values are: asc, - // desc. Default is desc. - Order string `url:"order,omitempty"` - - // Whether to retrieve text match metadata with a query - TextMatch bool `url:"-"` - - ListOptions -} - -// RepositoriesSearchResult represents the result of a repositories search. -type RepositoriesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Repositories []Repository `json:"items,omitempty"` -} - -// Repositories searches repositories via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-repositories -func (s *SearchService) Repositories(ctx context.Context, query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error) { - result := new(RepositoriesSearchResult) - resp, err := s.search(ctx, "repositories", query, opt, result) - return result, resp, err -} - -// CommitsSearchResult represents the result of a commits search. -type CommitsSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Commits []*CommitResult `json:"items,omitempty"` -} - -// CommitResult represents a commit object as returned in commit search endpoint response. -type CommitResult struct { - SHA *string `json:"sha,omitempty"` - Commit *Commit `json:"commit,omitempty"` - Author *User `json:"author,omitempty"` - Committer *User `json:"committer,omitempty"` - Parents []*Commit `json:"parents,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - URL *string `json:"url,omitempty"` - CommentsURL *string `json:"comments_url,omitempty"` - - Repository *Repository `json:"repository,omitempty"` - Score *float64 `json:"score,omitempty"` -} - -// Commits searches commits via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-commits -func (s *SearchService) Commits(ctx context.Context, query string, opt *SearchOptions) (*CommitsSearchResult, *Response, error) { - result := new(CommitsSearchResult) - resp, err := s.search(ctx, "commits", query, opt, result) - return result, resp, err -} - -// IssuesSearchResult represents the result of an issues search. -type IssuesSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Issues []Issue `json:"items,omitempty"` -} - -// Issues searches issues via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-issues -func (s *SearchService) Issues(ctx context.Context, query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error) { - result := new(IssuesSearchResult) - resp, err := s.search(ctx, "issues", query, opt, result) - return result, resp, err -} - -// UsersSearchResult represents the result of a users search. -type UsersSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - Users []User `json:"items,omitempty"` -} - -// Users searches users via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-users -func (s *SearchService) Users(ctx context.Context, query string, opt *SearchOptions) (*UsersSearchResult, *Response, error) { - result := new(UsersSearchResult) - resp, err := s.search(ctx, "users", query, opt, result) - return result, resp, err -} - -// Match represents a single text match. -type Match struct { - Text *string `json:"text,omitempty"` - Indices []int `json:"indices,omitempty"` -} - -// TextMatch represents a text match for a SearchResult -type TextMatch struct { - ObjectURL *string `json:"object_url,omitempty"` - ObjectType *string `json:"object_type,omitempty"` - Property *string `json:"property,omitempty"` - Fragment *string `json:"fragment,omitempty"` - Matches []Match `json:"matches,omitempty"` -} - -func (tm TextMatch) String() string { - return Stringify(tm) -} - -// CodeSearchResult represents the result of a code search. -type CodeSearchResult struct { - Total *int `json:"total_count,omitempty"` - IncompleteResults *bool `json:"incomplete_results,omitempty"` - CodeResults []CodeResult `json:"items,omitempty"` -} - -// CodeResult represents a single search result. -type CodeResult struct { - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - SHA *string `json:"sha,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - Repository *Repository `json:"repository,omitempty"` - TextMatches []TextMatch `json:"text_matches,omitempty"` -} - -func (c CodeResult) String() string { - return Stringify(c) -} - -// Code searches code via various criteria. -// -// GitHub API docs: https://developer.github.com/v3/search/#search-code -func (s *SearchService) Code(ctx context.Context, query string, opt *SearchOptions) (*CodeSearchResult, *Response, error) { - result := new(CodeSearchResult) - resp, err := s.search(ctx, "code", query, opt, result) - return result, resp, err -} - -// Helper function that executes search queries against different -// GitHub search types (repositories, commits, code, issues, users) -func (s *SearchService) search(ctx context.Context, searchType string, query string, opt *SearchOptions, result interface{}) (*Response, error) { - params, err := qs.Values(opt) - if err != nil { - return nil, err - } - params.Set("q", query) - u := fmt.Sprintf("search/%s?%s", searchType, params.Encode()) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - switch { - case searchType == "commits": - // Accept header for search commits preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeCommitSearchPreview) - case searchType == "repositories": - // Accept header for search repositories based on topics preview endpoint - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeTopicsPreview) - case opt != nil && opt.TextMatch: - // Accept header defaults to "application/vnd.github.v3+json" - // We change it here to fetch back text-match metadata - req.Header.Set("Accept", "application/vnd.github.v3.text-match+json") - } - - return s.client.Do(ctx, req, result) -} diff --git a/vendor/github.com/google/go-github/github/strings.go b/vendor/github.com/google/go-github/github/strings.go deleted file mode 100644 index 431e1cc6c1..0000000000 --- a/vendor/github.com/google/go-github/github/strings.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "bytes" - "fmt" - "io" - - "reflect" -) - -var timestampType = reflect.TypeOf(Timestamp{}) - -// Stringify attempts to create a reasonable string representation of types in -// the GitHub library. It does things like resolve pointers to their values -// and omits struct fields with nil values. -func Stringify(message interface{}) string { - var buf bytes.Buffer - v := reflect.ValueOf(message) - stringifyValue(&buf, v) - return buf.String() -} - -// stringifyValue was heavily inspired by the goprotobuf library. - -func stringifyValue(w io.Writer, val reflect.Value) { - if val.Kind() == reflect.Ptr && val.IsNil() { - w.Write([]byte("")) - return - } - - v := reflect.Indirect(val) - - switch v.Kind() { - case reflect.String: - fmt.Fprintf(w, `"%s"`, v) - case reflect.Slice: - w.Write([]byte{'['}) - for i := 0; i < v.Len(); i++ { - if i > 0 { - w.Write([]byte{' '}) - } - - stringifyValue(w, v.Index(i)) - } - - w.Write([]byte{']'}) - return - case reflect.Struct: - if v.Type().Name() != "" { - w.Write([]byte(v.Type().String())) - } - - // special handling of Timestamp values - if v.Type() == timestampType { - fmt.Fprintf(w, "{%s}", v.Interface()) - return - } - - w.Write([]byte{'{'}) - - var sep bool - for i := 0; i < v.NumField(); i++ { - fv := v.Field(i) - if fv.Kind() == reflect.Ptr && fv.IsNil() { - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - continue - } - - if sep { - w.Write([]byte(", ")) - } else { - sep = true - } - - w.Write([]byte(v.Type().Field(i).Name)) - w.Write([]byte{':'}) - stringifyValue(w, fv) - } - - w.Write([]byte{'}'}) - default: - if v.CanInterface() { - fmt.Fprint(w, v.Interface()) - } - } -} diff --git a/vendor/github.com/google/go-github/github/timestamp.go b/vendor/github.com/google/go-github/github/timestamp.go deleted file mode 100644 index a1c1554a30..0000000000 --- a/vendor/github.com/google/go-github/github/timestamp.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "strconv" - "time" -) - -// Timestamp represents a time that can be unmarshalled from a JSON string -// formatted as either an RFC3339 or Unix timestamp. This is necessary for some -// fields since the GitHub API is inconsistent in how it represents times. All -// exported methods of time.Time can be called on Timestamp. -type Timestamp struct { - time.Time -} - -func (t Timestamp) String() string { - return t.Time.String() -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -// Time is expected in RFC3339 or Unix format. -func (t *Timestamp) UnmarshalJSON(data []byte) (err error) { - str := string(data) - i, err := strconv.ParseInt(str, 10, 64) - if err == nil { - (*t).Time = time.Unix(i, 0) - } else { - (*t).Time, err = time.Parse(`"`+time.RFC3339+`"`, str) - } - return -} - -// Equal reports whether t and u are equal based on time.Equal -func (t Timestamp) Equal(u Timestamp) bool { - return t.Time.Equal(u.Time) -} diff --git a/vendor/github.com/google/go-github/github/users.go b/vendor/github.com/google/go-github/github/users.go deleted file mode 100644 index 83cfb45b5a..0000000000 --- a/vendor/github.com/google/go-github/github/users.go +++ /dev/null @@ -1,230 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// UsersService handles communication with the user related -// methods of the GitHub API. -// -// GitHub API docs: https://developer.github.com/v3/users/ -type UsersService service - -// User represents a GitHub user. -type User struct { - Login *string `json:"login,omitempty"` - ID *int `json:"id,omitempty"` - AvatarURL *string `json:"avatar_url,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - GravatarID *string `json:"gravatar_id,omitempty"` - Name *string `json:"name,omitempty"` - Company *string `json:"company,omitempty"` - Blog *string `json:"blog,omitempty"` - Location *string `json:"location,omitempty"` - Email *string `json:"email,omitempty"` - Hireable *bool `json:"hireable,omitempty"` - Bio *string `json:"bio,omitempty"` - PublicRepos *int `json:"public_repos,omitempty"` - PublicGists *int `json:"public_gists,omitempty"` - Followers *int `json:"followers,omitempty"` - Following *int `json:"following,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - SuspendedAt *Timestamp `json:"suspended_at,omitempty"` - Type *string `json:"type,omitempty"` - SiteAdmin *bool `json:"site_admin,omitempty"` - TotalPrivateRepos *int `json:"total_private_repos,omitempty"` - OwnedPrivateRepos *int `json:"owned_private_repos,omitempty"` - PrivateGists *int `json:"private_gists,omitempty"` - DiskUsage *int `json:"disk_usage,omitempty"` - Collaborators *int `json:"collaborators,omitempty"` - Plan *Plan `json:"plan,omitempty"` - - // API URLs - URL *string `json:"url,omitempty"` - EventsURL *string `json:"events_url,omitempty"` - FollowingURL *string `json:"following_url,omitempty"` - FollowersURL *string `json:"followers_url,omitempty"` - GistsURL *string `json:"gists_url,omitempty"` - OrganizationsURL *string `json:"organizations_url,omitempty"` - ReceivedEventsURL *string `json:"received_events_url,omitempty"` - ReposURL *string `json:"repos_url,omitempty"` - StarredURL *string `json:"starred_url,omitempty"` - SubscriptionsURL *string `json:"subscriptions_url,omitempty"` - - // TextMatches is only populated from search results that request text matches - // See: search.go and https://developer.github.com/v3/search/#text-match-metadata - TextMatches []TextMatch `json:"text_matches,omitempty"` - - // Permissions identifies the permissions that a user has on a given - // repository. This is only populated when calling Repositories.ListCollaborators. - Permissions *map[string]bool `json:"permissions,omitempty"` -} - -func (u User) String() string { - return Stringify(u) -} - -// Get fetches a user. Passing the empty string will fetch the authenticated -// user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-a-single-user -func (s *UsersService) Get(ctx context.Context, user string) (*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v", user) - } else { - u = "user" - } - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// GetByID fetches a user. -// -// Note: GetByID uses the undocumented GitHub API endpoint /user/:id. -func (s *UsersService) GetByID(ctx context.Context, id int) (*User, *Response, error) { - u := fmt.Sprintf("user/%d", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - user := new(User) - resp, err := s.client.Do(ctx, req, user) - if err != nil { - return nil, resp, err - } - - return user, resp, nil -} - -// Edit the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/#update-the-authenticated-user -func (s *UsersService) Edit(ctx context.Context, user *User) (*User, *Response, error) { - u := "user" - req, err := s.client.NewRequest("PATCH", u, user) - if err != nil { - return nil, nil, err - } - - uResp := new(User) - resp, err := s.client.Do(ctx, req, uResp) - if err != nil { - return nil, resp, err - } - - return uResp, resp, nil -} - -// UserListOptions specifies optional parameters to the UsersService.ListAll -// method. -type UserListOptions struct { - // ID of the last user seen - Since int `url:"since,omitempty"` - - ListOptions -} - -// ListAll lists all GitHub users. -// -// To paginate through all users, populate 'Since' with the ID of the last user. -// -// GitHub API docs: https://developer.github.com/v3/users/#get-all-users -func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*User, *Response, error) { - u, err := addOptions("users", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListInvitations lists all currently-open repository invitations for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations -func (s *UsersService) ListInvitations(ctx context.Context, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u, err := addOptions("user/repository_invitations", opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - invites := []*RepositoryInvitation{} - resp, err := s.client.Do(ctx, req, &invites) - if err != nil { - return nil, resp, err - } - - return invites, resp, nil -} - -// AcceptInvitation accepts the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#accept-a-repository-invitation -func (s *UsersService) AcceptInvitation(ctx context.Context, invitationID int) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("PATCH", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} - -// DeclineInvitation declines the currently-open repository invitation for the -// authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/repos/invitations/#decline-a-repository-invitation -func (s *UsersService) DeclineInvitation(ctx context.Context, invitationID int) (*Response, error) { - u := fmt.Sprintf("user/repository_invitations/%v", invitationID) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryInvitationsPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_administration.go b/vendor/github.com/google/go-github/github/users_administration.go deleted file mode 100644 index e042398d8c..0000000000 --- a/vendor/github.com/google/go-github/github/users_administration.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2014 The go-github 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 github - -import ( - "context" - "fmt" -) - -// PromoteSiteAdmin promotes a user to a site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#promote-an-ordinary-user-to-a-site-administrator -func (s *UsersService) PromoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// DemoteSiteAdmin demotes a user from site administrator of a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#demote-a-site-administrator-to-an-ordinary-user -func (s *UsersService) DemoteSiteAdmin(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/site_admin", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Suspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#suspend-a-user -func (s *UsersService) Suspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unsuspend a user on a GitHub Enterprise instance. -// -// GitHub API docs: https://developer.github.com/v3/users/administration/#unsuspend-a-user -func (s *UsersService) Unsuspend(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("users/%v/suspended", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_blocking.go b/vendor/github.com/google/go-github/github/users_blocking.go deleted file mode 100644 index 39e45601cc..0000000000 --- a/vendor/github.com/google/go-github/github/users_blocking.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2017 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListBlockedUsers lists all the blocked users by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#list-blocked-users -func (s *UsersService) ListBlockedUsers(ctx context.Context, opt *ListOptions) ([]*User, *Response, error) { - u := "user/blocks" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - var blockedUsers []*User - resp, err := s.client.Do(ctx, req, &blockedUsers) - if err != nil { - return nil, resp, err - } - - return blockedUsers, resp, nil -} - -// IsBlocked reports whether specified user is blocked by the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#check-whether-youve-blocked-a-user -func (s *UsersService) IsBlocked(ctx context.Context, user string) (bool, *Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - resp, err := s.client.Do(ctx, req, nil) - isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err -} - -// BlockUser blocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#block-a-user -func (s *UsersService) BlockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} - -// UnblockUser unblocks specified user for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/blocking/#unblock-a-user -func (s *UsersService) UnblockUser(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/blocks/%v", user) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeBlockUsersPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_emails.go b/vendor/github.com/google/go-github/github/users_emails.go deleted file mode 100644 index 0bbd4627e3..0000000000 --- a/vendor/github.com/google/go-github/github/users_emails.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import "context" - -// UserEmail represents user's email address -type UserEmail struct { - Email *string `json:"email,omitempty"` - Primary *bool `json:"primary,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListEmails lists all email addresses for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user -func (s *UsersService) ListEmails(ctx context.Context, opt *ListOptions) ([]*UserEmail, *Response, error) { - u := "user/emails" - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var emails []*UserEmail - resp, err := s.client.Do(ctx, req, &emails) - if err != nil { - return nil, resp, err - } - - return emails, resp, nil -} - -// AddEmails adds email addresses of the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#add-email-addresses -func (s *UsersService) AddEmails(ctx context.Context, emails []string) ([]*UserEmail, *Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("POST", u, emails) - if err != nil { - return nil, nil, err - } - - var e []*UserEmail - resp, err := s.client.Do(ctx, req, &e) - if err != nil { - return nil, resp, err - } - - return e, resp, nil -} - -// DeleteEmails deletes email addresses from authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/emails/#delete-email-addresses -func (s *UsersService) DeleteEmails(ctx context.Context, emails []string) (*Response, error) { - u := "user/emails" - req, err := s.client.NewRequest("DELETE", u, emails) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_followers.go b/vendor/github.com/google/go-github/github/users_followers.go deleted file mode 100644 index c2224096a6..0000000000 --- a/vendor/github.com/google/go-github/github/users_followers.go +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// ListFollowers lists the followers for a user. Passing the empty string will -// fetch followers for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-followers-of-a-user -func (s *UsersService) ListFollowers(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/followers", user) - } else { - u = "user/followers" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// ListFollowing lists the people that a user is following. Passing the empty -// string will list people the authenticated user is following. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#list-users-followed-by-another-user -func (s *UsersService) ListFollowing(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following", user) - } else { - u = "user/following" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var users []*User - resp, err := s.client.Do(ctx, req, &users) - if err != nil { - return nil, resp, err - } - - return users, resp, nil -} - -// IsFollowing checks if "user" is following "target". Passing the empty -// string for "user" will check if the authenticated user is following "target". -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#check-if-you-are-following-a-user -func (s *UsersService) IsFollowing(ctx context.Context, user, target string) (bool, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/following/%v", user, target) - } else { - u = fmt.Sprintf("user/following/%v", target) - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return false, nil, err - } - - resp, err := s.client.Do(ctx, req, nil) - following, err := parseBoolResponse(err) - return following, resp, err -} - -// Follow will cause the authenticated user to follow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#follow-a-user -func (s *UsersService) Follow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} - -// Unfollow will cause the authenticated user to unfollow the specified user. -// -// GitHub API docs: https://developer.github.com/v3/users/followers/#unfollow-a-user -func (s *UsersService) Unfollow(ctx context.Context, user string) (*Response, error) { - u := fmt.Sprintf("user/following/%v", user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_gpg_keys.go b/vendor/github.com/google/go-github/github/users_gpg_keys.go deleted file mode 100644 index 3e95fb4460..0000000000 --- a/vendor/github.com/google/go-github/github/users_gpg_keys.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2016 The go-github 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 github - -import ( - "context" - "fmt" - "time" -) - -// GPGKey represents a GitHub user's public GPG key used to verify GPG signed commits and tags. -// -// https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ -type GPGKey struct { - ID *int `json:"id,omitempty"` - PrimaryKeyID *int `json:"primary_key_id,omitempty"` - KeyID *string `json:"key_id,omitempty"` - PublicKey *string `json:"public_key,omitempty"` - Emails []GPGEmail `json:"emails,omitempty"` - Subkeys []GPGKey `json:"subkeys,omitempty"` - CanSign *bool `json:"can_sign,omitempty"` - CanEncryptComms *bool `json:"can_encrypt_comms,omitempty"` - CanEncryptStorage *bool `json:"can_encrypt_storage,omitempty"` - CanCertify *bool `json:"can_certify,omitempty"` - CreatedAt *time.Time `json:"created_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` -} - -// String stringifies a GPGKey. -func (k GPGKey) String() string { - return Stringify(k) -} - -// GPGEmail represents an email address associated to a GPG key. -type GPGEmail struct { - Email *string `json:"email,omitempty"` - Verified *bool `json:"verified,omitempty"` -} - -// ListGPGKeys lists the public GPG keys for a user. Passing the empty -// string will fetch keys for the authenticated user. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user -func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opt *ListOptions) ([]*GPGKey, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/gpg_keys", user) - } else { - u = "user/gpg_keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - var keys []*GPGKey - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetGPGKey gets extended details for a single GPG key. It requires authentication -// via Basic Auth or via OAuth with at least read:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#get-a-single-gpg-key -func (s *UsersService) GetGPGKey(ctx context.Context, id int) (*GPGKey, *Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateGPGKey creates a GPG key. It requires authenticatation via Basic Auth -// or OAuth with at least write:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#create-a-gpg-key -func (s *UsersService) CreateGPGKey(ctx context.Context, armoredPublicKey string) (*GPGKey, *Response, error) { - gpgKey := &struct { - ArmoredPublicKey string `json:"armored_public_key"` - }{ArmoredPublicKey: armoredPublicKey} - req, err := s.client.NewRequest("POST", "user/gpg_keys", gpgKey) - if err != nil { - return nil, nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - key := &GPGKey{} - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// DeleteGPGKey deletes a GPG key. It requires authentication via Basic Auth or -// via OAuth with at least admin:gpg_key scope. -// -// GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#delete-a-gpg-key -func (s *UsersService) DeleteGPGKey(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("user/gpg_keys/%v", id) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeGitSigningPreview) - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/users_keys.go b/vendor/github.com/google/go-github/github/users_keys.go deleted file mode 100644 index 97ed4b8611..0000000000 --- a/vendor/github.com/google/go-github/github/users_keys.go +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright 2013 The go-github 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 github - -import ( - "context" - "fmt" -) - -// Key represents a public SSH key used to authenticate a user or deploy script. -type Key struct { - ID *int `json:"id,omitempty"` - Key *string `json:"key,omitempty"` - URL *string `json:"url,omitempty"` - Title *string `json:"title,omitempty"` - ReadOnly *bool `json:"read_only,omitempty"` -} - -func (k Key) String() string { - return Stringify(k) -} - -// ListKeys lists the verified public keys for a user. Passing the empty -// string will fetch keys for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#list-public-keys-for-a-user -func (s *UsersService) ListKeys(ctx context.Context, user string, opt *ListOptions) ([]*Key, *Response, error) { - var u string - if user != "" { - u = fmt.Sprintf("users/%v/keys", user) - } else { - u = "user/keys" - } - u, err := addOptions(u, opt) - if err != nil { - return nil, nil, err - } - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - var keys []*Key - resp, err := s.client.Do(ctx, req, &keys) - if err != nil { - return nil, resp, err - } - - return keys, resp, nil -} - -// GetKey fetches a single public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#get-a-single-public-key -func (s *UsersService) GetKey(ctx context.Context, id int) (*Key, *Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - key := new(Key) - resp, err := s.client.Do(ctx, req, key) - if err != nil { - return nil, resp, err - } - - return key, resp, nil -} - -// CreateKey adds a public key for the authenticated user. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#create-a-public-key -func (s *UsersService) CreateKey(ctx context.Context, key *Key) (*Key, *Response, error) { - u := "user/keys" - - req, err := s.client.NewRequest("POST", u, key) - if err != nil { - return nil, nil, err - } - - k := new(Key) - resp, err := s.client.Do(ctx, req, k) - if err != nil { - return nil, resp, err - } - - return k, resp, nil -} - -// DeleteKey deletes a public key. -// -// GitHub API docs: https://developer.github.com/v3/users/keys/#delete-a-public-key -func (s *UsersService) DeleteKey(ctx context.Context, id int) (*Response, error) { - u := fmt.Sprintf("user/keys/%v", id) - - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(ctx, req, nil) -} diff --git a/vendor/github.com/google/go-github/github/with_appengine.go b/vendor/github.com/google/go-github/github/with_appengine.go deleted file mode 100644 index 957c4d3079..0000000000 --- a/vendor/github.com/google/go-github/github/with_appengine.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2017 The go-github 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 appengine - -// This file provides glue for making github work on App Engine. -// In order to get the entire github package to compile with -// Go 1.6, you will need to rewrite all the import "context" lines. -// Fortunately, this is easy with "gofmt": -// -// gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go - -package github - -import ( - "context" - "net/http" - - "google.golang.org/appengine" -) - -func withContext(ctx context.Context, req *http.Request) (context.Context, *http.Request) { - return appengine.WithContext(ctx, req), req -} diff --git a/vendor/github.com/google/go-github/github/without_appengine.go b/vendor/github.com/google/go-github/github/without_appengine.go deleted file mode 100644 index b0edc04db1..0000000000 --- a/vendor/github.com/google/go-github/github/without_appengine.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The go-github 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 !appengine - -// This file provides glue for making github work without App Engine. - -package github - -import ( - "context" - "net/http" -) - -func withContext(ctx context.Context, req *http.Request) (context.Context, *http.Request) { - return ctx, req.WithContext(ctx) -} diff --git a/vendor/github.com/google/go-querystring/LICENSE b/vendor/github.com/google/go-querystring/LICENSE deleted file mode 100644 index ae121a1e46..0000000000 --- a/vendor/github.com/google/go-querystring/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2013 Google. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/google/go-querystring/query/encode.go b/vendor/github.com/google/go-querystring/query/encode.go deleted file mode 100644 index 37080b19b5..0000000000 --- a/vendor/github.com/google/go-querystring/query/encode.go +++ /dev/null @@ -1,320 +0,0 @@ -// 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 query implements encoding of structs into URL query parameters. -// -// As a simple example: -// -// type Options struct { -// Query string `url:"q"` -// ShowAll bool `url:"all"` -// Page int `url:"page"` -// } -// -// opt := Options{ "foo", true, 2 } -// v, _ := query.Values(opt) -// fmt.Print(v.Encode()) // will output: "q=foo&all=true&page=2" -// -// The exact mapping between Go values and url.Values is described in the -// documentation for the Values() function. -package query - -import ( - "bytes" - "fmt" - "net/url" - "reflect" - "strconv" - "strings" - "time" -) - -var timeType = reflect.TypeOf(time.Time{}) - -var encoderType = reflect.TypeOf(new(Encoder)).Elem() - -// Encoder is an interface implemented by any type that wishes to encode -// itself into URL values in a non-standard way. -type Encoder interface { - EncodeValues(key string, v *url.Values) error -} - -// Values returns the url.Values encoding of v. -// -// Values expects to be passed a struct, and traverses it recursively using the -// following encoding rules. -// -// Each exported struct field is encoded as a URL parameter unless -// -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option -// -// The empty values are false, 0, any nil pointer or interface value, any array -// slice, map, or string of length zero, and any time.Time that returns true -// for IsZero(). -// -// The URL parameter name defaults to the struct field name but can be -// specified in the struct field's tag value. The "url" key in the struct -// field's tag value is the key name, followed by an optional comma and -// options. For example: -// -// // Field is ignored by this package. -// Field int `url:"-"` -// -// // Field appears as URL parameter "myName". -// Field int `url:"myName"` -// -// // Field appears as URL parameter "myName" and the field is omitted if -// // its value is empty -// Field int `url:"myName,omitempty"` -// -// // Field appears as URL parameter "Field" (the default), but the field -// // is skipped if empty. Note the leading comma. -// Field int `url:",omitempty"` -// -// For encoding individual field values, the following type-dependent rules -// apply: -// -// Boolean values default to encoding as the strings "true" or "false". -// Including the "int" option signals that the field should be encoded as the -// strings "1" or "0". -// -// time.Time values default to encoding as RFC3339 timestamps. Including the -// "unix" option signals that the field should be encoded as a Unix time (see -// time.Unix()) -// -// Slice and Array values default to encoding as multiple URL values of the -// same name. Including the "comma" option signals that the field should be -// encoded as a single comma-delimited value. Including the "space" option -// similarly encodes the value as a single space-delimited string. Including -// the "semicolon" option will encode the value as a semicolon-delimited string. -// Including the "brackets" option signals that the multiple URL values should -// have "[]" appended to the value name. "numbered" will append a number to -// the end of each incidence of the value name, example: -// name0=value0&name1=value1, etc. -// -// Anonymous struct fields are usually encoded as if their inner exported -// fields were fields in the outer struct, subject to the standard Go -// visibility rules. An anonymous struct field with a name given in its URL -// tag is treated as having that name, rather than being anonymous. -// -// Non-nil pointer values are encoded as the value pointed to. -// -// Nested structs are encoded including parent fields in value names for -// scoping. e.g: -// -// "user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO" -// -// All other values are encoded using their default string representation. -// -// Multiple fields that encode to the same URL parameter name will be included -// as multiple URL values of the same name. -func Values(v interface{}) (url.Values, error) { - values := make(url.Values) - val := reflect.ValueOf(v) - for val.Kind() == reflect.Ptr { - if val.IsNil() { - return values, nil - } - val = val.Elem() - } - - if v == nil { - return values, nil - } - - if val.Kind() != reflect.Struct { - return nil, fmt.Errorf("query: Values() expects struct input. Got %v", val.Kind()) - } - - err := reflectValue(values, val, "") - return values, err -} - -// reflectValue populates the values parameter from the struct fields in val. -// Embedded structs are followed recursively (using the rules defined in the -// Values function documentation) breadth-first. -func reflectValue(values url.Values, val reflect.Value, scope string) error { - var embedded []reflect.Value - - typ := val.Type() - for i := 0; i < typ.NumField(); i++ { - sf := typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - - sv := val.Field(i) - tag := sf.Tag.Get("url") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if name == "" { - if sf.Anonymous && sv.Kind() == reflect.Struct { - // save embedded struct for later processing - embedded = append(embedded, sv) - continue - } - - name = sf.Name - } - - if scope != "" { - name = scope + "[" + name + "]" - } - - if opts.Contains("omitempty") && isEmptyValue(sv) { - continue - } - - if sv.Type().Implements(encoderType) { - if !reflect.Indirect(sv).IsValid() { - sv = reflect.New(sv.Type().Elem()) - } - - m := sv.Interface().(Encoder) - if err := m.EncodeValues(name, &values); err != nil { - return err - } - continue - } - - if sv.Kind() == reflect.Slice || sv.Kind() == reflect.Array { - var del byte - if opts.Contains("comma") { - del = ',' - } else if opts.Contains("space") { - del = ' ' - } else if opts.Contains("semicolon") { - del = ';' - } else if opts.Contains("brackets") { - name = name + "[]" - } - - if del != 0 { - s := new(bytes.Buffer) - first := true - for i := 0; i < sv.Len(); i++ { - if first { - first = false - } else { - s.WriteByte(del) - } - s.WriteString(valueString(sv.Index(i), opts)) - } - values.Add(name, s.String()) - } else { - for i := 0; i < sv.Len(); i++ { - k := name - if opts.Contains("numbered") { - k = fmt.Sprintf("%s%d", name, i) - } - values.Add(k, valueString(sv.Index(i), opts)) - } - } - continue - } - - for sv.Kind() == reflect.Ptr { - if sv.IsNil() { - break - } - sv = sv.Elem() - } - - if sv.Type() == timeType { - values.Add(name, valueString(sv, opts)) - continue - } - - if sv.Kind() == reflect.Struct { - reflectValue(values, sv, name) - continue - } - - values.Add(name, valueString(sv, opts)) - } - - for _, f := range embedded { - if err := reflectValue(values, f, scope); err != nil { - return err - } - } - - return nil -} - -// valueString returns the string representation of a value. -func valueString(v reflect.Value, opts tagOptions) string { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - return "" - } - v = v.Elem() - } - - if v.Kind() == reflect.Bool && opts.Contains("int") { - if v.Bool() { - return "1" - } - return "0" - } - - if v.Type() == timeType { - t := v.Interface().(time.Time) - if opts.Contains("unix") { - return strconv.FormatInt(t.Unix(), 10) - } - return t.Format(time.RFC3339) - } - - return fmt.Sprint(v.Interface()) -} - -// isEmptyValue checks if a value should be considered empty for the purposes -// of omitting fields with the "omitempty" option. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - - if v.Type() == timeType { - return v.Interface().(time.Time).IsZero() - } - - return false -} - -// tagOptions is the string following a comma in a struct field's "url" tag, or -// the empty string. It does not include the leading comma. -type tagOptions []string - -// parseTag splits a struct field's url tag into its name and comma-separated -// options. -func parseTag(tag string) (string, tagOptions) { - s := strings.Split(tag, ",") - return s[0], s[1:] -} - -// Contains checks whether the tagOptions contains the specified option. -func (o tagOptions) Contains(option string) bool { - for _, s := range o { - if s == option { - return true - } - } - return false -} diff --git a/vendor/github.com/gorilla/context/LICENSE b/vendor/github.com/gorilla/context/LICENSE deleted file mode 100644 index 0e5fb87280..0000000000 --- a/vendor/github.com/gorilla/context/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/context/README.md b/vendor/github.com/gorilla/context/README.md deleted file mode 100644 index 08f86693bc..0000000000 --- a/vendor/github.com/gorilla/context/README.md +++ /dev/null @@ -1,10 +0,0 @@ -context -======= -[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context) - -gorilla/context is a general purpose registry for global request variables. - -> Note: gorilla/context, having been born well before `context.Context` existed, does not play well -> with the shallow copying of the request that [`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) (added to net/http Go 1.7 onwards) performs. You should either use *just* gorilla/context, or moving forward, the new `http.Request.Context()`. - -Read the full documentation here: http://www.gorillatoolkit.org/pkg/context diff --git a/vendor/github.com/gorilla/context/context.go b/vendor/github.com/gorilla/context/context.go deleted file mode 100644 index 81cb128b19..0000000000 --- a/vendor/github.com/gorilla/context/context.go +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright 2012 The Gorilla 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 context - -import ( - "net/http" - "sync" - "time" -) - -var ( - mutex sync.RWMutex - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) -) - -// Set stores a value for a given key in a given request. -func Set(r *http.Request, key, val interface{}) { - mutex.Lock() - if data[r] == nil { - data[r] = make(map[interface{}]interface{}) - datat[r] = time.Now().Unix() - } - data[r][key] = val - mutex.Unlock() -} - -// Get returns a value stored for a given key in a given request. -func Get(r *http.Request, key interface{}) interface{} { - mutex.RLock() - if ctx := data[r]; ctx != nil { - value := ctx[key] - mutex.RUnlock() - return value - } - mutex.RUnlock() - return nil -} - -// GetOk returns stored value and presence state like multi-value return of map access. -func GetOk(r *http.Request, key interface{}) (interface{}, bool) { - mutex.RLock() - if _, ok := data[r]; ok { - value, ok := data[r][key] - mutex.RUnlock() - return value, ok - } - mutex.RUnlock() - return nil, false -} - -// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests. -func GetAll(r *http.Request) map[interface{}]interface{} { - mutex.RLock() - if context, ok := data[r]; ok { - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result - } - mutex.RUnlock() - return nil -} - -// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if -// the request was registered. -func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) { - mutex.RLock() - context, ok := data[r] - result := make(map[interface{}]interface{}, len(context)) - for k, v := range context { - result[k] = v - } - mutex.RUnlock() - return result, ok -} - -// Delete removes a value stored for a given key in a given request. -func Delete(r *http.Request, key interface{}) { - mutex.Lock() - if data[r] != nil { - delete(data[r], key) - } - mutex.Unlock() -} - -// Clear removes all values stored for a given request. -// -// This is usually called by a handler wrapper to clean up request -// variables at the end of a request lifetime. See ClearHandler(). -func Clear(r *http.Request) { - mutex.Lock() - clear(r) - mutex.Unlock() -} - -// clear is Clear without the lock. -func clear(r *http.Request) { - delete(data, r) - delete(datat, r) -} - -// Purge removes request data stored for longer than maxAge, in seconds. -// It returns the amount of requests removed. -// -// If maxAge <= 0, all request data is removed. -// -// This is only used for sanity check: in case context cleaning was not -// properly set some request data can be kept forever, consuming an increasing -// amount of memory. In case this is detected, Purge() must be called -// periodically until the problem is fixed. -func Purge(maxAge int) int { - mutex.Lock() - count := 0 - if maxAge <= 0 { - count = len(data) - data = make(map[*http.Request]map[interface{}]interface{}) - datat = make(map[*http.Request]int64) - } else { - min := time.Now().Unix() - int64(maxAge) - for r := range data { - if datat[r] < min { - clear(r) - count++ - } - } - } - mutex.Unlock() - return count -} - -// ClearHandler wraps an http.Handler and clears request values at the end -// of a request lifetime. -func ClearHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - defer Clear(r) - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/context/doc.go b/vendor/github.com/gorilla/context/doc.go deleted file mode 100644 index 448d1bfcac..0000000000 --- a/vendor/github.com/gorilla/context/doc.go +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright 2012 The Gorilla 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 context stores values shared during a request lifetime. - -Note: gorilla/context, having been born well before `context.Context` existed, -does not play well > with the shallow copying of the request that -[`http.Request.WithContext`](https://golang.org/pkg/net/http/#Request.WithContext) -(added to net/http Go 1.7 onwards) performs. You should either use *just* -gorilla/context, or moving forward, the new `http.Request.Context()`. - -For example, a router can set variables extracted from the URL and later -application handlers can access those values, or it can be used to store -sessions values to be saved at the end of a request. There are several -others common uses. - -The idea was posted by Brad Fitzpatrick to the go-nuts mailing list: - - http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53 - -Here's the basic usage: first define the keys that you will need. The key -type is interface{} so a key can be of any type that supports equality. -Here we define a key using a custom int type to avoid name collisions: - - package foo - - import ( - "github.com/gorilla/context" - ) - - type key int - - const MyKey key = 0 - -Then set a variable. Variables are bound to an http.Request object, so you -need a request instance to set a value: - - context.Set(r, MyKey, "bar") - -The application can later access the variable using the same key you provided: - - func MyHandler(w http.ResponseWriter, r *http.Request) { - // val is "bar". - val := context.Get(r, foo.MyKey) - - // returns ("bar", true) - val, ok := context.GetOk(r, foo.MyKey) - // ... - } - -And that's all about the basic usage. We discuss some other ideas below. - -Any type can be stored in the context. To enforce a given type, make the key -private and wrap Get() and Set() to accept and return values of a specific -type: - - type key int - - const mykey key = 0 - - // GetMyKey returns a value for this package from the request values. - func GetMyKey(r *http.Request) SomeType { - if rv := context.Get(r, mykey); rv != nil { - return rv.(SomeType) - } - return nil - } - - // SetMyKey sets a value for this package in the request values. - func SetMyKey(r *http.Request, val SomeType) { - context.Set(r, mykey, val) - } - -Variables must be cleared at the end of a request, to remove all values -that were stored. This can be done in an http.Handler, after a request was -served. Just call Clear() passing the request: - - context.Clear(r) - -...or use ClearHandler(), which conveniently wraps an http.Handler to clear -variables at the end of a request lifetime. - -The Routers from the packages gorilla/mux and gorilla/pat call Clear() -so if you are using either of them you don't need to clear the context manually. -*/ -package context diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE deleted file mode 100644 index 0e5fb87280..0000000000 --- a/vendor/github.com/gorilla/mux/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md deleted file mode 100644 index cdab8784d1..0000000000 --- a/vendor/github.com/gorilla/mux/README.md +++ /dev/null @@ -1,340 +0,0 @@ -gorilla/mux -=== -[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) -[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge) - -![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png) - -http://www.gorillatoolkit.org/pkg/mux - -Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to -their respective handler. - -The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: - -* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. -* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. -* URL hosts and paths can have variables with an optional regular expression. -* Registered URLs can be built, or "reversed", which helps maintaining references to resources. -* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. - ---- - -* [Install](#install) -* [Examples](#examples) -* [Matching Routes](#matching-routes) -* [Listing Routes](#listing-routes) -* [Static Files](#static-files) -* [Registered URLs](#registered-urls) -* [Full Example](#full-example) - ---- - -## Install - -With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain: - -```sh -go get -u github.com/gorilla/mux -``` - -## Examples - -Let's start registering a couple of URL paths and handlers: - -```go -func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) -} -``` - -Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. - -Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/products/{key}", ProductHandler) -r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: - -```go -func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { - vars := mux.Vars(r) - w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, "Category: %v\n", vars["category"]) -} -``` - -And this is all you need to know about the basic usage. More advanced options are explained below. - -### Matching Routes - -Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: - -```go -r := mux.NewRouter() -// Only matches if domain is "www.example.com". -r.Host("www.example.com") -// Matches a dynamic subdomain. -r.Host("{subdomain:[a-z]+}.domain.com") -``` - -There are several other matchers that can be added. To match path prefixes: - -```go -r.PathPrefix("/products/") -``` - -...or HTTP methods: - -```go -r.Methods("GET", "POST") -``` - -...or URL schemes: - -```go -r.Schemes("https") -``` - -...or header values: - -```go -r.Headers("X-Requested-With", "XMLHttpRequest") -``` - -...or query values: - -```go -r.Queries("key", "value") -``` - -...or to use a custom matcher function: - -```go -r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 -}) -``` - -...and finally, it is possible to combine several matchers in a single route: - -```go -r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") -``` - -Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". - -For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: - -```go -r := mux.NewRouter() -s := r.Host("www.example.com").Subrouter() -``` - -Then register routes in the subrouter: - -```go -s.HandleFunc("/products/", ProductsHandler) -s.HandleFunc("/products/{key}", ProductHandler) -s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) -``` - -The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: - -```go -r := mux.NewRouter() -s := r.PathPrefix("/products").Subrouter() -// "/products/" -s.HandleFunc("/", ProductsHandler) -// "/products/{key}/" -s.HandleFunc("/{key}/", ProductHandler) -// "/products/{key}/details" -s.HandleFunc("/{key}/details", ProductDetailsHandler) -``` - -### Listing Routes - -Routes on a mux can be listed using the Router.Walk method—useful for generating documentation: - -```go -package main - -import ( - "fmt" - "net/http" - - "github.com/gorilla/mux" -) - -func handler(w http.ResponseWriter, r *http.Request) { - return -} - -func main() { - r := mux.NewRouter() - r.HandleFunc("/", handler) - r.HandleFunc("/products", handler) - r.HandleFunc("/articles", handler) - r.HandleFunc("/articles/{id}", handler) - r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { - t, err := route.GetPathTemplate() - if err != nil { - return err - } - fmt.Println(t) - return nil - }) - http.Handle("/", r) -} -``` - -### Static Files - -Note that the path provided to `PathPrefix()` represents a "wildcard": calling -`PathPrefix("/static/").Handler(...)` means that the handler will be passed any -request that matches "/static/*". This makes it easy to serve static files with mux: - -```go -func main() { - var dir string - - flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") - flag.Parse() - r := mux.NewRouter() - - // This will serve files under http://localhost:8000/static/ - r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) - - srv := &http.Server{ - Handler: r, - Addr: "127.0.0.1:8000", - // Good practice: enforce timeouts for servers you create! - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, - } - - log.Fatal(srv.ListenAndServe()) -} -``` - -### Registered URLs - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: - -```go -r := mux.NewRouter() -r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") -``` - -To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: - -```go -url, err := r.Get("article").URL("category", "technology", "id", "42") -``` - -...and the result will be a `url.URL` with the following path: - -``` -"/articles/technology/42" -``` - -This also works for host variables: - -```go -r := mux.NewRouter() -r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// url.String() will be "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - -```go -r.HeadersRegexp("Content-Type", "application/(text|json)") -``` - -...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` - -There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: - -```go -// "http://news.domain.com/" -host, err := r.Get("article").URLHost("subdomain", "news") - -// "/articles/technology/42" -path, err := r.Get("article").URLPath("category", "technology", "id", "42") -``` - -And if you use subrouters, host and path defined separately can be built as well: - -```go -r := mux.NewRouter() -s := r.Host("{subdomain}.domain.com").Subrouter() -s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - -// "http://news.domain.com/articles/technology/42" -url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -``` - -## Full Example - -Here's a complete, runnable example of a small `mux` based server: - -```go -package main - -import ( - "net/http" - "log" - "github.com/gorilla/mux" -) - -func YourHandler(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Gorilla!\n")) -} - -func main() { - r := mux.NewRouter() - // Routes consist of a path and a handler function. - r.HandleFunc("/", YourHandler) - - // Bind to a port and pass our router in - log.Fatal(http.ListenAndServe(":8000", r)) -} -``` - -## License - -BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/mux/context_gorilla.go b/vendor/github.com/gorilla/mux/context_gorilla.go deleted file mode 100644 index d7adaa8fad..0000000000 --- a/vendor/github.com/gorilla/mux/context_gorilla.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build !go1.7 - -package mux - -import ( - "net/http" - - "github.com/gorilla/context" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return context.Get(r, key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - context.Set(r, key, val) - return r -} - -func contextClear(r *http.Request) { - context.Clear(r) -} diff --git a/vendor/github.com/gorilla/mux/context_native.go b/vendor/github.com/gorilla/mux/context_native.go deleted file mode 100644 index 209cbea7d6..0000000000 --- a/vendor/github.com/gorilla/mux/context_native.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.7 - -package mux - -import ( - "context" - "net/http" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return r.Context().Value(key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - return r.WithContext(context.WithValue(r.Context(), key, val)) -} - -func contextClear(r *http.Request) { - return -} diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go deleted file mode 100644 index 00daf4a721..0000000000 --- a/vendor/github.com/gorilla/mux/doc.go +++ /dev/null @@ -1,240 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard -http.ServeMux, mux.Router matches incoming requests against a list of -registered routes and calls a handler for the route that matches the URL -or other conditions. The main features are: - - * Requests can be matched based on URL host, path, path prefix, schemes, - header and query values, HTTP methods or using custom matchers. - * URL hosts and paths can have variables with an optional regular - expression. - * Registered URLs can be built, or "reversed", which helps maintaining - references to resources. - * Routes can be used as subrouters: nested routes are only tested if the - parent route matches. This is useful to define groups of routes that - share common conditions like a host, a path prefix or other repeated - attributes. As a bonus, this optimizes request matching. - * It implements the http.Handler interface so it is compatible with the - standard http.ServeMux. - -Let's start registering a couple of URL paths and handlers: - - func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) - } - -Here we register three routes mapping URL paths to handlers. This is -equivalent to how http.HandleFunc() works: if an incoming request URL matches -one of the paths, the corresponding handler is called passing -(http.ResponseWriter, *http.Request) as parameters. - -Paths can have variables. They are defined using the format {name} or -{name:pattern}. If a regular expression pattern is not defined, the matched -variable will be anything until the next slash. For example: - - r := mux.NewRouter() - r.HandleFunc("/products/{key}", ProductHandler) - r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) - -Groups can be used inside patterns, as long as they are non-capturing (?:re). For example: - - r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler) - -The names are used to create a map of route variables which can be retrieved -calling mux.Vars(): - - vars := mux.Vars(request) - category := vars["category"] - -Note that if any capturing groups are present, mux will panic() during parsing. To prevent -this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to -"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably -when capturing groups were present. - -And this is all you need to know about the basic usage. More advanced options -are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host -pattern to be matched. They can also have variables: - - r := mux.NewRouter() - // Only matches if domain is "www.example.com". - r.Host("www.example.com") - // Matches a dynamic subdomain. - r.Host("{subdomain:[a-z]+}.domain.com") - -There are several other matchers that can be added. To match path prefixes: - - r.PathPrefix("/products/") - -...or HTTP methods: - - r.Methods("GET", "POST") - -...or URL schemes: - - r.Schemes("https") - -...or header values: - - r.Headers("X-Requested-With", "XMLHttpRequest") - -...or query values: - - r.Queries("key", "value") - -...or to use a custom matcher function: - - r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 - }) - -...and finally, it is possible to combine several matchers in a single route: - - r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") - -Setting the same matching conditions again and again can be boring, so we have -a way to group several routes that share the same requirements. -We call it "subrouting". - -For example, let's say we have several URLs that should only match when the -host is "www.example.com". Create a route for that host and get a "subrouter" -from it: - - r := mux.NewRouter() - s := r.Host("www.example.com").Subrouter() - -Then register routes in the subrouter: - - s.HandleFunc("/products/", ProductsHandler) - s.HandleFunc("/products/{key}", ProductHandler) - s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) - -The three URL paths we registered above will only be tested if the domain is -"www.example.com", because the subrouter is tested first. This is not -only convenient, but also optimizes request matching. You can create -subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define -subrouters in a central place and then parts of the app can register its -paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, -the inner routes use it as base for their paths: - - r := mux.NewRouter() - s := r.PathPrefix("/products").Subrouter() - // "/products/" - s.HandleFunc("/", ProductsHandler) - // "/products/{key}/" - s.HandleFunc("/{key}/", ProductHandler) - // "/products/{key}/details" - s.HandleFunc("/{key}/details", ProductDetailsHandler) - -Note that the path provided to PathPrefix() represents a "wildcard": calling -PathPrefix("/static/").Handler(...) means that the handler will be passed any -request that matches "/static/*". This makes it easy to serve static files with mux: - - func main() { - var dir string - - flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") - flag.Parse() - r := mux.NewRouter() - - // This will serve files under http://localhost:8000/static/ - r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) - - srv := &http.Server{ - Handler: r, - Addr: "127.0.0.1:8000", - // Good practice: enforce timeouts for servers you create! - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, - } - - log.Fatal(srv.ListenAndServe()) - } - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, -or "reversed". We define a name calling Name() on a route. For example: - - r := mux.NewRouter() - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") - -To build a URL, get the route and call the URL() method, passing a sequence of -key/value pairs for the route variables. For the previous route, we would do: - - url, err := r.Get("article").URL("category", "technology", "id", "42") - -...and the result will be a url.URL with the following path: - - "/articles/technology/42" - -This also works for host variables: - - r := mux.NewRouter() - r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // url.String() will be "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") - -All variables defined in the route are required, and their values must -conform to the corresponding patterns. These requirements guarantee that a -generated URL will always match a registered route -- the only exception is -for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - - r.HeadersRegexp("Content-Type", "application/(text|json)") - -...and the route will match both requests with a Content-Type of `application/json` as well as -`application/text` - -There's also a way to build only the URL host or path for a route: -use the methods URLHost() or URLPath() instead. For the previous route, -we would do: - - // "http://news.domain.com/" - host, err := r.Get("article").URLHost("subdomain", "news") - - // "/articles/technology/42" - path, err := r.Get("article").URLPath("category", "technology", "id", "42") - -And if you use subrouters, host and path defined separately can be built -as well: - - r := mux.NewRouter() - s := r.Host("{subdomain}.domain.com").Subrouter() - s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -*/ -package mux diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go deleted file mode 100644 index d66ec38415..0000000000 --- a/vendor/github.com/gorilla/mux/mux.go +++ /dev/null @@ -1,542 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "path" - "regexp" - "strings" -) - -// NewRouter returns a new router instance. -func NewRouter() *Router { - return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} -} - -// Router registers routes to be matched and dispatches a handler. -// -// It implements the http.Handler interface, so it can be registered to serve -// requests: -// -// var router = mux.NewRouter() -// -// func main() { -// http.Handle("/", router) -// } -// -// Or, for Google App Engine, register it in a init() function: -// -// func init() { -// http.Handle("/", router) -// } -// -// This will send all incoming requests to the router. -type Router struct { - // Configurable Handler to be used when no route matches. - NotFoundHandler http.Handler - // Parent route, if this is a subrouter. - parent parentRoute - // Routes to be matched, in order. - routes []*Route - // Routes by name for URL building. - namedRoutes map[string]*Route - // See Router.StrictSlash(). This defines the flag for new routes. - strictSlash bool - // See Router.SkipClean(). This defines the flag for new routes. - skipClean bool - // If true, do not clear the request context after handling the request. - // This has no effect when go1.7+ is used, since the context is stored - // on the request itself. - KeepContext bool - // see Router.UseEncodedPath(). This defines a flag for all routes. - useEncodedPath bool -} - -// Match matches registered routes against the request. -func (r *Router) Match(req *http.Request, match *RouteMatch) bool { - for _, route := range r.routes { - if route.Match(req, match) { - return true - } - } - - // Closest match for a router (includes sub-routers) - if r.NotFoundHandler != nil { - match.Handler = r.NotFoundHandler - return true - } - return false -} - -// ServeHTTP dispatches the handler registered in the matched route. -// -// When there is a match, the route variables can be retrieved calling -// mux.Vars(request). -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if !r.skipClean { - path := req.URL.Path - if r.useEncodedPath { - path = getPath(req) - } - // Clean path to canonical form and redirect. - if p := cleanPath(path); p != path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) - w.WriteHeader(http.StatusMovedPermanently) - return - } - } - var match RouteMatch - var handler http.Handler - if r.Match(req, &match) { - handler = match.Handler - req = setVars(req, match.Vars) - req = setCurrentRoute(req, match.Route) - } - if handler == nil { - handler = http.NotFoundHandler() - } - if !r.KeepContext { - defer contextClear(req) - } - handler.ServeHTTP(w, req) -} - -// Get returns a route registered with the given name. -func (r *Router) Get(name string) *Route { - return r.getNamedRoutes()[name] -} - -// GetRoute returns a route registered with the given name. This method -// was renamed to Get() and remains here for backwards compatibility. -func (r *Router) GetRoute(name string) *Route { - return r.getNamedRoutes()[name] -} - -// StrictSlash defines the trailing slash behavior for new routes. The initial -// value is false. -// -// When true, if the route path is "/path/", accessing "/path" will redirect -// to the former and vice versa. In other words, your application will always -// see the path as specified in the route. -// -// When false, if the route path is "/path", accessing "/path/" will not match -// this route and vice versa. -// -// Special case: when a route sets a path prefix using the PathPrefix() method, -// strict slash is ignored for that route because the redirect behavior can't -// be determined from a prefix alone. However, any subrouters created from that -// route inherit the original StrictSlash setting. -func (r *Router) StrictSlash(value bool) *Router { - r.strictSlash = value - return r -} - -// SkipClean defines the path cleaning behaviour for new routes. The initial -// value is false. Users should be careful about which routes are not cleaned -// -// When true, if the route path is "/path//to", it will remain with the double -// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ -// -// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will -// become /fetch/http/xkcd.com/534 -func (r *Router) SkipClean(value bool) *Router { - r.skipClean = value - return r -} - -// UseEncodedPath tells the router to match the encoded original path -// to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". -// This behavior has the drawback of needing to match routes against -// r.RequestURI instead of r.URL.Path. Any modifications (such as http.StripPrefix) -// to r.URL.Path will not affect routing when this flag is on and thus may -// induce unintended behavior. -// -// If not called, the router will match the unencoded path to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to" -func (r *Router) UseEncodedPath() *Router { - r.useEncodedPath = true - return r -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// getNamedRoutes returns the map where named routes are registered. -func (r *Router) getNamedRoutes() map[string]*Route { - if r.namedRoutes == nil { - if r.parent != nil { - r.namedRoutes = r.parent.getNamedRoutes() - } else { - r.namedRoutes = make(map[string]*Route) - } - } - return r.namedRoutes -} - -// getRegexpGroup returns regexp definitions from the parent route, if any. -func (r *Router) getRegexpGroup() *routeRegexpGroup { - if r.parent != nil { - return r.parent.getRegexpGroup() - } - return nil -} - -func (r *Router) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// Route factories -// ---------------------------------------------------------------------------- - -// NewRoute registers an empty route. -func (r *Router) NewRoute() *Route { - route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath} - r.routes = append(r.routes, route) - return route -} - -// Handle registers a new route with a matcher for the URL path. -// See Route.Path() and Route.Handler(). -func (r *Router) Handle(path string, handler http.Handler) *Route { - return r.NewRoute().Path(path).Handler(handler) -} - -// HandleFunc registers a new route with a matcher for the URL path. -// See Route.Path() and Route.HandlerFunc(). -func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, - *http.Request)) *Route { - return r.NewRoute().Path(path).HandlerFunc(f) -} - -// Headers registers a new route with a matcher for request header values. -// See Route.Headers(). -func (r *Router) Headers(pairs ...string) *Route { - return r.NewRoute().Headers(pairs...) -} - -// Host registers a new route with a matcher for the URL host. -// See Route.Host(). -func (r *Router) Host(tpl string) *Route { - return r.NewRoute().Host(tpl) -} - -// MatcherFunc registers a new route with a custom matcher function. -// See Route.MatcherFunc(). -func (r *Router) MatcherFunc(f MatcherFunc) *Route { - return r.NewRoute().MatcherFunc(f) -} - -// Methods registers a new route with a matcher for HTTP methods. -// See Route.Methods(). -func (r *Router) Methods(methods ...string) *Route { - return r.NewRoute().Methods(methods...) -} - -// Path registers a new route with a matcher for the URL path. -// See Route.Path(). -func (r *Router) Path(tpl string) *Route { - return r.NewRoute().Path(tpl) -} - -// PathPrefix registers a new route with a matcher for the URL path prefix. -// See Route.PathPrefix(). -func (r *Router) PathPrefix(tpl string) *Route { - return r.NewRoute().PathPrefix(tpl) -} - -// Queries registers a new route with a matcher for URL query values. -// See Route.Queries(). -func (r *Router) Queries(pairs ...string) *Route { - return r.NewRoute().Queries(pairs...) -} - -// Schemes registers a new route with a matcher for URL schemes. -// See Route.Schemes(). -func (r *Router) Schemes(schemes ...string) *Route { - return r.NewRoute().Schemes(schemes...) -} - -// BuildVarsFunc registers a new route with a custom function for modifying -// route variables before building a URL. -func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { - return r.NewRoute().BuildVarsFunc(f) -} - -// Walk walks the router and all its sub-routers, calling walkFn for each route -// in the tree. The routes are walked in the order they were added. Sub-routers -// are explored depth-first. -func (r *Router) Walk(walkFn WalkFunc) error { - return r.walk(walkFn, []*Route{}) -} - -// SkipRouter is used as a return value from WalkFuncs to indicate that the -// router that walk is about to descend down to should be skipped. -var SkipRouter = errors.New("skip this router") - -// WalkFunc is the type of the function called for each route visited by Walk. -// At every invocation, it is given the current route, and the current router, -// and a list of ancestor routes that lead to the current route. -type WalkFunc func(route *Route, router *Router, ancestors []*Route) error - -func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { - for _, t := range r.routes { - if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" { - continue - } - - err := walkFn(t, r, ancestors) - if err == SkipRouter { - continue - } - if err != nil { - return err - } - for _, sr := range t.matchers { - if h, ok := sr.(*Router); ok { - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - } - } - if h, ok := t.handler.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - return nil -} - -// ---------------------------------------------------------------------------- -// Context -// ---------------------------------------------------------------------------- - -// RouteMatch stores information about a matched route. -type RouteMatch struct { - Route *Route - Handler http.Handler - Vars map[string]string -} - -type contextKey int - -const ( - varsKey contextKey = iota - routeKey -) - -// Vars returns the route variables for the current request, if any. -func Vars(r *http.Request) map[string]string { - if rv := contextGet(r, varsKey); rv != nil { - return rv.(map[string]string) - } - return nil -} - -// CurrentRoute returns the matched route for the current request, if any. -// This only works when called inside the handler of the matched route -// because the matched route is stored in the request context which is cleared -// after the handler returns, unless the KeepContext option is set on the -// Router. -func CurrentRoute(r *http.Request) *Route { - if rv := contextGet(r, routeKey); rv != nil { - return rv.(*Route) - } - return nil -} - -func setVars(r *http.Request, val interface{}) *http.Request { - return contextSet(r, varsKey, val) -} - -func setCurrentRoute(r *http.Request, val interface{}) *http.Request { - return contextSet(r, routeKey, val) -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -// getPath returns the escaped path if possible; doing what URL.EscapedPath() -// which was added in go1.5 does -func getPath(req *http.Request) string { - if req.RequestURI != "" { - // Extract the path from RequestURI (which is escaped unlike URL.Path) - // as detailed here as detailed in https://golang.org/pkg/net/url/#URL - // for < 1.5 server side workaround - // http://localhost/path/here?v=1 -> /path/here - path := req.RequestURI - path = strings.TrimPrefix(path, req.URL.Scheme+`://`) - path = strings.TrimPrefix(path, req.URL.Host) - if i := strings.LastIndex(path, "?"); i > -1 { - path = path[:i] - } - if i := strings.LastIndex(path, "#"); i > -1 { - path = path[:i] - } - return path - } - return req.URL.Path -} - -// cleanPath returns the canonical path for p, eliminating . and .. elements. -// Borrowed from the net/http package. -func cleanPath(p string) string { - if p == "" { - return "/" - } - if p[0] != '/' { - p = "/" + p - } - np := path.Clean(p) - // path.Clean removes trailing slash except for root; - // put the trailing slash back if necessary. - if p[len(p)-1] == '/' && np != "/" { - np += "/" - } - - return np -} - -// uniqueVars returns an error if two slices contain duplicated strings. -func uniqueVars(s1, s2 []string) error { - for _, v1 := range s1 { - for _, v2 := range s2 { - if v1 == v2 { - return fmt.Errorf("mux: duplicated route variable %q", v2) - } - } - } - return nil -} - -// checkPairs returns the count of strings passed in, and an error if -// the count is not an even number. -func checkPairs(pairs ...string) (int, error) { - length := len(pairs) - if length%2 != 0 { - return length, fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - } - return length, nil -} - -// mapFromPairsToString converts variadic string parameters to a -// string to string map. -func mapFromPairsToString(pairs ...string) (map[string]string, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]string, length/2) - for i := 0; i < length; i += 2 { - m[pairs[i]] = pairs[i+1] - } - return m, nil -} - -// mapFromPairsToRegex converts variadic string paramers to a -// string to regex map. -func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]*regexp.Regexp, length/2) - for i := 0; i < length; i += 2 { - regex, err := regexp.Compile(pairs[i+1]) - if err != nil { - return nil, err - } - m[pairs[i]] = regex - } - return m, nil -} - -// matchInArray returns true if the given string value is in the array. -func matchInArray(arr []string, value string) bool { - for _, v := range arr { - if v == value { - return true - } - } - return false -} - -// matchMapWithString returns true if the given key/value pairs exist in a given map. -func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != "" { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v == value { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against -// the given regex -func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != nil { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v.MatchString(value) { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go deleted file mode 100644 index 0189ad346f..0000000000 --- a/vendor/github.com/gorilla/mux/regexp.go +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "bytes" - "fmt" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" -) - -// newRouteRegexp parses a route template and returns a routeRegexp, -// used to match a host, a path or a query string. -// -// It will extract named variables, assemble a regexp to be matched, create -// a "reverse" template to build URLs and compile regexps to validate variable -// values used in URL building. -// -// Previously we accepted only Python-like identifiers for variable -// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that -// name and pattern can't be empty, and names can't contain a colon. -func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) { - // Check if it is well-formed. - idxs, errBraces := braceIndices(tpl) - if errBraces != nil { - return nil, errBraces - } - // Backup the original. - template := tpl - // Now let's parse it. - defaultPattern := "[^/]+" - if matchQuery { - defaultPattern = "[^?&]*" - } else if matchHost { - defaultPattern = "[^.]+" - matchPrefix = false - } - // Only match strict slash if not matching - if matchPrefix || matchHost || matchQuery { - strictSlash = false - } - // Set a flag for strictSlash. - endSlash := false - if strictSlash && strings.HasSuffix(tpl, "/") { - tpl = tpl[:len(tpl)-1] - endSlash = true - } - varsN := make([]string, len(idxs)/2) - varsR := make([]*regexp.Regexp, len(idxs)/2) - pattern := bytes.NewBufferString("") - pattern.WriteByte('^') - reverse := bytes.NewBufferString("") - var end int - var err error - for i := 0; i < len(idxs); i += 2 { - // Set all values we are interested in. - raw := tpl[end:idxs[i]] - end = idxs[i+1] - parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) - name := parts[0] - patt := defaultPattern - if len(parts) == 2 { - patt = parts[1] - } - // Name or pattern can't be empty. - if name == "" || patt == "" { - return nil, fmt.Errorf("mux: missing name or pattern in %q", - tpl[idxs[i]:end]) - } - // Build the regexp pattern. - fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) - - // Build the reverse template. - fmt.Fprintf(reverse, "%s%%s", raw) - - // Append variable name and compiled pattern. - varsN[i/2] = name - varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) - if err != nil { - return nil, err - } - } - // Add the remaining. - raw := tpl[end:] - pattern.WriteString(regexp.QuoteMeta(raw)) - if strictSlash { - pattern.WriteString("[/]?") - } - if matchQuery { - // Add the default pattern if the query value is empty - if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { - pattern.WriteString(defaultPattern) - } - } - if !matchPrefix { - pattern.WriteByte('$') - } - reverse.WriteString(raw) - if endSlash { - reverse.WriteByte('/') - } - // Compile full regexp. - reg, errCompile := regexp.Compile(pattern.String()) - if errCompile != nil { - return nil, errCompile - } - - // Check for capturing groups which used to work in older versions - if reg.NumSubexp() != len(idxs)/2 { - panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) + - "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)") - } - - // Done! - return &routeRegexp{ - template: template, - matchHost: matchHost, - matchQuery: matchQuery, - strictSlash: strictSlash, - useEncodedPath: useEncodedPath, - regexp: reg, - reverse: reverse.String(), - varsN: varsN, - varsR: varsR, - }, nil -} - -// routeRegexp stores a regexp to match a host or path and information to -// collect and validate route variables. -type routeRegexp struct { - // The unmodified template. - template string - // True for host match, false for path or query string match. - matchHost bool - // True for query string match, false for path and host match. - matchQuery bool - // The strictSlash value defined on the route, but disabled if PathPrefix was used. - strictSlash bool - // Determines whether to use encoded path from getPath function or unencoded - // req.URL.Path for path matching - useEncodedPath bool - // Expanded regexp. - regexp *regexp.Regexp - // Reverse template. - reverse string - // Variable names. - varsN []string - // Variable regexps (validators). - varsR []*regexp.Regexp -} - -// Match matches the regexp against the URL host or path. -func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { - if !r.matchHost { - if r.matchQuery { - return r.matchQueryString(req) - } - path := req.URL.Path - if r.useEncodedPath { - path = getPath(req) - } - return r.regexp.MatchString(path) - } - - return r.regexp.MatchString(getHost(req)) -} - -// url builds a URL part using the given values. -func (r *routeRegexp) url(values map[string]string) (string, error) { - urlValues := make([]interface{}, len(r.varsN)) - for k, v := range r.varsN { - value, ok := values[v] - if !ok { - return "", fmt.Errorf("mux: missing route variable %q", v) - } - urlValues[k] = value - } - rv := fmt.Sprintf(r.reverse, urlValues...) - if !r.regexp.MatchString(rv) { - // The URL is checked against the full regexp, instead of checking - // individual variables. This is faster but to provide a good error - // message, we check individual regexps if the URL doesn't match. - for k, v := range r.varsN { - if !r.varsR[k].MatchString(values[v]) { - return "", fmt.Errorf( - "mux: variable %q doesn't match, expected %q", values[v], - r.varsR[k].String()) - } - } - } - return rv, nil -} - -// getURLQuery returns a single query parameter from a request URL. -// For a URL with foo=bar&baz=ding, we return only the relevant key -// value pair for the routeRegexp. -func (r *routeRegexp) getURLQuery(req *http.Request) string { - if !r.matchQuery { - return "" - } - templateKey := strings.SplitN(r.template, "=", 2)[0] - for key, vals := range req.URL.Query() { - if key == templateKey && len(vals) > 0 { - return key + "=" + vals[0] - } - } - return "" -} - -func (r *routeRegexp) matchQueryString(req *http.Request) bool { - return r.regexp.MatchString(r.getURLQuery(req)) -} - -// braceIndices returns the first level curly brace indices from a string. -// It returns an error in case of unbalanced braces. -func braceIndices(s string) ([]int, error) { - var level, idx int - var idxs []int - for i := 0; i < len(s); i++ { - switch s[i] { - case '{': - if level++; level == 1 { - idx = i - } - case '}': - if level--; level == 0 { - idxs = append(idxs, idx, i+1) - } else if level < 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - } - } - if level != 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - return idxs, nil -} - -// varGroupName builds a capturing group name for the indexed variable. -func varGroupName(idx int) string { - return "v" + strconv.Itoa(idx) -} - -// ---------------------------------------------------------------------------- -// routeRegexpGroup -// ---------------------------------------------------------------------------- - -// routeRegexpGroup groups the route matchers that carry variables. -type routeRegexpGroup struct { - host *routeRegexp - path *routeRegexp - queries []*routeRegexp -} - -// setMatch extracts the variables from the URL once a route matches. -func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { - // Store host variables. - if v.host != nil { - host := getHost(req) - matches := v.host.regexp.FindStringSubmatchIndex(host) - if len(matches) > 0 { - extractVars(host, matches, v.host.varsN, m.Vars) - } - } - path := req.URL.Path - if r.useEncodedPath { - path = getPath(req) - } - // Store path variables. - if v.path != nil { - matches := v.path.regexp.FindStringSubmatchIndex(path) - if len(matches) > 0 { - extractVars(path, matches, v.path.varsN, m.Vars) - // Check if we should redirect. - if v.path.strictSlash { - p1 := strings.HasSuffix(path, "/") - p2 := strings.HasSuffix(v.path.template, "/") - if p1 != p2 { - u, _ := url.Parse(req.URL.String()) - if p1 { - u.Path = u.Path[:len(u.Path)-1] - } else { - u.Path += "/" - } - m.Handler = http.RedirectHandler(u.String(), 301) - } - } - } - } - // Store query string variables. - for _, q := range v.queries { - queryURL := q.getURLQuery(req) - matches := q.regexp.FindStringSubmatchIndex(queryURL) - if len(matches) > 0 { - extractVars(queryURL, matches, q.varsN, m.Vars) - } - } -} - -// getHost tries its best to return the request host. -func getHost(r *http.Request) string { - if r.URL.IsAbs() { - return r.URL.Host - } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - -} - -func extractVars(input string, matches []int, names []string, output map[string]string) { - for i, name := range names { - output[name] = input[matches[2*i+2]:matches[2*i+3]] - } -} diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go deleted file mode 100644 index 5544c1fd6b..0000000000 --- a/vendor/github.com/gorilla/mux/route.go +++ /dev/null @@ -1,636 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "regexp" - "strings" -) - -// Route stores information to match a request and build URLs. -type Route struct { - // Parent where the route was registered (a Router). - parent parentRoute - // Request handler for the route. - handler http.Handler - // List of matchers. - matchers []matcher - // Manager for the variables from host and path. - regexp *routeRegexpGroup - // If true, when the path pattern is "/path/", accessing "/path" will - // redirect to the former and vice versa. - strictSlash bool - // If true, when the path pattern is "/path//to", accessing "/path//to" - // will not redirect - skipClean bool - // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" - useEncodedPath bool - // If true, this route never matches: it is only used to build URLs. - buildOnly bool - // The name used to build URLs. - name string - // Error resulted from building a route. - err error - - buildVarsFunc BuildVarsFunc -} - -func (r *Route) SkipClean() bool { - return r.skipClean -} - -// Match matches the route against the request. -func (r *Route) Match(req *http.Request, match *RouteMatch) bool { - if r.buildOnly || r.err != nil { - return false - } - // Match everything. - for _, m := range r.matchers { - if matched := m.Match(req, match); !matched { - return false - } - } - // Yay, we have a match. Let's collect some info about it. - if match.Route == nil { - match.Route = r - } - if match.Handler == nil { - match.Handler = r.handler - } - if match.Vars == nil { - match.Vars = make(map[string]string) - } - // Set variables. - if r.regexp != nil { - r.regexp.setMatch(req, match, r) - } - return true -} - -// ---------------------------------------------------------------------------- -// Route attributes -// ---------------------------------------------------------------------------- - -// GetError returns an error resulted from building the route, if any. -func (r *Route) GetError() error { - return r.err -} - -// BuildOnly sets the route to never match: it is only used to build URLs. -func (r *Route) BuildOnly() *Route { - r.buildOnly = true - return r -} - -// Handler -------------------------------------------------------------------- - -// Handler sets a handler for the route. -func (r *Route) Handler(handler http.Handler) *Route { - if r.err == nil { - r.handler = handler - } - return r -} - -// HandlerFunc sets a handler function for the route. -func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { - return r.Handler(http.HandlerFunc(f)) -} - -// GetHandler returns the handler for the route, if any. -func (r *Route) GetHandler() http.Handler { - return r.handler -} - -// Name ----------------------------------------------------------------------- - -// Name sets the name for the route, used to build URLs. -// If the name was registered already it will be overwritten. -func (r *Route) Name(name string) *Route { - if r.name != "" { - r.err = fmt.Errorf("mux: route already has name %q, can't set %q", - r.name, name) - } - if r.err == nil { - r.name = name - r.getNamedRoutes()[name] = r - } - return r -} - -// GetName returns the name for the route, if any. -func (r *Route) GetName() string { - return r.name -} - -// ---------------------------------------------------------------------------- -// Matchers -// ---------------------------------------------------------------------------- - -// matcher types try to match a request. -type matcher interface { - Match(*http.Request, *RouteMatch) bool -} - -// addMatcher adds a matcher to the route. -func (r *Route) addMatcher(m matcher) *Route { - if r.err == nil { - r.matchers = append(r.matchers, m) - } - return r -} - -// addRegexpMatcher adds a host or path matcher and builder to a route. -func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { - if r.err != nil { - return r.err - } - r.regexp = r.getRegexpGroup() - if !matchHost && !matchQuery { - if len(tpl) > 0 && tpl[0] != '/' { - return fmt.Errorf("mux: path must start with a slash, got %q", tpl) - } - if r.regexp.path != nil { - tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl - } - } - rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash, r.useEncodedPath) - if err != nil { - return err - } - for _, q := range r.regexp.queries { - if err = uniqueVars(rr.varsN, q.varsN); err != nil { - return err - } - } - if matchHost { - if r.regexp.path != nil { - if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { - return err - } - } - r.regexp.host = rr - } else { - if r.regexp.host != nil { - if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { - return err - } - } - if matchQuery { - r.regexp.queries = append(r.regexp.queries, rr) - } else { - r.regexp.path = rr - } - } - r.addMatcher(rr) - return nil -} - -// Headers -------------------------------------------------------------------- - -// headerMatcher matches the request against header values. -type headerMatcher map[string]string - -func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithString(m, r.Header, true) -} - -// Headers adds a matcher for request header values. -// It accepts a sequence of key/value pairs to be matched. For example: -// -// r := mux.NewRouter() -// r.Headers("Content-Type", "application/json", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both request header values match. -// If the value is an empty string, it will match any value if the key is set. -func (r *Route) Headers(pairs ...string) *Route { - if r.err == nil { - var headers map[string]string - headers, r.err = mapFromPairsToString(pairs...) - return r.addMatcher(headerMatcher(headers)) - } - return r -} - -// headerRegexMatcher matches the request against the route given a regex for the header -type headerRegexMatcher map[string]*regexp.Regexp - -func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithRegex(m, r.Header, true) -} - -// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex -// support. For example: -// -// r := mux.NewRouter() -// r.HeadersRegexp("Content-Type", "application/(text|json)", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both the request header matches both regular expressions. -// It the value is an empty string, it will match any value if the key is set. -func (r *Route) HeadersRegexp(pairs ...string) *Route { - if r.err == nil { - var headers map[string]*regexp.Regexp - headers, r.err = mapFromPairsToRegex(pairs...) - return r.addMatcher(headerRegexMatcher(headers)) - } - return r -} - -// Host ----------------------------------------------------------------------- - -// Host adds a matcher for the URL host. -// It accepts a template with zero or more URL variables enclosed by {}. -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next dot. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Host("www.example.com") -// r.Host("{subdomain}.domain.com") -// r.Host("{subdomain:[a-z]+}.domain.com") -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Host(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, true, false, false) - return r -} - -// MatcherFunc ---------------------------------------------------------------- - -// MatcherFunc is the function signature used by custom matchers. -type MatcherFunc func(*http.Request, *RouteMatch) bool - -// Match returns the match for a given request. -func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { - return m(r, match) -} - -// MatcherFunc adds a custom function to be used as request matcher. -func (r *Route) MatcherFunc(f MatcherFunc) *Route { - return r.addMatcher(f) -} - -// Methods -------------------------------------------------------------------- - -// methodMatcher matches the request against HTTP methods. -type methodMatcher []string - -func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.Method) -} - -// Methods adds a matcher for HTTP methods. -// It accepts a sequence of one or more methods to be matched, e.g.: -// "GET", "POST", "PUT". -func (r *Route) Methods(methods ...string) *Route { - for k, v := range methods { - methods[k] = strings.ToUpper(v) - } - return r.addMatcher(methodMatcher(methods)) -} - -// Path ----------------------------------------------------------------------- - -// Path adds a matcher for the URL path. -// It accepts a template with zero or more URL variables enclosed by {}. The -// template must start with a "/". -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Path("/products/").Handler(ProductsHandler) -// r.Path("/products/{key}").Handler(ProductsHandler) -// r.Path("/articles/{category}/{id:[0-9]+}"). -// Handler(ArticleHandler) -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Path(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, false, false) - return r -} - -// PathPrefix ----------------------------------------------------------------- - -// PathPrefix adds a matcher for the URL path prefix. This matches if the given -// template is a prefix of the full URL path. See Route.Path() for details on -// the tpl argument. -// -// Note that it does not treat slashes specially ("/foobar/" will be matched by -// the prefix "/foo") so you may want to use a trailing slash here. -// -// Also note that the setting of Router.StrictSlash() has no effect on routes -// with a PathPrefix matcher. -func (r *Route) PathPrefix(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, true, false) - return r -} - -// Query ---------------------------------------------------------------------- - -// Queries adds a matcher for URL query values. -// It accepts a sequence of key/value pairs. Values may define variables. -// For example: -// -// r := mux.NewRouter() -// r.Queries("foo", "bar", "id", "{id:[0-9]+}") -// -// The above route will only match if the URL contains the defined queries -// values, e.g.: ?foo=bar&id=42. -// -// It the value is an empty string, it will match any value if the key is set. -// -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -func (r *Route) Queries(pairs ...string) *Route { - length := len(pairs) - if length%2 != 0 { - r.err = fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - return nil - } - for i := 0; i < length; i += 2 { - if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { - return r - } - } - - return r -} - -// Schemes -------------------------------------------------------------------- - -// schemeMatcher matches the request against URL schemes. -type schemeMatcher []string - -func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.URL.Scheme) -} - -// Schemes adds a matcher for URL schemes. -// It accepts a sequence of schemes to be matched, e.g.: "http", "https". -func (r *Route) Schemes(schemes ...string) *Route { - for k, v := range schemes { - schemes[k] = strings.ToLower(v) - } - return r.addMatcher(schemeMatcher(schemes)) -} - -// BuildVarsFunc -------------------------------------------------------------- - -// BuildVarsFunc is the function signature used by custom build variable -// functions (which can modify route variables before a route's URL is built). -type BuildVarsFunc func(map[string]string) map[string]string - -// BuildVarsFunc adds a custom function to be used to modify build variables -// before a route's URL is built. -func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { - r.buildVarsFunc = f - return r -} - -// Subrouter ------------------------------------------------------------------ - -// Subrouter creates a subrouter for the route. -// -// It will test the inner routes only if the parent route matched. For example: -// -// r := mux.NewRouter() -// s := r.Host("www.example.com").Subrouter() -// s.HandleFunc("/products/", ProductsHandler) -// s.HandleFunc("/products/{key}", ProductHandler) -// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -// -// Here, the routes registered in the subrouter won't be tested if the host -// doesn't match. -func (r *Route) Subrouter() *Router { - router := &Router{parent: r, strictSlash: r.strictSlash} - r.addMatcher(router) - return router -} - -// ---------------------------------------------------------------------------- -// URL building -// ---------------------------------------------------------------------------- - -// URL builds a URL for the route. -// -// It accepts a sequence of key/value pairs for the route variables. For -// example, given this route: -// -// r := mux.NewRouter() -// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// ...a URL for it can be built using: -// -// url, err := r.Get("article").URL("category", "technology", "id", "42") -// -// ...which will return an url.URL with the following path: -// -// "/articles/technology/42" -// -// This also works for host variables: -// -// r := mux.NewRouter() -// r.Host("{subdomain}.domain.com"). -// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// // url.String() will be "http://news.domain.com/articles/technology/42" -// url, err := r.Get("article").URL("subdomain", "news", -// "category", "technology", -// "id", "42") -// -// All variables defined in the route are required, and their values must -// conform to the corresponding patterns. -func (r *Route) URL(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil { - return nil, errors.New("mux: route doesn't have a host or path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - var scheme, host, path string - if r.regexp.host != nil { - // Set a default scheme. - scheme = "http" - if host, err = r.regexp.host.url(values); err != nil { - return nil, err - } - } - if r.regexp.path != nil { - if path, err = r.regexp.path.url(values); err != nil { - return nil, err - } - } - return &url.URL{ - Scheme: scheme, - Host: host, - Path: path, - }, nil -} - -// URLHost builds the host part of the URL for a route. See Route.URL(). -// -// The route must have a host defined. -func (r *Route) URLHost(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.host == nil { - return nil, errors.New("mux: route doesn't have a host") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - host, err := r.regexp.host.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Scheme: "http", - Host: host, - }, nil -} - -// URLPath builds the path part of the URL for a route. See Route.URL(). -// -// The route must have a path defined. -func (r *Route) URLPath(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.path == nil { - return nil, errors.New("mux: route doesn't have a path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - path, err := r.regexp.path.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Path: path, - }, nil -} - -// GetPathTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a path. -func (r *Route) GetPathTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.path == nil { - return "", errors.New("mux: route doesn't have a path") - } - return r.regexp.path.template, nil -} - -// GetHostTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a host. -func (r *Route) GetHostTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.host == nil { - return "", errors.New("mux: route doesn't have a host") - } - return r.regexp.host.template, nil -} - -// prepareVars converts the route variable pairs into a map. If the route has a -// BuildVarsFunc, it is invoked. -func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { - m, err := mapFromPairsToString(pairs...) - if err != nil { - return nil, err - } - return r.buildVars(m), nil -} - -func (r *Route) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - if r.buildVarsFunc != nil { - m = r.buildVarsFunc(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// parentRoute allows routes to know about parent host and path definitions. -type parentRoute interface { - getNamedRoutes() map[string]*Route - getRegexpGroup() *routeRegexpGroup - buildVars(map[string]string) map[string]string -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Route) getNamedRoutes() map[string]*Route { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - return r.parent.getNamedRoutes() -} - -// getRegexpGroup returns regexp definitions from this route. -func (r *Route) getRegexpGroup() *routeRegexpGroup { - if r.regexp == nil { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - regexp := r.parent.getRegexpGroup() - if regexp == nil { - r.regexp = new(routeRegexpGroup) - } else { - // Copy. - r.regexp = &routeRegexpGroup{ - host: regexp.host, - path: regexp.path, - queries: regexp.queries, - } - } - } - return r.regexp -} diff --git a/vendor/github.com/imdario/mergo/CODE_OF_CONDUCT.md b/vendor/github.com/imdario/mergo/CODE_OF_CONDUCT.md deleted file mode 100644 index 469b44907a..0000000000 --- a/vendor/github.com/imdario/mergo/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at i@dario.im. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] - -[homepage]: http://contributor-covenant.org -[version]: http://contributor-covenant.org/version/1/4/ diff --git a/vendor/github.com/imdario/mergo/LICENSE b/vendor/github.com/imdario/mergo/LICENSE deleted file mode 100644 index 686680298d..0000000000 --- a/vendor/github.com/imdario/mergo/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2013 Dario Castañé. All rights reserved. -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md deleted file mode 100644 index b131069799..0000000000 --- a/vendor/github.com/imdario/mergo/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# Mergo - -A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements. - -Also a lovely [comune](http://en.wikipedia.org/wiki/Mergo) (municipality) in the Province of Ancona in the Italian region Marche. - -![Mergo dall'alto](http://www.comune.mergo.an.it/Siti/Mergo/Immagini/Foto/mergo_dall_alto.jpg) - -## Status - -It is ready for production use. It works fine after extensive use in the wild. - -[![Build Status][1]][2] -[![GoDoc][3]][4] -[![GoCard][5]][6] - -[1]: https://travis-ci.org/imdario/mergo.png -[2]: https://travis-ci.org/imdario/mergo -[3]: https://godoc.org/github.com/imdario/mergo?status.svg -[4]: https://godoc.org/github.com/imdario/mergo -[5]: https://goreportcard.com/badge/imdario/mergo -[6]: https://goreportcard.com/report/github.com/imdario/mergo - -### Important note - -Mergo is intended to assign **only** zero value fields on destination with source value. Since April 6th it works like this. Before it didn't work properly, causing some random overwrites. After some issues and PRs I found it didn't merge as I designed it. Thanks to [imdario/mergo#8](https://github.com/imdario/mergo/pull/8) overwriting functions were added and the wrong behavior was clearly detected. - -If you were using Mergo **before** April 6th 2015, please check your project works as intended after updating your local copy with ```go get -u github.com/imdario/mergo```. I apologize for any issue caused by its previous behavior and any future bug that Mergo could cause (I hope it won't!) in existing projects after the change (release 0.2.0). - -### Mergo in the wild - -- [docker/docker](https://github.com/docker/docker/) -- [kubernetes/kubernetes](https://github.com/kubernetes/kubernetes) -- [imdario/zas](https://github.com/imdario/zas) -- [soniah/dnsmadeeasy](https://github.com/soniah/dnsmadeeasy) -- [EagerIO/Stout](https://github.com/EagerIO/Stout) -- [lynndylanhurley/defsynth-api](https://github.com/lynndylanhurley/defsynth-api) -- [russross/canvasassignments](https://github.com/russross/canvasassignments) -- [rdegges/cryptly-api](https://github.com/rdegges/cryptly-api) -- [casualjim/exeggutor](https://github.com/casualjim/exeggutor) -- [divshot/gitling](https://github.com/divshot/gitling) -- [RWJMurphy/gorl](https://github.com/RWJMurphy/gorl) -- [andrerocker/deploy42](https://github.com/andrerocker/deploy42) -- [elwinar/rambler](https://github.com/elwinar/rambler) -- [tmaiaroto/gopartman](https://github.com/tmaiaroto/gopartman) -- [jfbus/impressionist](https://github.com/jfbus/impressionist) -- [Jmeyering/zealot](https://github.com/Jmeyering/zealot) -- [godep-migrator/rigger-host](https://github.com/godep-migrator/rigger-host) -- [Dronevery/MultiwaySwitch-Go](https://github.com/Dronevery/MultiwaySwitch-Go) -- [thoas/picfit](https://github.com/thoas/picfit) -- [mantasmatelis/whooplist-server](https://github.com/mantasmatelis/whooplist-server) -- [jnuthong/item_search](https://github.com/jnuthong/item_search) -- [Iris Web Framework](https://github.com/kataras/iris) - -## Installation - - go get github.com/imdario/mergo - - // use in your .go code - import ( - "github.com/imdario/mergo" - ) - -## Usage - -You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. Also maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection). - -```go -if err := mergo.Merge(&dst, src); err != nil { - // ... -} -``` - -Also, you can merge overwriting values using MergeWithOverwrite. - -```go -if err := mergo.MergeWithOverwrite(&dst, src); err != nil { - // ... -} -``` - -Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field. - -```go -if err := mergo.Map(&dst, srcMap); err != nil { - // ... -} -``` - -Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values. - -More information and examples in [godoc documentation](http://godoc.org/github.com/imdario/mergo). - -### Nice example - -```go -package main - -import ( - "fmt" - "github.com/imdario/mergo" -) - -type Foo struct { - A string - B int64 -} - -func main() { - src := Foo{ - A: "one", - B: 2, - } - - dest := Foo{ - A: "two", - } - - mergo.Merge(&dest, src) - - fmt.Println(dest) - // Will print - // {two 2} -} -``` - -Note: if test are failing due missing package, please execute: - - go get gopkg.in/yaml.v1 - -## Contact me - -If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): [@im_dario](https://twitter.com/im_dario) - -## About - -Written by [Dario Castañé](http://dario.im). - -## License - -[BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). diff --git a/vendor/github.com/imdario/mergo/doc.go b/vendor/github.com/imdario/mergo/doc.go deleted file mode 100644 index 6e9aa7baf3..0000000000 --- a/vendor/github.com/imdario/mergo/doc.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 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 mergo merges same-type structs and maps by setting default values in zero-value fields. - -Mergo won't merge unexported (private) fields but will do recursively any exported one. It also won't merge structs inside maps (because they are not addressable using Go reflection). - -Usage - -From my own work-in-progress project: - - type networkConfig struct { - Protocol string - Address string - ServerType string `json: "server_type"` - Port uint16 - } - - type FssnConfig struct { - Network networkConfig - } - - var fssnDefault = FssnConfig { - networkConfig { - "tcp", - "127.0.0.1", - "http", - 31560, - }, - } - - // Inside a function [...] - - if err := mergo.Merge(&config, fssnDefault); err != nil { - log.Fatal(err) - } - - // More code [...] - -*/ -package mergo diff --git a/vendor/github.com/imdario/mergo/issue17_test.go b/vendor/github.com/imdario/mergo/issue17_test.go deleted file mode 100644 index 0ee96f3771..0000000000 --- a/vendor/github.com/imdario/mergo/issue17_test.go +++ /dev/null @@ -1,25 +0,0 @@ -package mergo - -import ( - "encoding/json" - "testing" -) - -var ( - request = `{"timestamp":null, "name": "foo"}` - maprequest = map[string]interface{}{ - "timestamp": nil, - "name": "foo", - "newStuff": "foo", - } -) - -func TestIssue17MergeWithOverwrite(t *testing.T) { - var something map[string]interface{} - if err := json.Unmarshal([]byte(request), &something); err != nil { - t.Errorf("Error while Unmarshalling maprequest %s", err) - } - if err := MergeWithOverwrite(&something, maprequest); err != nil { - t.Errorf("Error while merging %s", err) - } -} diff --git a/vendor/github.com/imdario/mergo/issue23_test.go b/vendor/github.com/imdario/mergo/issue23_test.go deleted file mode 100644 index 9c32584131..0000000000 --- a/vendor/github.com/imdario/mergo/issue23_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package mergo - -import ( - "testing" - "time" -) - -type document struct { - Created *time.Time -} - -func TestIssue23MergeWithOverwrite(t *testing.T) { - now := time.Now() - dst := document{ - &now, - } - expected := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - src := document{ - &expected, - } - if err := MergeWithOverwrite(&dst, src); err != nil { - t.Errorf("Error while merging %s", err) - } - if dst.Created != src.Created { - t.Fatalf("Created not merged in properly: dst.Created(%v) != src.Created(%v)", dst.Created, src.Created) - } -} diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go deleted file mode 100644 index 8e8c4ba8eb..0000000000 --- a/vendor/github.com/imdario/mergo/map.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2014 Dario Castañé. All rights reserved. -// Copyright 2009 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "fmt" - "reflect" - "unicode" - "unicode/utf8" -) - -func changeInitialCase(s string, mapper func(rune) rune) string { - if s == "" { - return s - } - r, n := utf8.DecodeRuneInString(s) - return string(mapper(r)) + s[n:] -} - -func isExported(field reflect.StructField) bool { - r, _ := utf8.DecodeRuneInString(field.Name) - return r >= 'A' && r <= 'Z' -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, overwrite bool) (err error) { - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - zeroValue := reflect.Value{} - switch dst.Kind() { - case reflect.Map: - dstMap := dst.Interface().(map[string]interface{}) - for i, n := 0, src.NumField(); i < n; i++ { - srcType := src.Type() - field := srcType.Field(i) - if !isExported(field) { - continue - } - fieldName := field.Name - fieldName = changeInitialCase(fieldName, unicode.ToLower) - if v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v)) || overwrite) { - dstMap[fieldName] = src.Field(i).Interface() - } - } - case reflect.Struct: - srcMap := src.Interface().(map[string]interface{}) - for key := range srcMap { - srcValue := srcMap[key] - fieldName := changeInitialCase(key, unicode.ToUpper) - dstElement := dst.FieldByName(fieldName) - if dstElement == zeroValue { - // We discard it because the field doesn't exist. - continue - } - srcElement := reflect.ValueOf(srcValue) - dstKind := dstElement.Kind() - srcKind := srcElement.Kind() - if srcKind == reflect.Ptr && dstKind != reflect.Ptr { - srcElement = srcElement.Elem() - srcKind = reflect.TypeOf(srcElement.Interface()).Kind() - } else if dstKind == reflect.Ptr { - // Can this work? I guess it can't. - if srcKind != reflect.Ptr && srcElement.CanAddr() { - srcPtr := srcElement.Addr() - srcElement = reflect.ValueOf(srcPtr) - srcKind = reflect.Ptr - } - } - if !srcElement.IsValid() { - continue - } - if srcKind == dstKind { - if err = deepMerge(dstElement, srcElement, visited, depth+1, overwrite); err != nil { - return - } - } else { - if srcKind == reflect.Map { - if err = deepMap(dstElement, srcElement, visited, depth+1, overwrite); err != nil { - return - } - } else { - return fmt.Errorf("type mismatch on %s field: found %v, expected %v", fieldName, srcKind, dstKind) - } - } - } - } - return -} - -// Map sets fields' values in dst from src. -// src can be a map with string keys or a struct. dst must be the opposite: -// if src is a map, dst must be a valid pointer to struct. If src is a struct, -// dst must be map[string]interface{}. -// It won't merge unexported (private) fields and will do recursively -// any exported field. -// If dst is a map, keys will be src fields' names in lower camel case. -// Missing key in src that doesn't match a field in dst will be skipped. This -// doesn't apply if dst is a map. -// This is separated method from Merge because it is cleaner and it keeps sane -// semantics: merging equal types, mapping different (restricted) types. -func Map(dst, src interface{}) error { - return _map(dst, src, false) -} - -// MapWithOverwrite will do the same as Map except that non-empty dst attributes will be overriden by -// non-empty src attribute values. -func MapWithOverwrite(dst, src interface{}) error { - return _map(dst, src, true) -} - -func _map(dst, src interface{}, overwrite bool) error { - var ( - vDst, vSrc reflect.Value - err error - ) - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - // To be friction-less, we redirect equal-type arguments - // to deepMerge. Only because arguments can be anything. - if vSrc.Kind() == vDst.Kind() { - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite) - } - switch vSrc.Kind() { - case reflect.Struct: - if vDst.Kind() != reflect.Map { - return ErrExpectedMapAsDestination - } - case reflect.Map: - if vDst.Kind() != reflect.Struct { - return ErrExpectedStructAsDestination - } - default: - return ErrNotSupported - } - return deepMap(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite) -} diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go deleted file mode 100644 index 513774f4c7..0000000000 --- a/vendor/github.com/imdario/mergo/merge.go +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "reflect" -) - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, overwrite bool) (err error) { - if !src.IsValid() { - return - } - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - switch dst.Kind() { - case reflect.Struct: - for i, n := 0, dst.NumField(); i < n; i++ { - if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, overwrite); err != nil { - return - } - } - case reflect.Map: - for _, key := range src.MapKeys() { - srcElement := src.MapIndex(key) - if !srcElement.IsValid() { - continue - } - dstElement := dst.MapIndex(key) - switch srcElement.Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Slice: - if srcElement.IsNil() { - continue - } - fallthrough - default: - if !srcElement.CanInterface() { - continue - } - switch reflect.TypeOf(srcElement.Interface()).Kind() { - case reflect.Struct: - fallthrough - case reflect.Ptr: - fallthrough - case reflect.Map: - if err = deepMerge(dstElement, srcElement, visited, depth+1, overwrite); err != nil { - return - } - } - } - if !isEmptyValue(srcElement) && (overwrite || (!dstElement.IsValid() || isEmptyValue(dst))) { - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) - } - dst.SetMapIndex(key, srcElement) - } - } - case reflect.Ptr: - fallthrough - case reflect.Interface: - if src.IsNil() { - break - } else if dst.IsNil() || overwrite { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { - dst.Set(src) - } - } else if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, overwrite); err != nil { - return - } - default: - if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) { - dst.Set(src) - } - } - return -} - -// Merge will fill any empty for value type attributes on the dst struct using corresponding -// src attributes if they themselves are not empty. dst and src must be valid same-type structs -// and dst must be a pointer to struct. -// It won't merge unexported (private) fields and will do recursively any exported field. -func Merge(dst, src interface{}) error { - return merge(dst, src, false) -} - -// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overriden by -// non-empty src attribute values. -func MergeWithOverwrite(dst, src interface{}) error { - return merge(dst, src, true) -} - -func merge(dst, src interface{}, overwrite bool) error { - var ( - vDst, vSrc reflect.Value - err error - ) - if vDst, vSrc, err = resolveValues(dst, src); err != nil { - return err - } - if vDst.Type() != vSrc.Type() { - return ErrDifferentArgumentsTypes - } - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, overwrite) -} diff --git a/vendor/github.com/imdario/mergo/mergo.go b/vendor/github.com/imdario/mergo/mergo.go deleted file mode 100644 index f8a0991ec6..0000000000 --- a/vendor/github.com/imdario/mergo/mergo.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 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. - -// Based on src/pkg/reflect/deepequal.go from official -// golang's stdlib. - -package mergo - -import ( - "errors" - "reflect" -) - -// Errors reported by Mergo when it finds invalid arguments. -var ( - ErrNilArguments = errors.New("src and dst must not be nil") - ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") - ErrNotSupported = errors.New("only structs and maps are supported") - ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") - ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") -) - -// During deepMerge, must keep track of checks that are -// in progress. The comparison algorithm assumes that all -// checks in progress are true when it reencounters them. -// Visited are stored in a map indexed by 17 * a1 + a2; -type visit struct { - ptr uintptr - typ reflect.Type - next *visit -} - -// From src/pkg/encoding/json. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} - -func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { - if dst == nil || src == nil { - err = ErrNilArguments - return - } - vDst = reflect.ValueOf(dst).Elem() - if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map { - err = ErrNotSupported - return - } - vSrc = reflect.ValueOf(src) - // We check if vSrc is a pointer to dereference it. - if vSrc.Kind() == reflect.Ptr { - vSrc = vSrc.Elem() - } - return -} - -// Traverses recursively both values, assigning src's fields values to dst. -// The map argument tracks comparisons that have already been seen, which allows -// short circuiting on recursive types. -func deeper(dst, src reflect.Value, visited map[uintptr]*visit, depth int) (err error) { - if dst.CanAddr() { - addr := dst.UnsafeAddr() - h := 17 * addr - seen := visited[h] - typ := dst.Type() - for p := seen; p != nil; p = p.next { - if p.ptr == addr && p.typ == typ { - return nil - } - } - // Remember, remember... - visited[h] = &visit{addr, typ, seen} - } - return // TODO refactor -} diff --git a/vendor/github.com/imdario/mergo/mergo_test.go b/vendor/github.com/imdario/mergo/mergo_test.go deleted file mode 100644 index 1b7b4a6682..0000000000 --- a/vendor/github.com/imdario/mergo/mergo_test.go +++ /dev/null @@ -1,547 +0,0 @@ -// Copyright 2013 Dario Castañé. All rights reserved. -// Copyright 2009 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 mergo - -import ( - "io/ioutil" - "reflect" - "testing" - "time" - "gopkg.in/yaml.v2" -) - -type simpleTest struct { - Value int -} - -type complexTest struct { - St simpleTest - sz int - ID string -} - -type moreComplextText struct { - Ct complexTest - St simpleTest - Nt simpleTest -} - -type pointerTest struct { - C *simpleTest -} - -type sliceTest struct { - S []int -} - -func TestKb(t *testing.T) { - type testStruct struct { - Name string - KeyValue map[string]interface{} - } - - akv := make(map[string]interface{}) - akv["Key1"] = "not value 1" - akv["Key2"] = "value2" - a := testStruct{} - a.Name = "A" - a.KeyValue = akv - - bkv := make(map[string]interface{}) - bkv["Key1"] = "value1" - bkv["Key3"] = "value3" - b := testStruct{} - b.Name = "B" - b.KeyValue = bkv - - ekv := make(map[string]interface{}) - ekv["Key1"] = "value1" - ekv["Key2"] = "value2" - ekv["Key3"] = "value3" - expected := testStruct{} - expected.Name = "B" - expected.KeyValue = ekv - - Merge(&b, a) - - if !reflect.DeepEqual(b, expected) { - t.Errorf("Actual: %#v did not match \nExpected: %#v", b, expected) - } -} - -func TestNil(t *testing.T) { - if err := Merge(nil, nil); err != ErrNilArguments { - t.Fail() - } -} - -func TestDifferentTypes(t *testing.T) { - a := simpleTest{42} - b := 42 - if err := Merge(&a, b); err != ErrDifferentArgumentsTypes { - t.Fail() - } -} - -func TestSimpleStruct(t *testing.T) { - a := simpleTest{} - b := simpleTest{42} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value) - } - if !reflect.DeepEqual(a, b) { - t.FailNow() - } -} - -func TestComplexStruct(t *testing.T) { - a := complexTest{} - a.ID = "athing" - b := complexTest{simpleTest{42}, 1, "bthing"} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.St.Value != 42 { - t.Fatalf("b not merged in properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value) - } - if a.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz) - } - if a.ID == b.ID { - t.Fatalf("a's field ID merged unexpectedly: a.ID(%s) == b.ID(%s)", a.ID, b.ID) - } -} - -func TestComplexStructWithOverwrite(t *testing.T) { - a := complexTest{simpleTest{1}, 1, "do-not-overwrite-with-empty-value"} - b := complexTest{simpleTest{42}, 2, ""} - - expect := complexTest{simpleTest{42}, 1, "do-not-overwrite-with-empty-value"} - if err := MergeWithOverwrite(&a, b); err != nil { - t.FailNow() - } - - if !reflect.DeepEqual(a, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", a, expect) - } -} - -func TestPointerStruct(t *testing.T) { - s1 := simpleTest{} - s2 := simpleTest{19} - a := pointerTest{&s1} - b := pointerTest{&s2} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -type embeddingStruct struct { - embeddedStruct -} - -type embeddedStruct struct { - A string -} - -func TestEmbeddedStruct(t *testing.T) { - tests := []struct { - src embeddingStruct - dst embeddingStruct - expected embeddingStruct - }{ - { - src: embeddingStruct{ - embeddedStruct{"foo"}, - }, - dst: embeddingStruct{ - embeddedStruct{""}, - }, - expected: embeddingStruct{ - embeddedStruct{"foo"}, - }, - }, - { - src: embeddingStruct{ - embeddedStruct{""}, - }, - dst: embeddingStruct{ - embeddedStruct{"bar"}, - }, - expected: embeddingStruct{ - embeddedStruct{"bar"}, - }, - }, - { - src: embeddingStruct{ - embeddedStruct{"foo"}, - }, - dst: embeddingStruct{ - embeddedStruct{"bar"}, - }, - expected: embeddingStruct{ - embeddedStruct{"bar"}, - }, - }, - } - - for _, test := range tests { - err := Merge(&test.dst, test.src) - if err != nil { - t.Errorf("unexpected error: %v", err) - continue - } - if !reflect.DeepEqual(test.dst, test.expected) { - t.Errorf("unexpected output\nexpected:\n%+v\nsaw:\n%+v\n", test.expected, test.dst) - } - } -} - -func TestPointerStructNil(t *testing.T) { - a := pointerTest{nil} - b := pointerTest{&simpleTest{19}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if a.C.Value != b.C.Value { - t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) - } -} - -func TestSliceStruct(t *testing.T) { - a := sliceTest{} - b := sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(b.S) != 3 { - t.FailNow() - } - if len(a.S) != len(b.S) { - t.Fatalf("b not merged in a proper way %d != %d", len(a.S), len(b.S)) - } - - a = sliceTest{[]int{1}} - b = sliceTest{[]int{1, 2, 3}} - if err := Merge(&a, b); err != nil { - t.FailNow() - } - if len(a.S) != 1 { - t.FailNow() - } - if len(a.S) == len(b.S) { - t.Fatalf("b merged unexpectedly %d != %d", len(a.S), len(b.S)) - } -} - -func TestMapsWithOverwrite(t *testing.T) { - m := map[string]simpleTest{ - "a": {}, // overwritten by 16 - "b": {42}, // not overwritten by empty value - "c": {13}, // overwritten by 12 - "d": {61}, - } - n := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "e": {14}, - } - expect := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "d": {61}, - "e": {14}, - } - - if err := MergeWithOverwrite(&m, n); err != nil { - t.Fatalf(err.Error()) - } - - if !reflect.DeepEqual(m, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect) - } -} - -func TestMaps(t *testing.T) { - m := map[string]simpleTest{ - "a": {}, - "b": {42}, - "c": {13}, - "d": {61}, - } - n := map[string]simpleTest{ - "a": {16}, - "b": {}, - "c": {12}, - "e": {14}, - } - expect := map[string]simpleTest{ - "a": {0}, - "b": {42}, - "c": {13}, - "d": {61}, - "e": {14}, - } - - if err := Merge(&m, n); err != nil { - t.Fatalf(err.Error()) - } - - if !reflect.DeepEqual(m, expect) { - t.Fatalf("Test failed:\ngot :\n%#v\n\nwant :\n%#v\n\n", m, expect) - } - if m["a"].Value != 0 { - t.Fatalf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value) - } - if m["b"].Value != 42 { - t.Fatalf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value) - } - if m["c"].Value != 13 { - t.Fatalf(`n overwritten in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value) - } -} - -func TestYAMLMaps(t *testing.T) { - thing := loadYAML("testdata/thing.yml") - license := loadYAML("testdata/license.yml") - ft := thing["fields"].(map[interface{}]interface{}) - fl := license["fields"].(map[interface{}]interface{}) - expectedLength := len(ft) + len(fl) - if err := Merge(&license, thing); err != nil { - t.Fatal(err.Error()) - } - currentLength := len(license["fields"].(map[interface{}]interface{})) - if currentLength != expectedLength { - t.Fatalf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength) - } - fields := license["fields"].(map[interface{}]interface{}) - if _, ok := fields["id"]; !ok { - t.Fatalf(`thing not merged in license properly, license must have a new id field from thing`) - } -} - -func TestTwoPointerValues(t *testing.T) { - a := &simpleTest{} - b := &simpleTest{42} - if err := Merge(a, b); err != nil { - t.Fatalf(`Boom. You crossed the streams: %s`, err) - } -} - -func TestMap(t *testing.T) { - a := complexTest{} - a.ID = "athing" - c := moreComplextText{a, simpleTest{}, simpleTest{}} - b := map[string]interface{}{ - "ct": map[string]interface{}{ - "st": map[string]interface{}{ - "value": 42, - }, - "sz": 1, - "id": "bthing", - }, - "st": &simpleTest{144}, // Mapping a reference - "zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist) - "nt": simpleTest{3}, - } - if err := Map(&c, b); err != nil { - t.FailNow() - } - m := b["ct"].(map[string]interface{}) - n := m["st"].(map[string]interface{}) - o := b["st"].(*simpleTest) - p := b["nt"].(simpleTest) - if c.Ct.St.Value != 42 { - t.Fatalf("b not merged in properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"]) - } - if c.St.Value != 144 { - t.Fatalf("b not merged in properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value) - } - if c.Nt.Value != 3 { - t.Fatalf("b not merged in properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value) - } - if c.Ct.sz == 1 { - t.Fatalf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"]) - } - if c.Ct.ID == m["id"] { - t.Fatalf("a's field ID merged unexpectedly: c.Ct.ID(%s) == b.Ct.ID(%s)", c.Ct.ID, m["id"]) - } -} - -func TestSimpleMap(t *testing.T) { - a := simpleTest{} - b := map[string]interface{}{ - "value": 42, - } - if err := Map(&a, b); err != nil { - t.FailNow() - } - if a.Value != 42 { - t.Fatalf("b not merged in properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"]) - } -} - -type pointerMapTest struct { - A int - hidden int - B *simpleTest -} - -func TestBackAndForth(t *testing.T) { - pt := pointerMapTest{42, 1, &simpleTest{66}} - m := make(map[string]interface{}) - if err := Map(&m, pt); err != nil { - t.FailNow() - } - var ( - v interface{} - ok bool - ) - if v, ok = m["a"]; v.(int) != pt.A || !ok { - t.Fatalf("pt not merged in properly: m[`a`](%d) != pt.A(%d)", v, pt.A) - } - if v, ok = m["b"]; !ok { - t.Fatalf("pt not merged in properly: B is missing in m") - } - var st *simpleTest - if st = v.(*simpleTest); st.Value != 66 { - t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") - } - bpt := pointerMapTest{} - if err := Map(&bpt, m); err != nil { - t.Fatal(err) - } - if bpt.A != pt.A { - t.Fatalf("pt not merged in properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) - } - if bpt.hidden == pt.hidden { - t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) - } - if bpt.B.Value != pt.B.Value { - t.Fatalf("pt not merged in properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) - } -} - -type structWithTimePointer struct { - Birth *time.Time -} - -func TestTime(t *testing.T) { - now := time.Now() - dataStruct := structWithTimePointer{ - Birth: &now, - } - dataMap := map[string]interface{}{ - "Birth": &now, - } - b := structWithTimePointer{} - if err := Merge(&b, dataStruct); err != nil { - t.FailNow() - } - if b.Birth.IsZero() { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth) - } - if b.Birth != dataStruct.Birth { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataStruct['Birth'](%v)", b.Birth, dataStruct.Birth) - } - b = structWithTimePointer{} - if err := Map(&b, dataMap); err != nil { - t.FailNow() - } - if b.Birth.IsZero() { - t.Fatalf("time.Time not merged in properly: b.Birth(%v) != dataMap['Birth'](%v)", b.Birth, dataMap["Birth"]) - } -} - -type simpleNested struct { - A int -} - -type structWithNestedPtrValueMap struct { - NestedPtrValue map[string]*simpleNested -} - -func TestNestedPtrValueInMap(t *testing.T) { - src := &structWithNestedPtrValueMap{ - NestedPtrValue: map[string]*simpleNested{ - "x": { - A: 1, - }, - }, - } - dst := &structWithNestedPtrValueMap{ - NestedPtrValue: map[string]*simpleNested{ - "x": {}, - }, - } - if err := Map(dst, src); err != nil { - t.FailNow() - } - if dst.NestedPtrValue["x"].A == 0 { - t.Fatalf("Nested Ptr value not merged in properly: dst.NestedPtrValue[\"x\"].A(%v) != src.NestedPtrValue[\"x\"].A(%v)", dst.NestedPtrValue["x"].A, src.NestedPtrValue["x"].A) - } -} - -func loadYAML(path string) (m map[string]interface{}) { - m = make(map[string]interface{}) - raw, _ := ioutil.ReadFile(path) - _ = yaml.Unmarshal(raw, &m) - return -} - -type structWithMap struct { - m map[string]structWithUnexportedProperty -} - -type structWithUnexportedProperty struct { - s string -} - -func TestUnexportedProperty(t *testing.T) { - a := structWithMap{map[string]structWithUnexportedProperty{ - "key": structWithUnexportedProperty{"hello"}, - }} - b := structWithMap{map[string]structWithUnexportedProperty{ - "key": structWithUnexportedProperty{"hi"}, - }} - defer func() { - if r := recover(); r != nil { - t.Errorf("Should not have panicked") - } - }() - Merge(&a, b) -} - -type structWithBoolPointer struct { - C *bool -} - -func TestBooleanPointer(t *testing.T) { - bt, bf := true, false - src := structWithBoolPointer{ - &bt, - } - dst := structWithBoolPointer{ - &bf, - } - if err := Merge(&dst, src); err != nil { - t.FailNow() - } - if dst.C == src.C { - t.Fatalf("dst.C should be a different pointer than src.C") - } - if *dst.C != *src.C { - t.Fatalf("dst.C should be true") - } -} diff --git a/vendor/github.com/imdario/mergo/testdata/license.yml b/vendor/github.com/imdario/mergo/testdata/license.yml deleted file mode 100644 index 62fdb61ec3..0000000000 --- a/vendor/github.com/imdario/mergo/testdata/license.yml +++ /dev/null @@ -1,3 +0,0 @@ -import: ../../../../fossene/db/schema/thing.yml -fields: - site: string diff --git a/vendor/github.com/imdario/mergo/testdata/thing.yml b/vendor/github.com/imdario/mergo/testdata/thing.yml deleted file mode 100644 index c28eab0d05..0000000000 --- a/vendor/github.com/imdario/mergo/testdata/thing.yml +++ /dev/null @@ -1,5 +0,0 @@ -fields: - id: int - name: string - parent: ref "datu:thing" - status: enum(draft, public, private) diff --git a/vendor/github.com/jmespath/go-jmespath/LICENSE b/vendor/github.com/jmespath/go-jmespath/LICENSE deleted file mode 100644 index b03310a91f..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2015 James Saryerwinnie - -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. diff --git a/vendor/github.com/jmespath/go-jmespath/Makefile b/vendor/github.com/jmespath/go-jmespath/Makefile deleted file mode 100644 index a828d2848f..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/Makefile +++ /dev/null @@ -1,44 +0,0 @@ - -CMD = jpgo - -help: - @echo "Please use \`make ' where is one of" - @echo " test to run all the tests" - @echo " build to build the library and jp executable" - @echo " generate to run codegen" - - -generate: - go generate ./... - -build: - rm -f $(CMD) - go build ./... - rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./... - mv cmd/$(CMD)/$(CMD) . - -test: - go test -v ./... - -check: - go vet ./... - @echo "golint ./..." - @lint=`golint ./...`; \ - lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \ - echo "$$lint"; \ - if [ "$$lint" != "" ]; then exit 1; fi - -htmlc: - go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov - -buildfuzz: - go-fuzz-build github.com/jmespath/go-jmespath/fuzz - -fuzz: buildfuzz - go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/testdata - -bench: - go test -bench . -cpuprofile cpu.out - -pprof-cpu: - go tool pprof ./go-jmespath.test ./cpu.out diff --git a/vendor/github.com/jmespath/go-jmespath/README.md b/vendor/github.com/jmespath/go-jmespath/README.md deleted file mode 100644 index 187ef676dc..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# go-jmespath - A JMESPath implementation in Go - -[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath) - - - -See http://jmespath.org for more info. diff --git a/vendor/github.com/jmespath/go-jmespath/api.go b/vendor/github.com/jmespath/go-jmespath/api.go deleted file mode 100644 index 9cfa988bc5..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/api.go +++ /dev/null @@ -1,49 +0,0 @@ -package jmespath - -import "strconv" - -// JmesPath is the epresentation of a compiled JMES path query. A JmesPath is -// safe for concurrent use by multiple goroutines. -type JMESPath struct { - ast ASTNode - intr *treeInterpreter -} - -// Compile parses a JMESPath expression and returns, if successful, a JMESPath -// object that can be used to match against data. -func Compile(expression string) (*JMESPath, error) { - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - jmespath := &JMESPath{ast: ast, intr: newInterpreter()} - return jmespath, nil -} - -// MustCompile is like Compile but panics if the expression cannot be parsed. -// It simplifies safe initialization of global variables holding compiled -// JMESPaths. -func MustCompile(expression string) *JMESPath { - jmespath, err := Compile(expression) - if err != nil { - panic(`jmespath: Compile(` + strconv.Quote(expression) + `): ` + err.Error()) - } - return jmespath -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func (jp *JMESPath) Search(data interface{}) (interface{}, error) { - return jp.intr.Execute(jp.ast, data) -} - -// Search evaluates a JMESPath expression against input data and returns the result. -func Search(expression string, data interface{}) (interface{}, error) { - intr := newInterpreter() - parser := NewParser() - ast, err := parser.Parse(expression) - if err != nil { - return nil, err - } - return intr.Execute(ast, data) -} diff --git a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go b/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go deleted file mode 100644 index 1cd2d239c9..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/astnodetype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type astNodeType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTAndExpressionASTNotExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection" - -var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 229, 245, 252, 265, 281, 289, 307} - -func (i astNodeType) String() string { - if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) { - return fmt.Sprintf("astNodeType(%d)", i) - } - return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/functions.go b/vendor/github.com/jmespath/go-jmespath/functions.go deleted file mode 100644 index 9b7cd89b4b..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/functions.go +++ /dev/null @@ -1,842 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "strings" - "unicode/utf8" -) - -type jpFunction func(arguments []interface{}) (interface{}, error) - -type jpType string - -const ( - jpUnknown jpType = "unknown" - jpNumber jpType = "number" - jpString jpType = "string" - jpArray jpType = "array" - jpObject jpType = "object" - jpArrayNumber jpType = "array[number]" - jpArrayString jpType = "array[string]" - jpExpref jpType = "expref" - jpAny jpType = "any" -) - -type functionEntry struct { - name string - arguments []argSpec - handler jpFunction - hasExpRef bool -} - -type argSpec struct { - types []jpType - variadic bool -} - -type byExprString struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprString) Len() int { - return len(a.items) -} -func (a *byExprString) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprString) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(string) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(string) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type byExprFloat struct { - intr *treeInterpreter - node ASTNode - items []interface{} - hasError bool -} - -func (a *byExprFloat) Len() int { - return len(a.items) -} -func (a *byExprFloat) Swap(i, j int) { - a.items[i], a.items[j] = a.items[j], a.items[i] -} -func (a *byExprFloat) Less(i, j int) bool { - first, err := a.intr.Execute(a.node, a.items[i]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - ith, ok := first.(float64) - if !ok { - a.hasError = true - return true - } - second, err := a.intr.Execute(a.node, a.items[j]) - if err != nil { - a.hasError = true - // Return a dummy value. - return true - } - jth, ok := second.(float64) - if !ok { - a.hasError = true - return true - } - return ith < jth -} - -type functionCaller struct { - functionTable map[string]functionEntry -} - -func newFunctionCaller() *functionCaller { - caller := &functionCaller{} - caller.functionTable = map[string]functionEntry{ - "length": { - name: "length", - arguments: []argSpec{ - {types: []jpType{jpString, jpArray, jpObject}}, - }, - handler: jpfLength, - }, - "starts_with": { - name: "starts_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfStartsWith, - }, - "abs": { - name: "abs", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfAbs, - }, - "avg": { - name: "avg", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfAvg, - }, - "ceil": { - name: "ceil", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfCeil, - }, - "contains": { - name: "contains", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - {types: []jpType{jpAny}}, - }, - handler: jpfContains, - }, - "ends_with": { - name: "ends_with", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpString}}, - }, - handler: jpfEndsWith, - }, - "floor": { - name: "floor", - arguments: []argSpec{ - {types: []jpType{jpNumber}}, - }, - handler: jpfFloor, - }, - "map": { - name: "amp", - arguments: []argSpec{ - {types: []jpType{jpExpref}}, - {types: []jpType{jpArray}}, - }, - handler: jpfMap, - hasExpRef: true, - }, - "max": { - name: "max", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMax, - }, - "merge": { - name: "merge", - arguments: []argSpec{ - {types: []jpType{jpObject}, variadic: true}, - }, - handler: jpfMerge, - }, - "max_by": { - name: "max_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMaxBy, - hasExpRef: true, - }, - "sum": { - name: "sum", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber}}, - }, - handler: jpfSum, - }, - "min": { - name: "min", - arguments: []argSpec{ - {types: []jpType{jpArrayNumber, jpArrayString}}, - }, - handler: jpfMin, - }, - "min_by": { - name: "min_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfMinBy, - hasExpRef: true, - }, - "type": { - name: "type", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfType, - }, - "keys": { - name: "keys", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfKeys, - }, - "values": { - name: "values", - arguments: []argSpec{ - {types: []jpType{jpObject}}, - }, - handler: jpfValues, - }, - "sort": { - name: "sort", - arguments: []argSpec{ - {types: []jpType{jpArrayString, jpArrayNumber}}, - }, - handler: jpfSort, - }, - "sort_by": { - name: "sort_by", - arguments: []argSpec{ - {types: []jpType{jpArray}}, - {types: []jpType{jpExpref}}, - }, - handler: jpfSortBy, - hasExpRef: true, - }, - "join": { - name: "join", - arguments: []argSpec{ - {types: []jpType{jpString}}, - {types: []jpType{jpArrayString}}, - }, - handler: jpfJoin, - }, - "reverse": { - name: "reverse", - arguments: []argSpec{ - {types: []jpType{jpArray, jpString}}, - }, - handler: jpfReverse, - }, - "to_array": { - name: "to_array", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToArray, - }, - "to_string": { - name: "to_string", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToString, - }, - "to_number": { - name: "to_number", - arguments: []argSpec{ - {types: []jpType{jpAny}}, - }, - handler: jpfToNumber, - }, - "not_null": { - name: "not_null", - arguments: []argSpec{ - {types: []jpType{jpAny}, variadic: true}, - }, - handler: jpfNotNull, - }, - } - return caller -} - -func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) { - if len(e.arguments) == 0 { - return arguments, nil - } - if !e.arguments[len(e.arguments)-1].variadic { - if len(e.arguments) != len(arguments) { - return nil, errors.New("incorrect number of args") - } - for i, spec := range e.arguments { - userArg := arguments[i] - err := spec.typeCheck(userArg) - if err != nil { - return nil, err - } - } - return arguments, nil - } - if len(arguments) < len(e.arguments) { - return nil, errors.New("Invalid arity.") - } - return arguments, nil -} - -func (a *argSpec) typeCheck(arg interface{}) error { - for _, t := range a.types { - switch t { - case jpNumber: - if _, ok := arg.(float64); ok { - return nil - } - case jpString: - if _, ok := arg.(string); ok { - return nil - } - case jpArray: - if isSliceType(arg) { - return nil - } - case jpObject: - if _, ok := arg.(map[string]interface{}); ok { - return nil - } - case jpArrayNumber: - if _, ok := toArrayNum(arg); ok { - return nil - } - case jpArrayString: - if _, ok := toArrayStr(arg); ok { - return nil - } - case jpAny: - return nil - case jpExpref: - if _, ok := arg.(expRef); ok { - return nil - } - } - } - return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types) -} - -func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) { - entry, ok := f.functionTable[name] - if !ok { - return nil, errors.New("unknown function: " + name) - } - resolvedArgs, err := entry.resolveArgs(arguments) - if err != nil { - return nil, err - } - if entry.hasExpRef { - var extra []interface{} - extra = append(extra, intr) - resolvedArgs = append(extra, resolvedArgs...) - } - return entry.handler(resolvedArgs) -} - -func jpfAbs(arguments []interface{}) (interface{}, error) { - num := arguments[0].(float64) - return math.Abs(num), nil -} - -func jpfLength(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if c, ok := arg.(string); ok { - return float64(utf8.RuneCountInString(c)), nil - } else if isSliceType(arg) { - v := reflect.ValueOf(arg) - return float64(v.Len()), nil - } else if c, ok := arg.(map[string]interface{}); ok { - return float64(len(c)), nil - } - return nil, errors.New("could not compute length()") -} - -func jpfStartsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - prefix := arguments[1].(string) - return strings.HasPrefix(search, prefix), nil -} - -func jpfAvg(arguments []interface{}) (interface{}, error) { - // We've already type checked the value so we can safely use - // type assertions. - args := arguments[0].([]interface{}) - length := float64(len(args)) - numerator := 0.0 - for _, n := range args { - numerator += n.(float64) - } - return numerator / length, nil -} -func jpfCeil(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Ceil(val), nil -} -func jpfContains(arguments []interface{}) (interface{}, error) { - search := arguments[0] - el := arguments[1] - if searchStr, ok := search.(string); ok { - if elStr, ok := el.(string); ok { - return strings.Index(searchStr, elStr) != -1, nil - } - return false, nil - } - // Otherwise this is a generic contains for []interface{} - general := search.([]interface{}) - for _, item := range general { - if item == el { - return true, nil - } - } - return false, nil -} -func jpfEndsWith(arguments []interface{}) (interface{}, error) { - search := arguments[0].(string) - suffix := arguments[1].(string) - return strings.HasSuffix(search, suffix), nil -} -func jpfFloor(arguments []interface{}) (interface{}, error) { - val := arguments[0].(float64) - return math.Floor(val), nil -} -func jpfMap(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - exp := arguments[1].(expRef) - node := exp.ref - arr := arguments[2].([]interface{}) - mapped := make([]interface{}, 0, len(arr)) - for _, value := range arr { - current, err := intr.Execute(node, value) - if err != nil { - return nil, err - } - mapped = append(mapped, current) - } - return mapped, nil -} -func jpfMax(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil - } - // Otherwise we're dealing with a max() of strings. - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item > best { - best = item - } - } - return best, nil -} -func jpfMerge(arguments []interface{}) (interface{}, error) { - final := make(map[string]interface{}) - for _, m := range arguments { - mapped := m.(map[string]interface{}) - for key, value := range mapped { - final[key] = value - } - } - return final, nil -} -func jpfMaxBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - switch t := start.(type) { - case float64: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - case string: - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current > bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - default: - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfSum(arguments []interface{}) (interface{}, error) { - items, _ := toArrayNum(arguments[0]) - sum := 0.0 - for _, item := range items { - sum += item - } - return sum, nil -} - -func jpfMin(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil - } - items, _ := toArrayStr(arguments[0]) - if len(items) == 0 { - return nil, nil - } - if len(items) == 1 { - return items[0], nil - } - best := items[0] - for _, item := range items[1:] { - if item < best { - best = item - } - } - return best, nil -} - -func jpfMinBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return nil, nil - } else if len(arr) == 1 { - return arr[0], nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if t, ok := start.(float64); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(float64) - if !ok { - return nil, errors.New("invalid type, must be number") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else if t, ok := start.(string); ok { - bestVal := t - bestItem := arr[0] - for _, item := range arr[1:] { - result, err := intr.Execute(node, item) - if err != nil { - return nil, err - } - current, ok := result.(string) - if !ok { - return nil, errors.New("invalid type, must be string") - } - if current < bestVal { - bestVal = current - bestItem = item - } - } - return bestItem, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfType(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if _, ok := arg.(float64); ok { - return "number", nil - } - if _, ok := arg.(string); ok { - return "string", nil - } - if _, ok := arg.([]interface{}); ok { - return "array", nil - } - if _, ok := arg.(map[string]interface{}); ok { - return "object", nil - } - if arg == nil { - return "null", nil - } - if arg == true || arg == false { - return "boolean", nil - } - return nil, errors.New("unknown type") -} -func jpfKeys(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for key := range arg { - collected = append(collected, key) - } - return collected, nil -} -func jpfValues(arguments []interface{}) (interface{}, error) { - arg := arguments[0].(map[string]interface{}) - collected := make([]interface{}, 0, len(arg)) - for _, value := range arg { - collected = append(collected, value) - } - return collected, nil -} -func jpfSort(arguments []interface{}) (interface{}, error) { - if items, ok := toArrayNum(arguments[0]); ok { - d := sort.Float64Slice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil - } - // Otherwise we're dealing with sort()'ing strings. - items, _ := toArrayStr(arguments[0]) - d := sort.StringSlice(items) - sort.Stable(d) - final := make([]interface{}, len(d)) - for i, val := range d { - final[i] = val - } - return final, nil -} -func jpfSortBy(arguments []interface{}) (interface{}, error) { - intr := arguments[0].(*treeInterpreter) - arr := arguments[1].([]interface{}) - exp := arguments[2].(expRef) - node := exp.ref - if len(arr) == 0 { - return arr, nil - } else if len(arr) == 1 { - return arr, nil - } - start, err := intr.Execute(node, arr[0]) - if err != nil { - return nil, err - } - if _, ok := start.(float64); ok { - sortable := &byExprFloat{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else if _, ok := start.(string); ok { - sortable := &byExprString{intr, node, arr, false} - sort.Stable(sortable) - if sortable.hasError { - return nil, errors.New("error in sort_by comparison") - } - return arr, nil - } else { - return nil, errors.New("invalid type, must be number of string") - } -} -func jpfJoin(arguments []interface{}) (interface{}, error) { - sep := arguments[0].(string) - // We can't just do arguments[1].([]string), we have to - // manually convert each item to a string. - arrayStr := []string{} - for _, item := range arguments[1].([]interface{}) { - arrayStr = append(arrayStr, item.(string)) - } - return strings.Join(arrayStr, sep), nil -} -func jpfReverse(arguments []interface{}) (interface{}, error) { - if s, ok := arguments[0].(string); ok { - r := []rune(s) - for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { - r[i], r[j] = r[j], r[i] - } - return string(r), nil - } - items := arguments[0].([]interface{}) - length := len(items) - reversed := make([]interface{}, length) - for i, item := range items { - reversed[length-(i+1)] = item - } - return reversed, nil -} -func jpfToArray(arguments []interface{}) (interface{}, error) { - if _, ok := arguments[0].([]interface{}); ok { - return arguments[0], nil - } - return arguments[:1:1], nil -} -func jpfToString(arguments []interface{}) (interface{}, error) { - if v, ok := arguments[0].(string); ok { - return v, nil - } - result, err := json.Marshal(arguments[0]) - if err != nil { - return nil, err - } - return string(result), nil -} -func jpfToNumber(arguments []interface{}) (interface{}, error) { - arg := arguments[0] - if v, ok := arg.(float64); ok { - return v, nil - } - if v, ok := arg.(string); ok { - conv, err := strconv.ParseFloat(v, 64) - if err != nil { - return nil, nil - } - return conv, nil - } - if _, ok := arg.([]interface{}); ok { - return nil, nil - } - if _, ok := arg.(map[string]interface{}); ok { - return nil, nil - } - if arg == nil { - return nil, nil - } - if arg == true || arg == false { - return nil, nil - } - return nil, errors.New("unknown type") -} -func jpfNotNull(arguments []interface{}) (interface{}, error) { - for _, arg := range arguments { - if arg != nil { - return arg, nil - } - } - return nil, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/interpreter.go b/vendor/github.com/jmespath/go-jmespath/interpreter.go deleted file mode 100644 index 13c74604c2..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/interpreter.go +++ /dev/null @@ -1,418 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" - "unicode" - "unicode/utf8" -) - -/* This is a tree based interpreter. It walks the AST and directly - interprets the AST to search through a JSON document. -*/ - -type treeInterpreter struct { - fCall *functionCaller -} - -func newInterpreter() *treeInterpreter { - interpreter := treeInterpreter{} - interpreter.fCall = newFunctionCaller() - return &interpreter -} - -type expRef struct { - ref ASTNode -} - -// Execute takes an ASTNode and input data and interprets the AST directly. -// It will produce the result of applying the JMESPath expression associated -// with the ASTNode to the input data "value". -func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) { - switch node.nodeType { - case ASTComparator: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - right, err := intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - switch node.value { - case tEQ: - return objsEqual(left, right), nil - case tNE: - return !objsEqual(left, right), nil - } - leftNum, ok := left.(float64) - if !ok { - return nil, nil - } - rightNum, ok := right.(float64) - if !ok { - return nil, nil - } - switch node.value { - case tGT: - return leftNum > rightNum, nil - case tGTE: - return leftNum >= rightNum, nil - case tLT: - return leftNum < rightNum, nil - case tLTE: - return leftNum <= rightNum, nil - } - case ASTExpRef: - return expRef{ref: node.children[0]}, nil - case ASTFunctionExpression: - resolvedArgs := []interface{}{} - for _, arg := range node.children { - current, err := intr.Execute(arg, value) - if err != nil { - return nil, err - } - resolvedArgs = append(resolvedArgs, current) - } - return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr) - case ASTField: - if m, ok := value.(map[string]interface{}); ok { - key := node.value.(string) - return m[key], nil - } - return intr.fieldFromStruct(node.value.(string), value) - case ASTFilterProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.filterProjectionWithReflection(node, left) - } - return nil, nil - } - compareNode := node.children[2] - collected := []interface{}{} - for _, element := range sliceType { - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil - case ASTFlatten: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - sliceType, ok := left.([]interface{}) - if !ok { - // If we can't type convert to []interface{}, there's - // a chance this could still work via reflection if we're - // dealing with user provided types. - if isSliceType(left) { - return intr.flattenWithReflection(left) - } - return nil, nil - } - flattened := []interface{}{} - for _, element := range sliceType { - if elementSlice, ok := element.([]interface{}); ok { - flattened = append(flattened, elementSlice...) - } else if isSliceType(element) { - reflectFlat := []interface{}{} - v := reflect.ValueOf(element) - for i := 0; i < v.Len(); i++ { - reflectFlat = append(reflectFlat, v.Index(i).Interface()) - } - flattened = append(flattened, reflectFlat...) - } else { - flattened = append(flattened, element) - } - } - return flattened, nil - case ASTIdentity, ASTCurrentNode: - return value, nil - case ASTIndex: - if sliceType, ok := value.([]interface{}); ok { - index := node.value.(int) - if index < 0 { - index += len(sliceType) - } - if index < len(sliceType) && index >= 0 { - return sliceType[index], nil - } - return nil, nil - } - // Otherwise try via reflection. - rv := reflect.ValueOf(value) - if rv.Kind() == reflect.Slice { - index := node.value.(int) - if index < 0 { - index += rv.Len() - } - if index < rv.Len() && index >= 0 { - v := rv.Index(index) - return v.Interface(), nil - } - } - return nil, nil - case ASTKeyValPair: - return intr.Execute(node.children[0], value) - case ASTLiteral: - return node.value, nil - case ASTMultiSelectHash: - if value == nil { - return nil, nil - } - collected := make(map[string]interface{}) - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - key := child.value.(string) - collected[key] = current - } - return collected, nil - case ASTMultiSelectList: - if value == nil { - return nil, nil - } - collected := []interface{}{} - for _, child := range node.children { - current, err := intr.Execute(child, value) - if err != nil { - return nil, err - } - collected = append(collected, current) - } - return collected, nil - case ASTOrExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - matched, err = intr.Execute(node.children[1], value) - if err != nil { - return nil, err - } - } - return matched, nil - case ASTAndExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return matched, nil - } - return intr.Execute(node.children[1], value) - case ASTNotExpression: - matched, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - if isFalse(matched) { - return true, nil - } - return false, nil - case ASTPipe: - result := value - var err error - for _, child := range node.children { - result, err = intr.Execute(child, result) - if err != nil { - return nil, err - } - } - return result, nil - case ASTProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - sliceType, ok := left.([]interface{}) - if !ok { - if isSliceType(left) { - return intr.projectWithReflection(node, left) - } - return nil, nil - } - collected := []interface{}{} - var current interface{} - for _, element := range sliceType { - current, err = intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - case ASTSubexpression, ASTIndexExpression: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, err - } - return intr.Execute(node.children[1], left) - case ASTSlice: - sliceType, ok := value.([]interface{}) - if !ok { - if isSliceType(value) { - return intr.sliceWithReflection(node, value) - } - return nil, nil - } - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - return slice(sliceType, sliceParams) - case ASTValueProjection: - left, err := intr.Execute(node.children[0], value) - if err != nil { - return nil, nil - } - mapType, ok := left.(map[string]interface{}) - if !ok { - return nil, nil - } - values := make([]interface{}, len(mapType)) - for _, value := range mapType { - values = append(values, value) - } - collected := []interface{}{} - for _, element := range values { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - return collected, nil - } - return nil, errors.New("Unknown AST node: " + node.nodeType.String()) -} - -func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) { - rv := reflect.ValueOf(value) - first, n := utf8.DecodeRuneInString(key) - fieldName := string(unicode.ToUpper(first)) + key[n:] - if rv.Kind() == reflect.Struct { - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } else if rv.Kind() == reflect.Ptr { - // Handle multiple levels of indirection? - if rv.IsNil() { - return nil, nil - } - rv = rv.Elem() - v := rv.FieldByName(fieldName) - if !v.IsValid() { - return nil, nil - } - return v.Interface(), nil - } - return nil, nil -} - -func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - flattened := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - if reflect.TypeOf(element).Kind() == reflect.Slice { - // Then insert the contents of the element - // slice into the flattened slice, - // i.e flattened = append(flattened, mySlice...) - elementV := reflect.ValueOf(element) - for j := 0; j < elementV.Len(); j++ { - flattened = append( - flattened, elementV.Index(j).Interface()) - } - } else { - flattened = append(flattened, element) - } - } - return flattened, nil -} - -func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) { - v := reflect.ValueOf(value) - parts := node.value.([]*int) - sliceParams := make([]sliceParam, 3) - for i, part := range parts { - if part != nil { - sliceParams[i].Specified = true - sliceParams[i].N = *part - } - } - final := []interface{}{} - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - final = append(final, element) - } - return slice(final, sliceParams) -} - -func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) { - compareNode := node.children[2] - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(compareNode, element) - if err != nil { - return nil, err - } - if !isFalse(result) { - current, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if current != nil { - collected = append(collected, current) - } - } - } - return collected, nil -} - -func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) { - collected := []interface{}{} - v := reflect.ValueOf(value) - for i := 0; i < v.Len(); i++ { - element := v.Index(i).Interface() - result, err := intr.Execute(node.children[1], element) - if err != nil { - return nil, err - } - if result != nil { - collected = append(collected, result) - } - } - return collected, nil -} diff --git a/vendor/github.com/jmespath/go-jmespath/lexer.go b/vendor/github.com/jmespath/go-jmespath/lexer.go deleted file mode 100644 index 817900c8f5..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/lexer.go +++ /dev/null @@ -1,420 +0,0 @@ -package jmespath - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - "unicode/utf8" -) - -type token struct { - tokenType tokType - value string - position int - length int -} - -type tokType int - -const eof = -1 - -// Lexer contains information about the expression being tokenized. -type Lexer struct { - expression string // The expression provided by the user. - currentPos int // The current position in the string. - lastWidth int // The width of the current rune. This - buf bytes.Buffer // Internal buffer used for building up values. -} - -// SyntaxError is the main error used whenever a lexing or parsing error occurs. -type SyntaxError struct { - msg string // Error message displayed to user - Expression string // Expression that generated a SyntaxError - Offset int // The location in the string where the error occurred -} - -func (e SyntaxError) Error() string { - // In the future, it would be good to underline the specific - // location where the error occurred. - return "SyntaxError: " + e.msg -} - -// HighlightLocation will show where the syntax error occurred. -// It will place a "^" character on a line below the expression -// at the point where the syntax error occurred. -func (e SyntaxError) HighlightLocation() string { - return e.Expression + "\n" + strings.Repeat(" ", e.Offset) + "^" -} - -//go:generate stringer -type=tokType -const ( - tUnknown tokType = iota - tStar - tDot - tFilter - tFlatten - tLparen - tRparen - tLbracket - tRbracket - tLbrace - tRbrace - tOr - tPipe - tNumber - tUnquotedIdentifier - tQuotedIdentifier - tComma - tColon - tLT - tLTE - tGT - tGTE - tEQ - tNE - tJSONLiteral - tStringLiteral - tCurrent - tExpref - tAnd - tNot - tEOF -) - -var basicTokens = map[rune]tokType{ - '.': tDot, - '*': tStar, - ',': tComma, - ':': tColon, - '{': tLbrace, - '}': tRbrace, - ']': tRbracket, // tLbracket not included because it could be "[]" - '(': tLparen, - ')': tRparen, - '@': tCurrent, -} - -// Bit mask for [a-zA-Z_] shifted down 64 bits to fit in a single uint64. -// When using this bitmask just be sure to shift the rune down 64 bits -// before checking against identifierStartBits. -const identifierStartBits uint64 = 576460745995190270 - -// Bit mask for [a-zA-Z0-9], 128 bits -> 2 uint64s. -var identifierTrailingBits = [2]uint64{287948901175001088, 576460745995190270} - -var whiteSpace = map[rune]bool{ - ' ': true, '\t': true, '\n': true, '\r': true, -} - -func (t token) String() string { - return fmt.Sprintf("Token{%+v, %s, %d, %d}", - t.tokenType, t.value, t.position, t.length) -} - -// NewLexer creates a new JMESPath lexer. -func NewLexer() *Lexer { - lexer := Lexer{} - return &lexer -} - -func (lexer *Lexer) next() rune { - if lexer.currentPos >= len(lexer.expression) { - lexer.lastWidth = 0 - return eof - } - r, w := utf8.DecodeRuneInString(lexer.expression[lexer.currentPos:]) - lexer.lastWidth = w - lexer.currentPos += w - return r -} - -func (lexer *Lexer) back() { - lexer.currentPos -= lexer.lastWidth -} - -func (lexer *Lexer) peek() rune { - t := lexer.next() - lexer.back() - return t -} - -// tokenize takes an expression and returns corresponding tokens. -func (lexer *Lexer) tokenize(expression string) ([]token, error) { - var tokens []token - lexer.expression = expression - lexer.currentPos = 0 - lexer.lastWidth = 0 -loop: - for { - r := lexer.next() - if identifierStartBits&(1<<(uint64(r)-64)) > 0 { - t := lexer.consumeUnquotedIdentifier() - tokens = append(tokens, t) - } else if val, ok := basicTokens[r]; ok { - // Basic single char token. - t := token{ - tokenType: val, - value: string(r), - position: lexer.currentPos - lexer.lastWidth, - length: 1, - } - tokens = append(tokens, t) - } else if r == '-' || (r >= '0' && r <= '9') { - t := lexer.consumeNumber() - tokens = append(tokens, t) - } else if r == '[' { - t := lexer.consumeLBracket() - tokens = append(tokens, t) - } else if r == '"' { - t, err := lexer.consumeQuotedIdentifier() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '\'' { - t, err := lexer.consumeRawStringLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '`' { - t, err := lexer.consumeLiteral() - if err != nil { - return tokens, err - } - tokens = append(tokens, t) - } else if r == '|' { - t := lexer.matchOrElse(r, '|', tOr, tPipe) - tokens = append(tokens, t) - } else if r == '<' { - t := lexer.matchOrElse(r, '=', tLTE, tLT) - tokens = append(tokens, t) - } else if r == '>' { - t := lexer.matchOrElse(r, '=', tGTE, tGT) - tokens = append(tokens, t) - } else if r == '!' { - t := lexer.matchOrElse(r, '=', tNE, tNot) - tokens = append(tokens, t) - } else if r == '=' { - t := lexer.matchOrElse(r, '=', tEQ, tUnknown) - tokens = append(tokens, t) - } else if r == '&' { - t := lexer.matchOrElse(r, '&', tAnd, tExpref) - tokens = append(tokens, t) - } else if r == eof { - break loop - } else if _, ok := whiteSpace[r]; ok { - // Ignore whitespace - } else { - return tokens, lexer.syntaxError(fmt.Sprintf("Unknown char: %s", strconv.QuoteRuneToASCII(r))) - } - } - tokens = append(tokens, token{tEOF, "", len(lexer.expression), 0}) - return tokens, nil -} - -// Consume characters until the ending rune "r" is reached. -// If the end of the expression is reached before seeing the -// terminating rune "r", then an error is returned. -// If no error occurs then the matching substring is returned. -// The returned string will not include the ending rune. -func (lexer *Lexer) consumeUntil(end rune) (string, error) { - start := lexer.currentPos - current := lexer.next() - for current != end && current != eof { - if current == '\\' && lexer.peek() != eof { - lexer.next() - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return "", SyntaxError{ - msg: "Unclosed delimiter: " + string(end), - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - return lexer.expression[start : lexer.currentPos-lexer.lastWidth], nil -} - -func (lexer *Lexer) consumeLiteral() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('`') - if err != nil { - return token{}, err - } - value = strings.Replace(value, "\\`", "`", -1) - return token{ - tokenType: tJSONLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) consumeRawStringLiteral() (token, error) { - start := lexer.currentPos - currentIndex := start - current := lexer.next() - for current != '\'' && lexer.peek() != eof { - if current == '\\' && lexer.peek() == '\'' { - chunk := lexer.expression[currentIndex : lexer.currentPos-1] - lexer.buf.WriteString(chunk) - lexer.buf.WriteString("'") - lexer.next() - currentIndex = lexer.currentPos - } - current = lexer.next() - } - if lexer.lastWidth == 0 { - // Then we hit an EOF so we never reached the closing - // delimiter. - return token{}, SyntaxError{ - msg: "Unclosed delimiter: '", - Expression: lexer.expression, - Offset: len(lexer.expression), - } - } - if currentIndex < lexer.currentPos { - lexer.buf.WriteString(lexer.expression[currentIndex : lexer.currentPos-1]) - } - value := lexer.buf.String() - // Reset the buffer so it can reused again. - lexer.buf.Reset() - return token{ - tokenType: tStringLiteral, - value: value, - position: start, - length: len(value), - }, nil -} - -func (lexer *Lexer) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: lexer.expression, - Offset: lexer.currentPos - 1, - } -} - -// Checks for a two char token, otherwise matches a single character -// token. This is used whenever a two char token overlaps a single -// char token, e.g. "||" -> tPipe, "|" -> tOr. -func (lexer *Lexer) matchOrElse(first rune, second rune, matchedType tokType, singleCharType tokType) token { - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == second { - t = token{ - tokenType: matchedType, - value: string(first) + string(second), - position: start, - length: 2, - } - } else { - lexer.back() - t = token{ - tokenType: singleCharType, - value: string(first), - position: start, - length: 1, - } - } - return t -} - -func (lexer *Lexer) consumeLBracket() token { - // There's three options here: - // 1. A filter expression "[?" - // 2. A flatten operator "[]" - // 3. A bare rbracket "[" - start := lexer.currentPos - lexer.lastWidth - nextRune := lexer.next() - var t token - if nextRune == '?' { - t = token{ - tokenType: tFilter, - value: "[?", - position: start, - length: 2, - } - } else if nextRune == ']' { - t = token{ - tokenType: tFlatten, - value: "[]", - position: start, - length: 2, - } - } else { - t = token{ - tokenType: tLbracket, - value: "[", - position: start, - length: 1, - } - lexer.back() - } - return t -} - -func (lexer *Lexer) consumeQuotedIdentifier() (token, error) { - start := lexer.currentPos - value, err := lexer.consumeUntil('"') - if err != nil { - return token{}, err - } - var decoded string - asJSON := []byte("\"" + value + "\"") - if err := json.Unmarshal([]byte(asJSON), &decoded); err != nil { - return token{}, err - } - return token{ - tokenType: tQuotedIdentifier, - value: decoded, - position: start - 1, - length: len(decoded), - }, nil -} - -func (lexer *Lexer) consumeUnquotedIdentifier() token { - // Consume runes until we reach the end of an unquoted - // identifier. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < 0 || r > 128 || identifierTrailingBits[uint64(r)/64]&(1<<(uint64(r)%64)) == 0 { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tUnquotedIdentifier, - value: value, - position: start, - length: lexer.currentPos - start, - } -} - -func (lexer *Lexer) consumeNumber() token { - // Consume runes until we reach something that's not a number. - start := lexer.currentPos - lexer.lastWidth - for { - r := lexer.next() - if r < '0' || r > '9' { - lexer.back() - break - } - } - value := lexer.expression[start:lexer.currentPos] - return token{ - tokenType: tNumber, - value: value, - position: start, - length: lexer.currentPos - start, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/parser.go b/vendor/github.com/jmespath/go-jmespath/parser.go deleted file mode 100644 index 1240a17552..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/parser.go +++ /dev/null @@ -1,603 +0,0 @@ -package jmespath - -import ( - "encoding/json" - "fmt" - "strconv" - "strings" -) - -type astNodeType int - -//go:generate stringer -type astNodeType -const ( - ASTEmpty astNodeType = iota - ASTComparator - ASTCurrentNode - ASTExpRef - ASTFunctionExpression - ASTField - ASTFilterProjection - ASTFlatten - ASTIdentity - ASTIndex - ASTIndexExpression - ASTKeyValPair - ASTLiteral - ASTMultiSelectHash - ASTMultiSelectList - ASTOrExpression - ASTAndExpression - ASTNotExpression - ASTPipe - ASTProjection - ASTSubexpression - ASTSlice - ASTValueProjection -) - -// ASTNode represents the abstract syntax tree of a JMESPath expression. -type ASTNode struct { - nodeType astNodeType - value interface{} - children []ASTNode -} - -func (node ASTNode) String() string { - return node.PrettyPrint(0) -} - -// PrettyPrint will pretty print the parsed AST. -// The AST is an implementation detail and this pretty print -// function is provided as a convenience method to help with -// debugging. You should not rely on its output as the internal -// structure of the AST may change at any time. -func (node ASTNode) PrettyPrint(indent int) string { - spaces := strings.Repeat(" ", indent) - output := fmt.Sprintf("%s%s {\n", spaces, node.nodeType) - nextIndent := indent + 2 - if node.value != nil { - if converted, ok := node.value.(fmt.Stringer); ok { - // Account for things like comparator nodes - // that are enums with a String() method. - output += fmt.Sprintf("%svalue: %s\n", strings.Repeat(" ", nextIndent), converted.String()) - } else { - output += fmt.Sprintf("%svalue: %#v\n", strings.Repeat(" ", nextIndent), node.value) - } - } - lastIndex := len(node.children) - if lastIndex > 0 { - output += fmt.Sprintf("%schildren: {\n", strings.Repeat(" ", nextIndent)) - childIndent := nextIndent + 2 - for _, elem := range node.children { - output += elem.PrettyPrint(childIndent) - } - } - output += fmt.Sprintf("%s}\n", spaces) - return output -} - -var bindingPowers = map[tokType]int{ - tEOF: 0, - tUnquotedIdentifier: 0, - tQuotedIdentifier: 0, - tRbracket: 0, - tRparen: 0, - tComma: 0, - tRbrace: 0, - tNumber: 0, - tCurrent: 0, - tExpref: 0, - tColon: 0, - tPipe: 1, - tOr: 2, - tAnd: 3, - tEQ: 5, - tLT: 5, - tLTE: 5, - tGT: 5, - tGTE: 5, - tNE: 5, - tFlatten: 9, - tStar: 20, - tFilter: 21, - tDot: 40, - tNot: 45, - tLbrace: 50, - tLbracket: 55, - tLparen: 60, -} - -// Parser holds state about the current expression being parsed. -type Parser struct { - expression string - tokens []token - index int -} - -// NewParser creates a new JMESPath parser. -func NewParser() *Parser { - p := Parser{} - return &p -} - -// Parse will compile a JMESPath expression. -func (p *Parser) Parse(expression string) (ASTNode, error) { - lexer := NewLexer() - p.expression = expression - p.index = 0 - tokens, err := lexer.tokenize(expression) - if err != nil { - return ASTNode{}, err - } - p.tokens = tokens - parsed, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() != tEOF { - return ASTNode{}, p.syntaxError(fmt.Sprintf( - "Unexpected token at the end of the expresssion: %s", p.current())) - } - return parsed, nil -} - -func (p *Parser) parseExpression(bindingPower int) (ASTNode, error) { - var err error - leftToken := p.lookaheadToken(0) - p.advance() - leftNode, err := p.nud(leftToken) - if err != nil { - return ASTNode{}, err - } - currentToken := p.current() - for bindingPower < bindingPowers[currentToken] { - p.advance() - leftNode, err = p.led(currentToken, leftNode) - if err != nil { - return ASTNode{}, err - } - currentToken = p.current() - } - return leftNode, nil -} - -func (p *Parser) parseIndexExpression() (ASTNode, error) { - if p.lookahead(0) == tColon || p.lookahead(1) == tColon { - return p.parseSliceExpression() - } - indexStr := p.lookaheadToken(0).value - parsedInt, err := strconv.Atoi(indexStr) - if err != nil { - return ASTNode{}, err - } - indexNode := ASTNode{nodeType: ASTIndex, value: parsedInt} - p.advance() - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return indexNode, nil -} - -func (p *Parser) parseSliceExpression() (ASTNode, error) { - parts := []*int{nil, nil, nil} - index := 0 - current := p.current() - for current != tRbracket && index < 3 { - if current == tColon { - index++ - p.advance() - } else if current == tNumber { - parsedInt, err := strconv.Atoi(p.lookaheadToken(0).value) - if err != nil { - return ASTNode{}, err - } - parts[index] = &parsedInt - p.advance() - } else { - return ASTNode{}, p.syntaxError( - "Expected tColon or tNumber" + ", received: " + p.current().String()) - } - current = p.current() - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTSlice, - value: parts, - }, nil -} - -func (p *Parser) match(tokenType tokType) error { - if p.current() == tokenType { - p.advance() - return nil - } - return p.syntaxError("Expected " + tokenType.String() + ", received: " + p.current().String()) -} - -func (p *Parser) led(tokenType tokType, node ASTNode) (ASTNode, error) { - switch tokenType { - case tDot: - if p.current() != tStar { - right, err := p.parseDotRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTSubexpression, - children: []ASTNode{node, right}, - }, err - } - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tDot]) - return ASTNode{ - nodeType: ASTValueProjection, - children: []ASTNode{node, right}, - }, err - case tPipe: - right, err := p.parseExpression(bindingPowers[tPipe]) - return ASTNode{nodeType: ASTPipe, children: []ASTNode{node, right}}, err - case tOr: - right, err := p.parseExpression(bindingPowers[tOr]) - return ASTNode{nodeType: ASTOrExpression, children: []ASTNode{node, right}}, err - case tAnd: - right, err := p.parseExpression(bindingPowers[tAnd]) - return ASTNode{nodeType: ASTAndExpression, children: []ASTNode{node, right}}, err - case tLparen: - name := node.value - var args []ASTNode - for p.current() != tRparen { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if p.current() == tComma { - if err := p.match(tComma); err != nil { - return ASTNode{}, err - } - } - args = append(args, expression) - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTFunctionExpression, - value: name, - children: args, - }, nil - case tFilter: - return p.parseFilter(node) - case tFlatten: - left := ASTNode{nodeType: ASTFlatten, children: []ASTNode{node}} - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{left, right}, - }, err - case tEQ, tNE, tGT, tGTE, tLT, tLTE: - right, err := p.parseExpression(bindingPowers[tokenType]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTComparator, - value: tokenType, - children: []ASTNode{node, right}, - }, nil - case tLbracket: - tokenType := p.current() - var right ASTNode - var err error - if tokenType == tNumber || tokenType == tColon { - right, err = p.parseIndexExpression() - if err != nil { - return ASTNode{}, err - } - return p.projectIfSlice(node, right) - } - // Otherwise this is a projection. - if err := p.match(tStar); err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{node, right}, - }, nil - } - return ASTNode{}, p.syntaxError("Unexpected token: " + tokenType.String()) -} - -func (p *Parser) nud(token token) (ASTNode, error) { - switch token.tokenType { - case tJSONLiteral: - var parsed interface{} - err := json.Unmarshal([]byte(token.value), &parsed) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTLiteral, value: parsed}, nil - case tStringLiteral: - return ASTNode{nodeType: ASTLiteral, value: token.value}, nil - case tUnquotedIdentifier: - return ASTNode{ - nodeType: ASTField, - value: token.value, - }, nil - case tQuotedIdentifier: - node := ASTNode{nodeType: ASTField, value: token.value} - if p.current() == tLparen { - return ASTNode{}, p.syntaxErrorToken("Can't have quoted identifier as function name.", token) - } - return node, nil - case tStar: - left := ASTNode{nodeType: ASTIdentity} - var right ASTNode - var err error - if p.current() == tRbracket { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tStar]) - } - return ASTNode{nodeType: ASTValueProjection, children: []ASTNode{left, right}}, err - case tFilter: - return p.parseFilter(ASTNode{nodeType: ASTIdentity}) - case tLbrace: - return p.parseMultiSelectHash() - case tFlatten: - left := ASTNode{ - nodeType: ASTFlatten, - children: []ASTNode{{nodeType: ASTIdentity}}, - } - right, err := p.parseProjectionRHS(bindingPowers[tFlatten]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTProjection, children: []ASTNode{left, right}}, nil - case tLbracket: - tokenType := p.current() - //var right ASTNode - if tokenType == tNumber || tokenType == tColon { - right, err := p.parseIndexExpression() - if err != nil { - return ASTNode{}, nil - } - return p.projectIfSlice(ASTNode{nodeType: ASTIdentity}, right) - } else if tokenType == tStar && p.lookahead(1) == tRbracket { - p.advance() - p.advance() - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{{nodeType: ASTIdentity}, right}, - }, nil - } else { - return p.parseMultiSelectList() - } - case tCurrent: - return ASTNode{nodeType: ASTCurrentNode}, nil - case tExpref: - expression, err := p.parseExpression(bindingPowers[tExpref]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTExpRef, children: []ASTNode{expression}}, nil - case tNot: - expression, err := p.parseExpression(bindingPowers[tNot]) - if err != nil { - return ASTNode{}, err - } - return ASTNode{nodeType: ASTNotExpression, children: []ASTNode{expression}}, nil - case tLparen: - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRparen); err != nil { - return ASTNode{}, err - } - return expression, nil - case tEOF: - return ASTNode{}, p.syntaxErrorToken("Incomplete expression", token) - } - - return ASTNode{}, p.syntaxErrorToken("Invalid token: "+token.tokenType.String(), token) -} - -func (p *Parser) parseMultiSelectList() (ASTNode, error) { - var expressions []ASTNode - for { - expression, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - expressions = append(expressions, expression) - if p.current() == tRbracket { - break - } - err = p.match(tComma) - if err != nil { - return ASTNode{}, err - } - } - err := p.match(tRbracket) - if err != nil { - return ASTNode{}, err - } - return ASTNode{ - nodeType: ASTMultiSelectList, - children: expressions, - }, nil -} - -func (p *Parser) parseMultiSelectHash() (ASTNode, error) { - var children []ASTNode - for { - keyToken := p.lookaheadToken(0) - if err := p.match(tUnquotedIdentifier); err != nil { - if err := p.match(tQuotedIdentifier); err != nil { - return ASTNode{}, p.syntaxError("Expected tQuotedIdentifier or tUnquotedIdentifier") - } - } - keyName := keyToken.value - err := p.match(tColon) - if err != nil { - return ASTNode{}, err - } - value, err := p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - node := ASTNode{ - nodeType: ASTKeyValPair, - value: keyName, - children: []ASTNode{value}, - } - children = append(children, node) - if p.current() == tComma { - err := p.match(tComma) - if err != nil { - return ASTNode{}, nil - } - } else if p.current() == tRbrace { - err := p.match(tRbrace) - if err != nil { - return ASTNode{}, nil - } - break - } - } - return ASTNode{ - nodeType: ASTMultiSelectHash, - children: children, - }, nil -} - -func (p *Parser) projectIfSlice(left ASTNode, right ASTNode) (ASTNode, error) { - indexExpr := ASTNode{ - nodeType: ASTIndexExpression, - children: []ASTNode{left, right}, - } - if right.nodeType == ASTSlice { - right, err := p.parseProjectionRHS(bindingPowers[tStar]) - return ASTNode{ - nodeType: ASTProjection, - children: []ASTNode{indexExpr, right}, - }, err - } - return indexExpr, nil -} -func (p *Parser) parseFilter(node ASTNode) (ASTNode, error) { - var right, condition ASTNode - var err error - condition, err = p.parseExpression(0) - if err != nil { - return ASTNode{}, err - } - if err := p.match(tRbracket); err != nil { - return ASTNode{}, err - } - if p.current() == tFlatten { - right = ASTNode{nodeType: ASTIdentity} - } else { - right, err = p.parseProjectionRHS(bindingPowers[tFilter]) - if err != nil { - return ASTNode{}, err - } - } - - return ASTNode{ - nodeType: ASTFilterProjection, - children: []ASTNode{node, right, condition}, - }, nil -} - -func (p *Parser) parseDotRHS(bindingPower int) (ASTNode, error) { - lookahead := p.current() - if tokensOneOf([]tokType{tQuotedIdentifier, tUnquotedIdentifier, tStar}, lookahead) { - return p.parseExpression(bindingPower) - } else if lookahead == tLbracket { - if err := p.match(tLbracket); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectList() - } else if lookahead == tLbrace { - if err := p.match(tLbrace); err != nil { - return ASTNode{}, err - } - return p.parseMultiSelectHash() - } - return ASTNode{}, p.syntaxError("Expected identifier, lbracket, or lbrace") -} - -func (p *Parser) parseProjectionRHS(bindingPower int) (ASTNode, error) { - current := p.current() - if bindingPowers[current] < 10 { - return ASTNode{nodeType: ASTIdentity}, nil - } else if current == tLbracket { - return p.parseExpression(bindingPower) - } else if current == tFilter { - return p.parseExpression(bindingPower) - } else if current == tDot { - err := p.match(tDot) - if err != nil { - return ASTNode{}, err - } - return p.parseDotRHS(bindingPower) - } else { - return ASTNode{}, p.syntaxError("Error") - } -} - -func (p *Parser) lookahead(number int) tokType { - return p.lookaheadToken(number).tokenType -} - -func (p *Parser) current() tokType { - return p.lookahead(0) -} - -func (p *Parser) lookaheadToken(number int) token { - return p.tokens[p.index+number] -} - -func (p *Parser) advance() { - p.index++ -} - -func tokensOneOf(elements []tokType, token tokType) bool { - for _, elem := range elements { - if elem == token { - return true - } - } - return false -} - -func (p *Parser) syntaxError(msg string) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: p.lookaheadToken(0).position, - } -} - -// Create a SyntaxError based on the provided token. -// This differs from syntaxError() which creates a SyntaxError -// based on the current lookahead token. -func (p *Parser) syntaxErrorToken(msg string, t token) SyntaxError { - return SyntaxError{ - msg: msg, - Expression: p.expression, - Offset: t.position, - } -} diff --git a/vendor/github.com/jmespath/go-jmespath/toktype_string.go b/vendor/github.com/jmespath/go-jmespath/toktype_string.go deleted file mode 100644 index dae79cbdf3..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/toktype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// generated by stringer -type=tokType; DO NOT EDIT - -package jmespath - -import "fmt" - -const _tokType_name = "tUnknowntStartDottFiltertFlattentLparentRparentLbrackettRbrackettLbracetRbracetOrtPipetNumbertUnquotedIdentifiertQuotedIdentifiertCommatColontLTtLTEtGTtGTEtEQtNEtJSONLiteraltStringLiteraltCurrenttExpreftAndtNottEOF" - -var _tokType_index = [...]uint8{0, 8, 13, 17, 24, 32, 39, 46, 55, 64, 71, 78, 81, 86, 93, 112, 129, 135, 141, 144, 148, 151, 155, 158, 161, 173, 187, 195, 202, 206, 210, 214} - -func (i tokType) String() string { - if i < 0 || i >= tokType(len(_tokType_index)-1) { - return fmt.Sprintf("tokType(%d)", i) - } - return _tokType_name[_tokType_index[i]:_tokType_index[i+1]] -} diff --git a/vendor/github.com/jmespath/go-jmespath/util.go b/vendor/github.com/jmespath/go-jmespath/util.go deleted file mode 100644 index ddc1b7d7d4..0000000000 --- a/vendor/github.com/jmespath/go-jmespath/util.go +++ /dev/null @@ -1,185 +0,0 @@ -package jmespath - -import ( - "errors" - "reflect" -) - -// IsFalse determines if an object is false based on the JMESPath spec. -// JMESPath defines false values to be any of: -// - An empty string array, or hash. -// - The boolean value false. -// - nil -func isFalse(value interface{}) bool { - switch v := value.(type) { - case bool: - return !v - case []interface{}: - return len(v) == 0 - case map[string]interface{}: - return len(v) == 0 - case string: - return len(v) == 0 - case nil: - return true - } - // Try the reflection cases before returning false. - rv := reflect.ValueOf(value) - switch rv.Kind() { - case reflect.Struct: - // A struct type will never be false, even if - // all of its values are the zero type. - return false - case reflect.Slice, reflect.Map: - return rv.Len() == 0 - case reflect.Ptr: - if rv.IsNil() { - return true - } - // If it's a pointer type, we'll try to deref the pointer - // and evaluate the pointer value for isFalse. - element := rv.Elem() - return isFalse(element.Interface()) - } - return false -} - -// ObjsEqual is a generic object equality check. -// It will take two arbitrary objects and recursively determine -// if they are equal. -func objsEqual(left interface{}, right interface{}) bool { - return reflect.DeepEqual(left, right) -} - -// SliceParam refers to a single part of a slice. -// A slice consists of a start, a stop, and a step, similar to -// python slices. -type sliceParam struct { - N int - Specified bool -} - -// Slice supports [start:stop:step] style slicing that's supported in JMESPath. -func slice(slice []interface{}, parts []sliceParam) ([]interface{}, error) { - computed, err := computeSliceParams(len(slice), parts) - if err != nil { - return nil, err - } - start, stop, step := computed[0], computed[1], computed[2] - result := []interface{}{} - if step > 0 { - for i := start; i < stop; i += step { - result = append(result, slice[i]) - } - } else { - for i := start; i > stop; i += step { - result = append(result, slice[i]) - } - } - return result, nil -} - -func computeSliceParams(length int, parts []sliceParam) ([]int, error) { - var start, stop, step int - if !parts[2].Specified { - step = 1 - } else if parts[2].N == 0 { - return nil, errors.New("Invalid slice, step cannot be 0") - } else { - step = parts[2].N - } - var stepValueNegative bool - if step < 0 { - stepValueNegative = true - } else { - stepValueNegative = false - } - - if !parts[0].Specified { - if stepValueNegative { - start = length - 1 - } else { - start = 0 - } - } else { - start = capSlice(length, parts[0].N, step) - } - - if !parts[1].Specified { - if stepValueNegative { - stop = -1 - } else { - stop = length - } - } else { - stop = capSlice(length, parts[1].N, step) - } - return []int{start, stop, step}, nil -} - -func capSlice(length int, actual int, step int) int { - if actual < 0 { - actual += length - if actual < 0 { - if step < 0 { - actual = -1 - } else { - actual = 0 - } - } - } else if actual >= length { - if step < 0 { - actual = length - 1 - } else { - actual = length - } - } - return actual -} - -// ToArrayNum converts an empty interface type to a slice of float64. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. -func toArrayNum(data interface{}) ([]float64, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]float64, len(d)) - for i, el := range d { - item, ok := el.(float64) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -// ToArrayStr converts an empty interface type to a slice of strings. -// If any element in the array cannot be converted, then nil is returned -// along with a second value of false. If the input data could be entirely -// converted, then the converted data, along with a second value of true, -// will be returned. -func toArrayStr(data interface{}) ([]string, bool) { - // Is there a better way to do this with reflect? - if d, ok := data.([]interface{}); ok { - result := make([]string, len(d)) - for i, el := range d { - item, ok := el.(string) - if !ok { - return nil, false - } - result[i] = item - } - return result, true - } - return nil, false -} - -func isSliceType(v interface{}) bool { - if v == nil { - return false - } - return reflect.TypeOf(v).Kind() == reflect.Slice -} diff --git a/vendor/github.com/mailru/easyjson/LICENSE b/vendor/github.com/mailru/easyjson/LICENSE deleted file mode 100644 index fbff658f70..0000000000 --- a/vendor/github.com/mailru/easyjson/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2016 Mail.Ru Group - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mailru/easyjson/buffer/pool.go b/vendor/github.com/mailru/easyjson/buffer/pool.go deleted file mode 100644 index 07fb4bc1f7..0000000000 --- a/vendor/github.com/mailru/easyjson/buffer/pool.go +++ /dev/null @@ -1,270 +0,0 @@ -// Package buffer implements a buffer for serialization, consisting of a chain of []byte-s to -// reduce copying and to allow reuse of individual chunks. -package buffer - -import ( - "io" - "sync" -) - -// PoolConfig contains configuration for the allocation and reuse strategy. -type PoolConfig struct { - StartSize int // Minimum chunk size that is allocated. - PooledSize int // Minimum chunk size that is reused, reusing chunks too small will result in overhead. - MaxSize int // Maximum chunk size that will be allocated. -} - -var config = PoolConfig{ - StartSize: 128, - PooledSize: 512, - MaxSize: 32768, -} - -// Reuse pool: chunk size -> pool. -var buffers = map[int]*sync.Pool{} - -func initBuffers() { - for l := config.PooledSize; l <= config.MaxSize; l *= 2 { - buffers[l] = new(sync.Pool) - } -} - -func init() { - initBuffers() -} - -// Init sets up a non-default pooling and allocation strategy. Should be run before serialization is done. -func Init(cfg PoolConfig) { - config = cfg - initBuffers() -} - -// putBuf puts a chunk to reuse pool if it can be reused. -func putBuf(buf []byte) { - size := cap(buf) - if size < config.PooledSize { - return - } - if c := buffers[size]; c != nil { - c.Put(buf[:0]) - } -} - -// getBuf gets a chunk from reuse pool or creates a new one if reuse failed. -func getBuf(size int) []byte { - if size < config.PooledSize { - return make([]byte, 0, size) - } - - if c := buffers[size]; c != nil { - v := c.Get() - if v != nil { - return v.([]byte) - } - } - return make([]byte, 0, size) -} - -// Buffer is a buffer optimized for serialization without extra copying. -type Buffer struct { - - // Buf is the current chunk that can be used for serialization. - Buf []byte - - toPool []byte - bufs [][]byte -} - -// EnsureSpace makes sure that the current chunk contains at least s free bytes, -// possibly creating a new chunk. -func (b *Buffer) EnsureSpace(s int) { - if cap(b.Buf)-len(b.Buf) >= s { - return - } - l := len(b.Buf) - if l > 0 { - if cap(b.toPool) != cap(b.Buf) { - // Chunk was reallocated, toPool can be pooled. - putBuf(b.toPool) - } - if cap(b.bufs) == 0 { - b.bufs = make([][]byte, 0, 8) - } - b.bufs = append(b.bufs, b.Buf) - l = cap(b.toPool) * 2 - } else { - l = config.StartSize - } - - if l > config.MaxSize { - l = config.MaxSize - } - b.Buf = getBuf(l) - b.toPool = b.Buf -} - -// AppendByte appends a single byte to buffer. -func (b *Buffer) AppendByte(data byte) { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } - b.Buf = append(b.Buf, data) -} - -// AppendBytes appends a byte slice to buffer. -func (b *Buffer) AppendBytes(data []byte) { - for len(data) > 0 { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// AppendBytes appends a string to buffer. -func (b *Buffer) AppendString(data string) { - for len(data) > 0 { - if cap(b.Buf) == len(b.Buf) { // EnsureSpace won't be inlined. - b.EnsureSpace(1) - } - - sz := cap(b.Buf) - len(b.Buf) - if sz > len(data) { - sz = len(data) - } - - b.Buf = append(b.Buf, data[:sz]...) - data = data[sz:] - } -} - -// Size computes the size of a buffer by adding sizes of every chunk. -func (b *Buffer) Size() int { - size := len(b.Buf) - for _, buf := range b.bufs { - size += len(buf) - } - return size -} - -// DumpTo outputs the contents of a buffer to a writer and resets the buffer. -func (b *Buffer) DumpTo(w io.Writer) (written int, err error) { - var n int - for _, buf := range b.bufs { - if err == nil { - n, err = w.Write(buf) - written += n - } - putBuf(buf) - } - - if err == nil { - n, err = w.Write(b.Buf) - written += n - } - putBuf(b.toPool) - - b.bufs = nil - b.Buf = nil - b.toPool = nil - - return -} - -// BuildBytes creates a single byte slice with all the contents of the buffer. Data is -// copied if it does not fit in a single chunk. You can optionally provide one byte -// slice as argument that it will try to reuse. -func (b *Buffer) BuildBytes(reuse ...[]byte) []byte { - if len(b.bufs) == 0 { - ret := b.Buf - b.toPool = nil - b.Buf = nil - return ret - } - - var ret []byte - size := b.Size() - - // If we got a buffer as argument and it is big enought, reuse it. - if len(reuse) == 1 && cap(reuse[0]) >= size { - ret = reuse[0][:0] - } else { - ret = make([]byte, 0, size) - } - for _, buf := range b.bufs { - ret = append(ret, buf...) - putBuf(buf) - } - - ret = append(ret, b.Buf...) - putBuf(b.toPool) - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} - -type readCloser struct { - offset int - bufs [][]byte -} - -func (r *readCloser) Read(p []byte) (n int, err error) { - for _, buf := range r.bufs { - // Copy as much as we can. - x := copy(p[n:], buf[r.offset:]) - n += x // Increment how much we filled. - - // Did we empty the whole buffer? - if r.offset+x == len(buf) { - // On to the next buffer. - r.offset = 0 - r.bufs = r.bufs[1:] - - // We can release this buffer. - putBuf(buf) - } else { - r.offset += x - } - - if n == len(p) { - break - } - } - // No buffers left or nothing read? - if len(r.bufs) == 0 { - err = io.EOF - } - return -} - -func (r *readCloser) Close() error { - // Release all remaining buffers. - for _, buf := range r.bufs { - putBuf(buf) - } - // In case Close gets called multiple times. - r.bufs = nil - - return nil -} - -// ReadCloser creates an io.ReadCloser with all the contents of the buffer. -func (b *Buffer) ReadCloser() io.ReadCloser { - ret := &readCloser{0, append(b.bufs, b.Buf)} - - b.bufs = nil - b.toPool = nil - b.Buf = nil - - return ret -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go deleted file mode 100644 index ff7b27c5b2..0000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr.go +++ /dev/null @@ -1,24 +0,0 @@ -// This file will only be included to the build if neither -// easyjson_nounsafe nor appengine build tag is set. See README notes -// for more details. - -//+build !easyjson_nounsafe -//+build !appengine - -package jlexer - -import ( - "reflect" - "unsafe" -) - -// bytesToStr creates a string pointing at the slice to avoid copying. -// -// Warning: the string returned by the function should be used with care, as the whole input data -// chunk may be either blocked from being freed by GC because of a single string or the buffer.Data -// may be garbage-collected even when the string exists. -func bytesToStr(data []byte) string { - h := (*reflect.SliceHeader)(unsafe.Pointer(&data)) - shdr := reflect.StringHeader{Data: h.Data, Len: h.Len} - return *(*string)(unsafe.Pointer(&shdr)) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go b/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go deleted file mode 100644 index 864d1be676..0000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/bytestostr_nounsafe.go +++ /dev/null @@ -1,13 +0,0 @@ -// This file is included to the build if any of the buildtags below -// are defined. Refer to README notes for more details. - -//+build easyjson_nounsafe appengine - -package jlexer - -// bytesToStr creates a string normally from []byte -// -// Note that this method is roughly 1.5x slower than using the 'unsafe' method. -func bytesToStr(data []byte) string { - return string(data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/error.go b/vendor/github.com/mailru/easyjson/jlexer/error.go deleted file mode 100644 index e90ec40d05..0000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/error.go +++ /dev/null @@ -1,15 +0,0 @@ -package jlexer - -import "fmt" - -// LexerError implements the error interface and represents all possible errors that can be -// generated during parsing the JSON data. -type LexerError struct { - Reason string - Offset int - Data string -} - -func (l *LexerError) Error() string { - return fmt.Sprintf("parse error: %s near offset %d of '%s'", l.Reason, l.Offset, l.Data) -} diff --git a/vendor/github.com/mailru/easyjson/jlexer/lexer.go b/vendor/github.com/mailru/easyjson/jlexer/lexer.go deleted file mode 100644 index e81f1031b0..0000000000 --- a/vendor/github.com/mailru/easyjson/jlexer/lexer.go +++ /dev/null @@ -1,1114 +0,0 @@ -// Package jlexer contains a JSON lexer implementation. -// -// It is expected that it is mostly used with generated parser code, so the interface is tuned -// for a parser that knows what kind of data is expected. -package jlexer - -import ( - "encoding/base64" - "errors" - "fmt" - "io" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -// tokenKind determines type of a token. -type tokenKind byte - -const ( - tokenUndef tokenKind = iota // No token. - tokenDelim // Delimiter: one of '{', '}', '[' or ']'. - tokenString // A string literal, e.g. "abc\u1234" - tokenNumber // Number literal, e.g. 1.5e5 - tokenBool // Boolean literal: true or false. - tokenNull // null keyword. -) - -// token describes a single token: type, position in the input and value. -type token struct { - kind tokenKind // Type of a token. - - boolValue bool // Value if a boolean literal token. - byteValue []byte // Raw value of a token. - delimValue byte -} - -// Lexer is a JSON lexer: it iterates over JSON tokens in a byte slice. -type Lexer struct { - Data []byte // Input data given to the lexer. - - start int // Start of the current token. - pos int // Current unscanned position in the input stream. - token token // Last scanned token, if token.kind != tokenUndef. - - firstElement bool // Whether current element is the first in array or an object. - wantSep byte // A comma or a colon character, which need to occur before a token. - - UseMultipleErrors bool // If we want to use multiple errors. - fatalError error // Fatal error occurred during lexing. It is usually a syntax error. - multipleErrors []*LexerError // Semantic errors occurred during lexing. Marshalling will be continued after finding this errors. -} - -// FetchToken scans the input for the next token. -func (r *Lexer) FetchToken() { - r.token.kind = tokenUndef - r.start = r.pos - - // Check if r.Data has r.pos element - // If it doesn't, it mean corrupted input data - if len(r.Data) < r.pos { - r.errParse("Unexpected end of data") - return - } - // Determine the type of a token by skipping whitespace and reading the - // first character. - for _, c := range r.Data[r.pos:] { - switch c { - case ':', ',': - if r.wantSep == c { - r.pos++ - r.start++ - r.wantSep = 0 - } else { - r.errSyntax() - } - - case ' ', '\t', '\r', '\n': - r.pos++ - r.start++ - - case '"': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenString - r.fetchString() - return - - case '{', '[': - if r.wantSep != 0 { - r.errSyntax() - } - r.firstElement = true - r.token.kind = tokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '}', ']': - if !r.firstElement && (r.wantSep != ',') { - r.errSyntax() - } - r.wantSep = 0 - r.token.kind = tokenDelim - r.token.delimValue = r.Data[r.pos] - r.pos++ - return - - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': - if r.wantSep != 0 { - r.errSyntax() - } - r.token.kind = tokenNumber - r.fetchNumber() - return - - case 'n': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenNull - r.fetchNull() - return - - case 't': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenBool - r.token.boolValue = true - r.fetchTrue() - return - - case 'f': - if r.wantSep != 0 { - r.errSyntax() - } - - r.token.kind = tokenBool - r.token.boolValue = false - r.fetchFalse() - return - - default: - r.errSyntax() - return - } - } - r.fatalError = io.EOF - return -} - -// isTokenEnd returns true if the char can follow a non-delimiter token -func isTokenEnd(c byte) bool { - return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '[' || c == ']' || c == '{' || c == '}' || c == ',' || c == ':' -} - -// fetchNull fetches and checks remaining bytes of null keyword. -func (r *Lexer) fetchNull() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'u' || - r.Data[r.pos-2] != 'l' || - r.Data[r.pos-1] != 'l' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchTrue fetches and checks remaining bytes of true keyword. -func (r *Lexer) fetchTrue() { - r.pos += 4 - if r.pos > len(r.Data) || - r.Data[r.pos-3] != 'r' || - r.Data[r.pos-2] != 'u' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 4 - r.errSyntax() - } -} - -// fetchFalse fetches and checks remaining bytes of false keyword. -func (r *Lexer) fetchFalse() { - r.pos += 5 - if r.pos > len(r.Data) || - r.Data[r.pos-4] != 'a' || - r.Data[r.pos-3] != 'l' || - r.Data[r.pos-2] != 's' || - r.Data[r.pos-1] != 'e' || - (r.pos != len(r.Data) && !isTokenEnd(r.Data[r.pos])) { - - r.pos -= 5 - r.errSyntax() - } -} - -// fetchNumber scans a number literal token. -func (r *Lexer) fetchNumber() { - hasE := false - afterE := false - hasDot := false - - r.pos++ - for i, c := range r.Data[r.pos:] { - switch { - case c >= '0' && c <= '9': - afterE = false - case c == '.' && !hasDot: - hasDot = true - case (c == 'e' || c == 'E') && !hasE: - hasE = true - hasDot = true - afterE = true - case (c == '+' || c == '-') && afterE: - afterE = false - default: - r.pos += i - if !isTokenEnd(c) { - r.errSyntax() - } else { - r.token.byteValue = r.Data[r.start:r.pos] - } - return - } - } - - r.pos = len(r.Data) - r.token.byteValue = r.Data[r.start:] -} - -// findStringLen tries to scan into the string literal for ending quote char to determine required size. -// The size will be exact if no escapes are present and may be inexact if there are escaped chars. -func findStringLen(data []byte) (hasEscapes bool, length int) { - delta := 0 - - for i := 0; i < len(data); i++ { - switch data[i] { - case '\\': - i++ - delta++ - if i < len(data) && data[i] == 'u' { - delta++ - } - case '"': - return (delta > 0), (i - delta) - } - } - - return false, len(data) -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - var val rune - for i := 2; i < len(s) && i < 6; i++ { - var v byte - c := s[i] - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - v = c - '0' - case 'a', 'b', 'c', 'd', 'e', 'f': - v = c - 'a' + 10 - case 'A', 'B', 'C', 'D', 'E', 'F': - v = c - 'A' + 10 - default: - return -1 - } - - val <<= 4 - val |= rune(v) - } - return val -} - -// processEscape processes a single escape sequence and returns number of bytes processed. -func (r *Lexer) processEscape(data []byte) (int, error) { - if len(data) < 2 { - return 0, fmt.Errorf("syntax error at %v", string(data)) - } - - c := data[1] - switch c { - case '"', '/', '\\': - r.token.byteValue = append(r.token.byteValue, c) - return 2, nil - case 'b': - r.token.byteValue = append(r.token.byteValue, '\b') - return 2, nil - case 'f': - r.token.byteValue = append(r.token.byteValue, '\f') - return 2, nil - case 'n': - r.token.byteValue = append(r.token.byteValue, '\n') - return 2, nil - case 'r': - r.token.byteValue = append(r.token.byteValue, '\r') - return 2, nil - case 't': - r.token.byteValue = append(r.token.byteValue, '\t') - return 2, nil - case 'u': - rr := getu4(data) - if rr < 0 { - return 0, errors.New("syntax error") - } - - read := 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(data[read:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - read += 6 - rr = dec - } else { - rr = unicode.ReplacementChar - } - } - var d [4]byte - s := utf8.EncodeRune(d[:], rr) - r.token.byteValue = append(r.token.byteValue, d[:s]...) - return read, nil - } - - return 0, errors.New("syntax error") -} - -// fetchString scans a string literal token. -func (r *Lexer) fetchString() { - r.pos++ - data := r.Data[r.pos:] - - hasEscapes, length := findStringLen(data) - if !hasEscapes { - r.token.byteValue = data[:length] - r.pos += length + 1 - return - } - - r.token.byteValue = make([]byte, 0, length) - p := 0 - for i := 0; i < len(data); { - switch data[i] { - case '"': - r.pos += i + 1 - r.token.byteValue = append(r.token.byteValue, data[p:i]...) - i++ - return - - case '\\': - r.token.byteValue = append(r.token.byteValue, data[p:i]...) - off, err := r.processEscape(data[i:]) - if err != nil { - r.errParse(err.Error()) - return - } - i += off - p = i - - default: - i++ - } - } - r.errParse("unterminated string literal") -} - -// scanToken scans the next token if no token is currently available in the lexer. -func (r *Lexer) scanToken() { - if r.token.kind != tokenUndef || r.fatalError != nil { - return - } - - r.FetchToken() -} - -// consume resets the current token to allow scanning the next one. -func (r *Lexer) consume() { - r.token.kind = tokenUndef - r.token.delimValue = 0 -} - -// Ok returns true if no error (including io.EOF) was encountered during scanning. -func (r *Lexer) Ok() bool { - return r.fatalError == nil -} - -const maxErrorContextLen = 13 - -func (r *Lexer) errParse(what string) { - if r.fatalError == nil { - var str string - if len(r.Data)-r.pos <= maxErrorContextLen { - str = string(r.Data) - } else { - str = string(r.Data[r.pos:r.pos+maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: what, - Offset: r.pos, - Data: str, - } - } -} - -func (r *Lexer) errSyntax() { - r.errParse("syntax error") -} - -func (r *Lexer) errInvalidToken(expected string) { - if r.fatalError != nil { - return - } - if r.UseMultipleErrors { - r.pos = r.start - r.consume() - r.SkipRecursive() - switch expected { - case "[": - r.token.delimValue = ']' - r.token.kind = tokenDelim - case "{": - r.token.delimValue = '}' - r.token.kind = tokenDelim - } - r.addNonfatalError(&LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - }) - return - } - - var str string - if len(r.token.byteValue) <= maxErrorContextLen { - str = string(r.token.byteValue) - } else { - str = string(r.token.byteValue[:maxErrorContextLen-3]) + "..." - } - r.fatalError = &LexerError{ - Reason: fmt.Sprintf("expected %s", expected), - Offset: r.pos, - Data: str, - } -} - -func (r *Lexer) GetPos() int { - return r.pos -} - -// Delim consumes a token and verifies that it is the given delimiter. -func (r *Lexer) Delim(c byte) { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() || r.token.delimValue != c { - r.consume() // errInvalidToken can change token if UseMultipleErrors is enabled. - r.errInvalidToken(string([]byte{c})) - } else { - r.consume() - } -} - -// IsDelim returns true if there was no scanning error and next token is the given delimiter. -func (r *Lexer) IsDelim(c byte) bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - return !r.Ok() || r.token.delimValue == c -} - -// Null verifies that the next token is null and consumes it. -func (r *Lexer) Null() { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenNull { - r.errInvalidToken("null") - } - r.consume() -} - -// IsNull returns true if the next token is a null keyword. -func (r *Lexer) IsNull() bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - return r.Ok() && r.token.kind == tokenNull -} - -// Skip skips a single token. -func (r *Lexer) Skip() { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - r.consume() -} - -// SkipRecursive skips next array or object completely, or just skips a single token if not -// an array/object. -// -// Note: no syntax validation is performed on the skipped data. -func (r *Lexer) SkipRecursive() { - r.scanToken() - var start, end byte - - if r.token.delimValue == '{' { - start, end = '{', '}' - } else if r.token.delimValue == '[' { - start, end = '[', ']' - } else { - r.consume() - return - } - - r.consume() - - level := 1 - inQuotes := false - wasEscape := false - - for i, c := range r.Data[r.pos:] { - switch { - case c == start && !inQuotes: - level++ - case c == end && !inQuotes: - level-- - if level == 0 { - r.pos += i + 1 - return - } - case c == '\\' && inQuotes: - wasEscape = !wasEscape - continue - case c == '"' && inQuotes: - inQuotes = wasEscape - case c == '"': - inQuotes = true - } - wasEscape = false - } - r.pos = len(r.Data) - r.fatalError = &LexerError{ - Reason: "EOF reached while skipping array/object or token", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - } -} - -// Raw fetches the next item recursively as a data slice -func (r *Lexer) Raw() []byte { - r.SkipRecursive() - if !r.Ok() { - return nil - } - return r.Data[r.start:r.pos] -} - -// IsStart returns whether the lexer is positioned at the start -// of an input string. -func (r *Lexer) IsStart() bool { - return r.pos == 0 -} - -// Consumed reads all remaining bytes from the input, publishing an error if -// there is anything but whitespace remaining. -func (r *Lexer) Consumed() { - if r.pos > len(r.Data) || !r.Ok() { - return - } - - for _, c := range r.Data[r.pos:] { - if c != ' ' && c != '\t' && c != '\r' && c != '\n' { - r.AddError(&LexerError{ - Reason: "invalid character '" + string(c) + "' after top-level value", - Offset: r.pos, - Data: string(r.Data[r.pos:]), - }) - return - } - - r.pos++ - r.start++ - } -} - -func (r *Lexer) unsafeString() (string, []byte) { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return "", nil - } - bytes := r.token.byteValue - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret, bytes -} - -// UnsafeString returns the string value if the token is a string literal. -// -// Warning: returned string may point to the input buffer, so the string should not outlive -// the input buffer. Intended pattern of usage is as an argument to a switch statement. -func (r *Lexer) UnsafeString() string { - ret, _ := r.unsafeString() - return ret -} - -// UnsafeBytes returns the byte slice if the token is a string literal. -func (r *Lexer) UnsafeBytes() []byte { - _, ret := r.unsafeString() - return ret -} - -// String reads a string literal. -func (r *Lexer) String() string { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return "" - } - ret := string(r.token.byteValue) - r.consume() - return ret -} - -// Bytes reads a string literal and base64 decodes it into a byte slice. -func (r *Lexer) Bytes() []byte { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenString { - r.errInvalidToken("string") - return nil - } - ret := make([]byte, base64.StdEncoding.DecodedLen(len(r.token.byteValue))) - len, err := base64.StdEncoding.Decode(ret, r.token.byteValue) - if err != nil { - r.fatalError = &LexerError{ - Reason: err.Error(), - } - return nil - } - - r.consume() - return ret[:len] -} - -// Bool reads a true or false boolean keyword. -func (r *Lexer) Bool() bool { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenBool { - r.errInvalidToken("bool") - return false - } - ret := r.token.boolValue - r.consume() - return ret -} - -func (r *Lexer) number() string { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - if !r.Ok() || r.token.kind != tokenNumber { - r.errInvalidToken("number") - return "" - } - ret := bytesToStr(r.token.byteValue) - r.consume() - return ret -} - -func (r *Lexer) Uint8() uint8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16() uint16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32() uint32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64() uint64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Uint() uint { - return uint(r.Uint64()) -} - -func (r *Lexer) Int8() int8 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int8(n) -} - -func (r *Lexer) Int16() int16 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int16(n) -} - -func (r *Lexer) Int32() int32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return int32(n) -} - -func (r *Lexer) Int64() int64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Int() int { - return int(r.Int64()) -} - -func (r *Lexer) Uint8Str() uint8 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint8(n) -} - -func (r *Lexer) Uint16Str() uint16 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint16(n) -} - -func (r *Lexer) Uint32Str() uint32 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return uint32(n) -} - -func (r *Lexer) Uint64Str() uint64 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseUint(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) UintStr() uint { - return uint(r.Uint64Str()) -} - -func (r *Lexer) Int8Str() int8 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 8) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int8(n) -} - -func (r *Lexer) Int16Str() int16 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 16) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int16(n) -} - -func (r *Lexer) Int32Str() int32 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return int32(n) -} - -func (r *Lexer) Int64Str() int64 { - s, b := r.unsafeString() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseInt(s, 10, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: string(b), - }) - } - return n -} - -func (r *Lexer) IntStr() int { - return int(r.Int64Str()) -} - -func (r *Lexer) Float32() float32 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 32) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return float32(n) -} - -func (r *Lexer) Float64() float64 { - s := r.number() - if !r.Ok() { - return 0 - } - - n, err := strconv.ParseFloat(s, 64) - if err != nil { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Reason: err.Error(), - Data: s, - }) - } - return n -} - -func (r *Lexer) Error() error { - return r.fatalError -} - -func (r *Lexer) AddError(e error) { - if r.fatalError == nil { - r.fatalError = e - } -} - -func (r *Lexer) AddNonFatalError(e error) { - r.addNonfatalError(&LexerError{ - Offset: r.start, - Data: string(r.Data[r.start:r.pos]), - Reason: e.Error(), - }) -} - -func (r *Lexer) addNonfatalError(err *LexerError) { - if r.UseMultipleErrors { - // We don't want to add errors with the same offset. - if len(r.multipleErrors) != 0 && r.multipleErrors[len(r.multipleErrors)-1].Offset == err.Offset { - return - } - r.multipleErrors = append(r.multipleErrors, err) - return - } - r.fatalError = err -} - -func (r *Lexer) GetNonFatalErrors() []*LexerError { - return r.multipleErrors -} - -// Interface fetches an interface{} analogous to the 'encoding/json' package. -func (r *Lexer) Interface() interface{} { - if r.token.kind == tokenUndef && r.Ok() { - r.FetchToken() - } - - if !r.Ok() { - return nil - } - switch r.token.kind { - case tokenString: - return r.String() - case tokenNumber: - return r.Float64() - case tokenBool: - return r.Bool() - case tokenNull: - r.Null() - return nil - } - - if r.token.delimValue == '{' { - r.consume() - - ret := map[string]interface{}{} - for !r.IsDelim('}') { - key := r.String() - r.WantColon() - ret[key] = r.Interface() - r.WantComma() - } - r.Delim('}') - - if r.Ok() { - return ret - } else { - return nil - } - } else if r.token.delimValue == '[' { - r.consume() - - var ret []interface{} - for !r.IsDelim(']') { - ret = append(ret, r.Interface()) - r.WantComma() - } - r.Delim(']') - - if r.Ok() { - return ret - } else { - return nil - } - } - r.errSyntax() - return nil -} - -// WantComma requires a comma to be present before fetching next token. -func (r *Lexer) WantComma() { - r.wantSep = ',' - r.firstElement = false -} - -// WantColon requires a colon to be present before fetching next token. -func (r *Lexer) WantColon() { - r.wantSep = ':' - r.firstElement = false -} diff --git a/vendor/github.com/mailru/easyjson/jwriter/writer.go b/vendor/github.com/mailru/easyjson/jwriter/writer.go deleted file mode 100644 index 7b55293a0f..0000000000 --- a/vendor/github.com/mailru/easyjson/jwriter/writer.go +++ /dev/null @@ -1,328 +0,0 @@ -// Package jwriter contains a JSON writer. -package jwriter - -import ( - "encoding/base64" - "io" - "strconv" - "unicode/utf8" - - "github.com/mailru/easyjson/buffer" -) - -// Flags describe various encoding options. The behavior may be actually implemented in the encoder, but -// Flags field in Writer is used to set and pass them around. -type Flags int - -const ( - NilMapAsEmpty Flags = 1 << iota // Encode nil map as '{}' rather than 'null'. - NilSliceAsEmpty // Encode nil slice as '[]' rather than 'null'. -) - -// Writer is a JSON writer. -type Writer struct { - Flags Flags - - Error error - Buffer buffer.Buffer - NoEscapeHTML bool -} - -// Size returns the size of the data that was written out. -func (w *Writer) Size() int { - return w.Buffer.Size() -} - -// DumpTo outputs the data to given io.Writer, resetting the buffer. -func (w *Writer) DumpTo(out io.Writer) (written int, err error) { - return w.Buffer.DumpTo(out) -} - -// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice -// as argument that it will try to reuse. -func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.BuildBytes(reuse...), nil -} - -// ReadCloser returns an io.ReadCloser that can be used to read the data. -// ReadCloser also resets the buffer. -func (w *Writer) ReadCloser() (io.ReadCloser, error) { - if w.Error != nil { - return nil, w.Error - } - - return w.Buffer.ReadCloser(), nil -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawByte(c byte) { - w.Buffer.AppendByte(c) -} - -// RawByte appends raw binary data to the buffer. -func (w *Writer) RawString(s string) { - w.Buffer.AppendString(s) -} - -// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for -// calling with results of MarshalJSON-like functions. -func (w *Writer) Raw(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.Buffer.AppendBytes(data) - default: - w.RawString("null") - } -} - -// RawText encloses raw binary data in quotes and appends in to the buffer. -// Useful for calling with results of MarshalText-like functions. -func (w *Writer) RawText(data []byte, err error) { - switch { - case w.Error != nil: - return - case err != nil: - w.Error = err - case len(data) > 0: - w.String(string(data)) - default: - w.RawString("null") - } -} - -// Base64Bytes appends data to the buffer after base64 encoding it -func (w *Writer) Base64Bytes(data []byte) { - if data == nil { - w.Buffer.AppendString("null") - return - } - w.Buffer.AppendByte('"') - dst := make([]byte, base64.StdEncoding.EncodedLen(len(data))) - base64.StdEncoding.Encode(dst, data) - w.Buffer.AppendBytes(dst) - w.Buffer.AppendByte('"') -} - -func (w *Writer) Uint8(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint16(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint32(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) -} - -func (w *Writer) Uint64(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Int8(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int16(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int32(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) -} - -func (w *Writer) Int64(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) -} - -func (w *Writer) Uint8Str(n uint8) { - w.Buffer.EnsureSpace(3) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint16Str(n uint16) { - w.Buffer.EnsureSpace(5) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint32Str(n uint32) { - w.Buffer.EnsureSpace(10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) UintStr(n uint) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, uint64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Uint64Str(n uint64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendUint(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int8Str(n int8) { - w.Buffer.EnsureSpace(4) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int16Str(n int16) { - w.Buffer.EnsureSpace(6) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int32Str(n int32) { - w.Buffer.EnsureSpace(11) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) IntStr(n int) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, int64(n), 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Int64Str(n int64) { - w.Buffer.EnsureSpace(21) - w.Buffer.Buf = append(w.Buffer.Buf, '"') - w.Buffer.Buf = strconv.AppendInt(w.Buffer.Buf, n, 10) - w.Buffer.Buf = append(w.Buffer.Buf, '"') -} - -func (w *Writer) Float32(n float32) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, float64(n), 'g', -1, 32) -} - -func (w *Writer) Float64(n float64) { - w.Buffer.EnsureSpace(20) - w.Buffer.Buf = strconv.AppendFloat(w.Buffer.Buf, n, 'g', -1, 64) -} - -func (w *Writer) Bool(v bool) { - w.Buffer.EnsureSpace(5) - if v { - w.Buffer.Buf = append(w.Buffer.Buf, "true"...) - } else { - w.Buffer.Buf = append(w.Buffer.Buf, "false"...) - } -} - -const chars = "0123456789abcdef" - -func isNotEscapedSingleChar(c byte, escapeHTML bool) bool { - // Note: might make sense to use a table if there are more chars to escape. With 4 chars - // it benchmarks the same. - if escapeHTML { - return c != '<' && c != '>' && c != '&' && c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf - } else { - return c != '\\' && c != '"' && c >= 0x20 && c < utf8.RuneSelf - } -} - -func (w *Writer) String(s string) { - w.Buffer.AppendByte('"') - - // Portions of the string that contain no escapes are appended as - // byte slices. - - p := 0 // last non-escape symbol - - for i := 0; i < len(s); { - c := s[i] - - if isNotEscapedSingleChar(c, !w.NoEscapeHTML) { - // single-width character, no escaping is required - i++ - continue - } else if c < utf8.RuneSelf { - // single-with character, need to escape - w.Buffer.AppendString(s[p:i]) - switch c { - case '\t': - w.Buffer.AppendString(`\t`) - case '\r': - w.Buffer.AppendString(`\r`) - case '\n': - w.Buffer.AppendString(`\n`) - case '\\': - w.Buffer.AppendString(`\\`) - case '"': - w.Buffer.AppendString(`\"`) - default: - w.Buffer.AppendString(`\u00`) - w.Buffer.AppendByte(chars[c>>4]) - w.Buffer.AppendByte(chars[c&0xf]) - } - - i++ - p = i - continue - } - - // broken utf - runeValue, runeWidth := utf8.DecodeRuneInString(s[i:]) - if runeValue == utf8.RuneError && runeWidth == 1 { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\ufffd`) - i++ - p = i - continue - } - - // jsonp stuff - tab separator and line separator - if runeValue == '\u2028' || runeValue == '\u2029' { - w.Buffer.AppendString(s[p:i]) - w.Buffer.AppendString(`\u202`) - w.Buffer.AppendByte(chars[runeValue&0xf]) - i += runeWidth - p = i - continue - } - i += runeWidth - } - w.Buffer.AppendString(s[p:]) - w.Buffer.AppendByte('"') -} diff --git a/vendor/github.com/mattn/go-colorable/LICENSE b/vendor/github.com/mattn/go-colorable/LICENSE deleted file mode 100644 index 91b5cef30e..0000000000 --- a/vendor/github.com/mattn/go-colorable/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Yasuhiro Matsumoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/mattn/go-colorable/README.md b/vendor/github.com/mattn/go-colorable/README.md deleted file mode 100644 index 56729a92ca..0000000000 --- a/vendor/github.com/mattn/go-colorable/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# go-colorable - -[![Godoc Reference](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) -[![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) -[![Coverage Status](https://coveralls.io/repos/github/mattn/go-colorable/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-colorable?branch=master) -[![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) - -Colorable writer for windows. - -For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) -This package is possible to handle escape sequence for ansi color on windows. - -## Too Bad! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) - - -## So Good! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) - -## Usage - -```go -logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) -logrus.SetOutput(colorable.NewColorableStdout()) - -logrus.Info("succeeded") -logrus.Warn("not correct") -logrus.Error("something error") -logrus.Fatal("panic") -``` - -You can compile above code on non-windows OSs. - -## Installation - -``` -$ go get github.com/mattn/go-colorable -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/mattn/go-colorable/colorable_appengine.go b/vendor/github.com/mattn/go-colorable/colorable_appengine.go deleted file mode 100644 index 1f28d773d7..0000000000 --- a/vendor/github.com/mattn/go-colorable/colorable_appengine.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable return new instance of Writer which handle escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_others.go b/vendor/github.com/mattn/go-colorable/colorable_others.go deleted file mode 100644 index 887f203dc7..0000000000 --- a/vendor/github.com/mattn/go-colorable/colorable_others.go +++ /dev/null @@ -1,30 +0,0 @@ -// +build !windows -// +build !appengine - -package colorable - -import ( - "io" - "os" - - _ "github.com/mattn/go-isatty" -) - -// NewColorable return new instance of Writer which handle escape sequence. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return os.Stdout -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/mattn/go-colorable/colorable_windows.go b/vendor/github.com/mattn/go-colorable/colorable_windows.go deleted file mode 100644 index 575a1343cd..0000000000 --- a/vendor/github.com/mattn/go-colorable/colorable_windows.go +++ /dev/null @@ -1,874 +0,0 @@ -// +build windows -// +build !appengine - -package colorable - -import ( - "bytes" - "io" - "math" - "os" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/mattn/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 - -type coord struct { - x short - y short -} - -type smallRect struct { - left short - top short - right short - bottom short -} - -type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect - maximumWindowSize coord -} - -type consoleCursorInfo struct { - size dword - visible int32 -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") - procGetConsoleCursorInfo = kernel32.NewProc("GetConsoleCursorInfo") - procSetConsoleCursorInfo = kernel32.NewProc("SetConsoleCursorInfo") - procSetConsoleTitle = kernel32.NewProc("SetConsoleTitleW") -) - -// Writer provide colorable Writer to the console -type Writer struct { - out io.Writer - handle syscall.Handle - oldattr word - oldpos coord -} - -// NewColorable return new instance of Writer which handle escape sequence from File. -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - if isatty.IsTerminal(file.Fd()) { - var csbi consoleScreenBufferInfo - handle := syscall.Handle(file.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: file, handle: handle, oldattr: csbi.attributes, oldpos: coord{0, 0}} - } - return file -} - -// NewColorableStdout return new instance of Writer which handle escape sequence for stdout. -func NewColorableStdout() io.Writer { - return NewColorable(os.Stdout) -} - -// NewColorableStderr return new instance of Writer which handle escape sequence for stderr. -func NewColorableStderr() io.Writer { - return NewColorable(os.Stderr) -} - -var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, - 100: 0x878700, - 101: 0x87875f, - 102: 0x878787, - 103: 0x8787af, - 104: 0x8787d7, - 105: 0x8787ff, - 106: 0x87af00, - 107: 0x87af5f, - 108: 0x87af87, - 109: 0x87afaf, - 110: 0x87afd7, - 111: 0x87afff, - 112: 0x87d700, - 113: 0x87d75f, - 114: 0x87d787, - 115: 0x87d7af, - 116: 0x87d7d7, - 117: 0x87d7ff, - 118: 0x87ff00, - 119: 0x87ff5f, - 120: 0x87ff87, - 121: 0x87ffaf, - 122: 0x87ffd7, - 123: 0x87ffff, - 124: 0xaf0000, - 125: 0xaf005f, - 126: 0xaf0087, - 127: 0xaf00af, - 128: 0xaf00d7, - 129: 0xaf00ff, - 130: 0xaf5f00, - 131: 0xaf5f5f, - 132: 0xaf5f87, - 133: 0xaf5faf, - 134: 0xaf5fd7, - 135: 0xaf5fff, - 136: 0xaf8700, - 137: 0xaf875f, - 138: 0xaf8787, - 139: 0xaf87af, - 140: 0xaf87d7, - 141: 0xaf87ff, - 142: 0xafaf00, - 143: 0xafaf5f, - 144: 0xafaf87, - 145: 0xafafaf, - 146: 0xafafd7, - 147: 0xafafff, - 148: 0xafd700, - 149: 0xafd75f, - 150: 0xafd787, - 151: 0xafd7af, - 152: 0xafd7d7, - 153: 0xafd7ff, - 154: 0xafff00, - 155: 0xafff5f, - 156: 0xafff87, - 157: 0xafffaf, - 158: 0xafffd7, - 159: 0xafffff, - 160: 0xd70000, - 161: 0xd7005f, - 162: 0xd70087, - 163: 0xd700af, - 164: 0xd700d7, - 165: 0xd700ff, - 166: 0xd75f00, - 167: 0xd75f5f, - 168: 0xd75f87, - 169: 0xd75faf, - 170: 0xd75fd7, - 171: 0xd75fff, - 172: 0xd78700, - 173: 0xd7875f, - 174: 0xd78787, - 175: 0xd787af, - 176: 0xd787d7, - 177: 0xd787ff, - 178: 0xd7af00, - 179: 0xd7af5f, - 180: 0xd7af87, - 181: 0xd7afaf, - 182: 0xd7afd7, - 183: 0xd7afff, - 184: 0xd7d700, - 185: 0xd7d75f, - 186: 0xd7d787, - 187: 0xd7d7af, - 188: 0xd7d7d7, - 189: 0xd7d7ff, - 190: 0xd7ff00, - 191: 0xd7ff5f, - 192: 0xd7ff87, - 193: 0xd7ffaf, - 194: 0xd7ffd7, - 195: 0xd7ffff, - 196: 0xff0000, - 197: 0xff005f, - 198: 0xff0087, - 199: 0xff00af, - 200: 0xff00d7, - 201: 0xff00ff, - 202: 0xff5f00, - 203: 0xff5f5f, - 204: 0xff5f87, - 205: 0xff5faf, - 206: 0xff5fd7, - 207: 0xff5fff, - 208: 0xff8700, - 209: 0xff875f, - 210: 0xff8787, - 211: 0xff87af, - 212: 0xff87d7, - 213: 0xff87ff, - 214: 0xffaf00, - 215: 0xffaf5f, - 216: 0xffaf87, - 217: 0xffafaf, - 218: 0xffafd7, - 219: 0xffafff, - 220: 0xffd700, - 221: 0xffd75f, - 222: 0xffd787, - 223: 0xffd7af, - 224: 0xffd7d7, - 225: 0xffd7ff, - 226: 0xffff00, - 227: 0xffff5f, - 228: 0xffff87, - 229: 0xffffaf, - 230: 0xffffd7, - 231: 0xffffff, - 232: 0x080808, - 233: 0x121212, - 234: 0x1c1c1c, - 235: 0x262626, - 236: 0x303030, - 237: 0x3a3a3a, - 238: 0x444444, - 239: 0x4e4e4e, - 240: 0x585858, - 241: 0x626262, - 242: 0x6c6c6c, - 243: 0x767676, - 244: 0x808080, - 245: 0x8a8a8a, - 246: 0x949494, - 247: 0x9e9e9e, - 248: 0xa8a8a8, - 249: 0xb2b2b2, - 250: 0xbcbcbc, - 251: 0xc6c6c6, - 252: 0xd0d0d0, - 253: 0xdadada, - 254: 0xe4e4e4, - 255: 0xeeeeee, -} - -// `\033]0;TITLESTR\007` -func doTitleSequence(er *bytes.Reader) error { - var c byte - var err error - - c, err = er.ReadByte() - if err != nil { - return err - } - if c != '0' && c != '2' { - return nil - } - c, err = er.ReadByte() - if err != nil { - return err - } - if c != ';' { - return nil - } - title := make([]byte, 0, 80) - for { - c, err = er.ReadByte() - if err != nil { - return err - } - if c == 0x07 || c == '\n' { - break - } - title = append(title, c) - } - if len(title) > 0 { - title8, err := syscall.UTF16PtrFromString(string(title)) - if err == nil { - procSetConsoleTitle.Call(uintptr(unsafe.Pointer(title8))) - } - } - return nil -} - -// Write write data on console -func (w *Writer) Write(data []byte) (n int, err error) { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - - er := bytes.NewReader(data) - var bw [1]byte -loop: - for { - c1, err := er.ReadByte() - if err != nil { - break loop - } - if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) - continue - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - - if c2 == ']' { - if err := doTitleSequence(er); err != nil { - break loop - } - continue - } - if c2 != 0x5b { - continue - } - - var buf bytes.Buffer - var m byte - for { - c, err := er.ReadByte() - if err != nil { - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - m = c - break - } - buf.Write([]byte(string(c))) - } - - switch m { - case 'A': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'B': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'C': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'D': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'E': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'F': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'G': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = short(n - 1) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'H': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - if buf.Len() > 0 { - token := strings.Split(buf.String(), ";") - switch len(token) { - case 1: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - csbi.cursorPosition.y = short(n1 - 1) - case 2: - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - n2, err := strconv.Atoi(token[1]) - if err != nil { - continue - } - csbi.cursorPosition.x = short(n2 - 1) - csbi.cursorPosition.y = short(n1 - 1) - } - } else { - csbi.cursorPosition.y = 0 - } - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'J': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - var count, written dword - var cursor coord - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.window.top-csbi.cursorPosition.y)*csbi.size.x) - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - } - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'K': - n := 0 - if buf.Len() > 0 { - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - var cursor coord - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - } - var count, written dword - count = dword(csbi.size.x - csbi.cursorPosition.x) - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'm': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - attr := csbi.attributes - cs := buf.String() - if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) - continue - } - token := strings.Split(cs, ";") - for i := 0; i < len(token); i++ { - ns := token[i] - if n, err = strconv.Atoi(ns); err == nil { - switch { - case n == 0 || n == 100: - attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case n == 22 || n == 25: - attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 30 <= n && n <= 37: - attr &= backgroundMask - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case n == 38: // set foreground color. - if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256foreAttr == nil { - n256setup() - } - attr &= backgroundMask - attr |= n256foreAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & backgroundMask) - } - case n == 39: // reset foreground color. - attr &= backgroundMask - attr |= w.oldattr & foregroundMask - case 40 <= n && n <= 47: - attr &= foregroundMask - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case n == 48: // set background color. - if i < len(token)-2 && token[i+1] == "5" { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256backAttr == nil { - n256setup() - } - attr &= foregroundMask - attr |= n256backAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & foregroundMask) - } - case n == 49: // reset foreground color. - attr &= foregroundMask - attr |= w.oldattr & backgroundMask - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) - } - } - case 'h': - cs := buf.String() - if cs == "?25" { - var ci consoleCursorInfo - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 1 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } - case 'l': - cs := buf.String() - if cs == "?25" { - var ci consoleCursorInfo - procGetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - ci.visible = 0 - procSetConsoleCursorInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&ci))) - } - case 's': - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - w.oldpos = csbi.cursorPosition - case 'u': - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&w.oldpos))) - } - } - - return len(data), nil -} - -type consoleColor struct { - rgb int - red bool - green bool - blue bool - intensity bool -} - -func (c consoleColor) foregroundAttr() (attr word) { - if c.red { - attr |= foregroundRed - } - if c.green { - attr |= foregroundGreen - } - if c.blue { - attr |= foregroundBlue - } - if c.intensity { - attr |= foregroundIntensity - } - return -} - -func (c consoleColor) backgroundAttr() (attr word) { - if c.red { - attr |= backgroundRed - } - if c.green { - attr |= backgroundGreen - } - if c.blue { - attr |= backgroundBlue - } - if c.intensity { - attr |= backgroundIntensity - } - return -} - -var color16 = []consoleColor{ - {0x000000, false, false, false, false}, - {0x000080, false, false, true, false}, - {0x008000, false, true, false, false}, - {0x008080, false, true, true, false}, - {0x800000, true, false, false, false}, - {0x800080, true, false, true, false}, - {0x808000, true, true, false, false}, - {0xc0c0c0, true, true, true, false}, - {0x808080, false, false, false, true}, - {0x0000ff, false, false, true, true}, - {0x00ff00, false, true, false, true}, - {0x00ffff, false, true, true, true}, - {0xff0000, true, false, false, true}, - {0xff00ff, true, false, true, true}, - {0xffff00, true, true, false, true}, - {0xffffff, true, true, true, true}, -} - -type hsv struct { - h, s, v float32 -} - -func (a hsv) dist(b hsv) float32 { - dh := a.h - b.h - switch { - case dh > 0.5: - dh = 1 - dh - case dh < -0.5: - dh = -1 - dh - } - ds := a.s - b.s - dv := a.v - b.v - return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) -} - -func toHSV(rgb int) hsv { - r, g, b := float32((rgb&0xFF0000)>>16)/256.0, - float32((rgb&0x00FF00)>>8)/256.0, - float32(rgb&0x0000FF)/256.0 - min, max := minmax3f(r, g, b) - h := max - min - if h > 0 { - if max == r { - h = (g - b) / h - if h < 0 { - h += 6 - } - } else if max == g { - h = 2 + (b-r)/h - } else { - h = 4 + (r-g)/h - } - } - h /= 6.0 - s := max - min - if max != 0 { - s /= max - } - v := max - return hsv{h: h, s: s, v: v} -} - -type hsvTable []hsv - -func toHSVTable(rgbTable []consoleColor) hsvTable { - t := make(hsvTable, len(rgbTable)) - for i, c := range rgbTable { - t[i] = toHSV(c.rgb) - } - return t -} - -func (t hsvTable) find(rgb int) consoleColor { - hsv := toHSV(rgb) - n := 7 - l := float32(5.0) - for i, p := range t { - d := hsv.dist(p) - if d < l { - l, n = d, i - } - } - return color16[n] -} - -func minmax3f(a, b, c float32) (min, max float32) { - if a < b { - if b < c { - return a, c - } else if a < c { - return a, b - } else { - return c, b - } - } else { - if a < c { - return b, c - } else if b < c { - return b, a - } else { - return c, a - } - } -} - -var n256foreAttr []word -var n256backAttr []word - -func n256setup() { - n256foreAttr = make([]word, 256) - n256backAttr = make([]word, 256) - t := toHSVTable(color16) - for i, rgb := range color256 { - c := t.find(rgb) - n256foreAttr[i] = c.foregroundAttr() - n256backAttr[i] = c.backgroundAttr() - } -} diff --git a/vendor/github.com/mattn/go-colorable/noncolorable.go b/vendor/github.com/mattn/go-colorable/noncolorable.go deleted file mode 100644 index 9721e16f4b..0000000000 --- a/vendor/github.com/mattn/go-colorable/noncolorable.go +++ /dev/null @@ -1,55 +0,0 @@ -package colorable - -import ( - "bytes" - "io" -) - -// NonColorable hold writer but remove escape sequence. -type NonColorable struct { - out io.Writer -} - -// NewNonColorable return new instance of Writer which remove escape sequence from Writer. -func NewNonColorable(w io.Writer) io.Writer { - return &NonColorable{out: w} -} - -// Write write data on console -func (w *NonColorable) Write(data []byte) (n int, err error) { - er := bytes.NewReader(data) - var bw [1]byte -loop: - for { - c1, err := er.ReadByte() - if err != nil { - break loop - } - if c1 != 0x1b { - bw[0] = c1 - w.out.Write(bw[:]) - continue - } - c2, err := er.ReadByte() - if err != nil { - break loop - } - if c2 != 0x5b { - continue - } - - var buf bytes.Buffer - for { - c, err := er.ReadByte() - if err != nil { - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - buf.Write([]byte(string(c))) - } - } - - return len(data), nil -} diff --git a/vendor/github.com/mattn/go-isatty/LICENSE b/vendor/github.com/mattn/go-isatty/LICENSE deleted file mode 100644 index 65dc692b6b..0000000000 --- a/vendor/github.com/mattn/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/mattn/go-isatty/README.md b/vendor/github.com/mattn/go-isatty/README.md deleted file mode 100644 index 1e69004bb0..0000000000 --- a/vendor/github.com/mattn/go-isatty/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# go-isatty - -[![Godoc Reference](https://godoc.org/github.com/mattn/go-isatty?status.svg)](http://godoc.org/github.com/mattn/go-isatty) -[![Build Status](https://travis-ci.org/mattn/go-isatty.svg?branch=master)](https://travis-ci.org/mattn/go-isatty) -[![Coverage Status](https://coveralls.io/repos/github/mattn/go-isatty/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-isatty?branch=master) -[![Go Report Card](https://goreportcard.com/badge/mattn/go-isatty)](https://goreportcard.com/report/mattn/go-isatty) - -isatty for golang - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/mattn/go-isatty" - "os" -) - -func main() { - if isatty.IsTerminal(os.Stdout.Fd()) { - fmt.Println("Is Terminal") - } else if isatty.IsCygwinTerminal(os.Stdout.Fd()) { - fmt.Println("Is Cygwin/MSYS2 Terminal") - } else { - fmt.Println("Is Not Terminal") - } -} -``` - -## Installation - -``` -$ go get github.com/mattn/go-isatty -``` - -## License - -MIT - -## Author - -Yasuhiro Matsumoto (a.k.a mattn) - -## Thanks - -* k-takata: base idea for IsCygwinTerminal - - https://github.com/k-takata/go-iscygpty diff --git a/vendor/github.com/mattn/go-isatty/doc.go b/vendor/github.com/mattn/go-isatty/doc.go deleted file mode 100644 index 17d4f90ebc..0000000000 --- a/vendor/github.com/mattn/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/mattn/go-isatty/isatty_appengine.go b/vendor/github.com/mattn/go-isatty/isatty_appengine.go deleted file mode 100644 index 9584a98842..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_appengine.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build appengine - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on on appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_bsd.go b/vendor/github.com/mattn/go-isatty/isatty_bsd.go deleted file mode 100644 index 42f2514d13..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build darwin freebsd openbsd netbsd dragonfly -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_linux.go b/vendor/github.com/mattn/go-isatty/isatty_linux.go deleted file mode 100644 index 9d24bac1db..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_linux.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_others.go b/vendor/github.com/mattn/go-isatty/isatty_others.go deleted file mode 100644 index ff4de3d9a5..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_others.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows -// +build !appengine - -package isatty - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. This is also always false on this environment. -func IsCygwinTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_solaris.go b/vendor/github.com/mattn/go-isatty/isatty_solaris.go deleted file mode 100644 index 1f0c6bf53d..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build solaris -// +build !appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func IsTerminal(fd uintptr) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) - return err == nil -} diff --git a/vendor/github.com/mattn/go-isatty/isatty_windows.go b/vendor/github.com/mattn/go-isatty/isatty_windows.go deleted file mode 100644 index af51cbcaa4..0000000000 --- a/vendor/github.com/mattn/go-isatty/isatty_windows.go +++ /dev/null @@ -1,94 +0,0 @@ -// +build windows -// +build !appengine - -package isatty - -import ( - "strings" - "syscall" - "unicode/utf16" - "unsafe" -) - -const ( - fileNameInfo uintptr = 2 - fileTypePipe = 3 -) - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx") - procGetFileType = kernel32.NewProc("GetFileType") -) - -func init() { - // Check if GetFileInformationByHandleEx is available. - if procGetFileInformationByHandleEx.Find() != nil { - procGetFileInformationByHandleEx = nil - } -} - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} - -// Check pipe name is used for cygwin/msys2 pty. -// Cygwin/MSYS2 PTY has a name like: -// \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master -func isCygwinPipeName(name string) bool { - token := strings.Split(name, "-") - if len(token) < 5 { - return false - } - - if token[0] != `\msys` && token[0] != `\cygwin` { - return false - } - - if token[1] == "" { - return false - } - - if !strings.HasPrefix(token[2], "pty") { - return false - } - - if token[3] != `from` && token[3] != `to` { - return false - } - - if token[4] != "master" { - return false - } - - return true -} - -// IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2 -// terminal. -func IsCygwinTerminal(fd uintptr) bool { - if procGetFileInformationByHandleEx == nil { - return false - } - - // Cygwin/msys's pty is a pipe. - ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0) - if ft != fileTypePipe || e != 0 { - return false - } - - var buf [2 + syscall.MAX_PATH]uint16 - r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), - 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)), - uintptr(len(buf)*2), 0, 0) - if r == 0 || e != 0 { - return false - } - - l := *(*uint32)(unsafe.Pointer(&buf)) - return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2]))) -} diff --git a/vendor/github.com/mitchellh/mapstructure/LICENSE b/vendor/github.com/mitchellh/mapstructure/LICENSE deleted file mode 100644 index f9c841a51e..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Mitchell Hashimoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/github.com/mitchellh/mapstructure/README.md b/vendor/github.com/mitchellh/mapstructure/README.md deleted file mode 100644 index 659d6885fc..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# mapstructure - -mapstructure is a Go library for decoding generic map values to structures -and vice versa, while providing helpful error handling. - -This library is most useful when decoding values from some data stream (JSON, -Gob, etc.) where you don't _quite_ know the structure of the underlying data -until you read a part of it. You can therefore read a `map[string]interface{}` -and use this library to decode it into the proper underlying native Go -structure. - -## Installation - -Standard `go get`: - -``` -$ go get github.com/mitchellh/mapstructure -``` - -## Usage & Example - -For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure). - -The `Decode` function has examples associated with it there. - -## But Why?! - -Go offers fantastic standard libraries for decoding formats such as JSON. -The standard method is to have a struct pre-created, and populate that struct -from the bytes of the encoded format. This is great, but the problem is if -you have configuration or an encoding that changes slightly depending on -specific fields. For example, consider this JSON: - -```json -{ - "type": "person", - "name": "Mitchell" -} -``` - -Perhaps we can't populate a specific structure without first reading -the "type" field from the JSON. We could always do two passes over the -decoding of the JSON (reading the "type" first, and the rest later). -However, it is much simpler to just decode this into a `map[string]interface{}` -structure, read the "type" key, then use something like this library -to decode it into the proper structure. diff --git a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go b/vendor/github.com/mitchellh/mapstructure/decode_hooks.go deleted file mode 100644 index afcfd5eed6..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/decode_hooks.go +++ /dev/null @@ -1,152 +0,0 @@ -package mapstructure - -import ( - "errors" - "reflect" - "strconv" - "strings" - "time" -) - -// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns -// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. -func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { - // Create variables here so we can reference them with the reflect pkg - var f1 DecodeHookFuncType - var f2 DecodeHookFuncKind - - // Fill in the variables into this interface and the rest is done - // automatically using the reflect package. - potential := []interface{}{f1, f2} - - v := reflect.ValueOf(h) - vt := v.Type() - for _, raw := range potential { - pt := reflect.ValueOf(raw).Type() - if vt.ConvertibleTo(pt) { - return v.Convert(pt).Interface() - } - } - - return nil -} - -// DecodeHookExec executes the given decode hook. This should be used -// since it'll naturally degrade to the older backwards compatible DecodeHookFunc -// that took reflect.Kind instead of reflect.Type. -func DecodeHookExec( - raw DecodeHookFunc, - from reflect.Type, to reflect.Type, - data interface{}) (interface{}, error) { - switch f := typedDecodeHook(raw).(type) { - case DecodeHookFuncType: - return f(from, to, data) - case DecodeHookFuncKind: - return f(from.Kind(), to.Kind(), data) - default: - return nil, errors.New("invalid decode hook signature") - } -} - -// ComposeDecodeHookFunc creates a single DecodeHookFunc that -// automatically composes multiple DecodeHookFuncs. -// -// The composed funcs are called in order, with the result of the -// previous transformation. -func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - var err error - for _, f1 := range fs { - data, err = DecodeHookExec(f1, f, t, data) - if err != nil { - return nil, err - } - - // Modify the from kind to be correct with the new data - f = nil - if val := reflect.ValueOf(data); val.IsValid() { - f = val.Type() - } - } - - return data, nil - } -} - -// StringToSliceHookFunc returns a DecodeHookFunc that converts -// string to []string by splitting on the given sep. -func StringToSliceHookFunc(sep string) DecodeHookFunc { - return func( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - if f != reflect.String || t != reflect.Slice { - return data, nil - } - - raw := data.(string) - if raw == "" { - return []string{}, nil - } - - return strings.Split(raw, sep), nil - } -} - -// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts -// strings to time.Duration. -func StringToTimeDurationHookFunc() DecodeHookFunc { - return func( - f reflect.Type, - t reflect.Type, - data interface{}) (interface{}, error) { - if f.Kind() != reflect.String { - return data, nil - } - if t != reflect.TypeOf(time.Duration(5)) { - return data, nil - } - - // Convert it by parsing - return time.ParseDuration(data.(string)) - } -} - -// WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to -// the decoder. -// -// Note that this is significantly different from the WeaklyTypedInput option -// of the DecoderConfig. -func WeaklyTypedHook( - f reflect.Kind, - t reflect.Kind, - data interface{}) (interface{}, error) { - dataVal := reflect.ValueOf(data) - switch t { - case reflect.String: - switch f { - case reflect.Bool: - if dataVal.Bool() { - return "1", nil - } - return "0", nil - case reflect.Float32: - return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil - case reflect.Int: - return strconv.FormatInt(dataVal.Int(), 10), nil - case reflect.Slice: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - if elemKind == reflect.Uint8 { - return string(dataVal.Interface().([]uint8)), nil - } - case reflect.Uint: - return strconv.FormatUint(dataVal.Uint(), 10), nil - } - } - - return data, nil -} diff --git a/vendor/github.com/mitchellh/mapstructure/error.go b/vendor/github.com/mitchellh/mapstructure/error.go deleted file mode 100644 index 47a99e5af3..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/error.go +++ /dev/null @@ -1,50 +0,0 @@ -package mapstructure - -import ( - "errors" - "fmt" - "sort" - "strings" -) - -// Error implements the error interface and can represents multiple -// errors that occur in the course of a single decode. -type Error struct { - Errors []string -} - -func (e *Error) Error() string { - points := make([]string, len(e.Errors)) - for i, err := range e.Errors { - points[i] = fmt.Sprintf("* %s", err) - } - - sort.Strings(points) - return fmt.Sprintf( - "%d error(s) decoding:\n\n%s", - len(e.Errors), strings.Join(points, "\n")) -} - -// WrappedErrors implements the errwrap.Wrapper interface to make this -// return value more useful with the errwrap and go-multierror libraries. -func (e *Error) WrappedErrors() []error { - if e == nil { - return nil - } - - result := make([]error, len(e.Errors)) - for i, e := range e.Errors { - result[i] = errors.New(e) - } - - return result -} - -func appendErrors(errors []string, err error) []string { - switch e := err.(type) { - case *Error: - return append(errors, e.Errors...) - default: - return append(errors, e.Error()) - } -} diff --git a/vendor/github.com/mitchellh/mapstructure/mapstructure.go b/vendor/github.com/mitchellh/mapstructure/mapstructure.go deleted file mode 100644 index 6ec5c33357..0000000000 --- a/vendor/github.com/mitchellh/mapstructure/mapstructure.go +++ /dev/null @@ -1,828 +0,0 @@ -// Package mapstructure exposes functionality to convert an arbitrary -// map[string]interface{} into a native Go structure. -// -// The Go structure can be arbitrarily complex, containing slices, -// other structs, etc. and the decoder will properly decode nested -// maps and so on into the proper structures in the native Go struct. -// See the examples to see what the decoder is capable of. -package mapstructure - -import ( - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" - "strconv" - "strings" -) - -// DecodeHookFunc is the callback function that can be used for -// data transformations. See "DecodeHook" in the DecoderConfig -// struct. -// -// The type should be DecodeHookFuncType or DecodeHookFuncKind. -// Either is accepted. Types are a superset of Kinds (Types can return -// Kinds) and are generally a richer thing to use, but Kinds are simpler -// if you only need those. -// -// The reason DecodeHookFunc is multi-typed is for backwards compatibility: -// we started with Kinds and then realized Types were the better solution, -// but have a promise to not break backwards compat so we now support -// both. -type DecodeHookFunc interface{} - -// DecodeHookFuncType is a DecodeHookFunc which has complete information about -// the source and target types. -type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) - -// DecodeHookFuncKind is a DecodeHookFunc which knows only the Kinds of the -// source and target types. -type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) - -// DecoderConfig is the configuration that is used to create a new decoder -// and allows customization of various aspects of decoding. -type DecoderConfig struct { - // DecodeHook, if set, will be called before any decoding and any - // type conversion (if WeaklyTypedInput is on). This lets you modify - // the values before they're set down onto the resulting struct. - // - // If an error is returned, the entire decode will fail with that - // error. - DecodeHook DecodeHookFunc - - // If ErrorUnused is true, then it is an error for there to exist - // keys in the original map that were unused in the decoding process - // (extra keys). - ErrorUnused bool - - // ZeroFields, if set to true, will zero fields before writing them. - // For example, a map will be emptied before decoded values are put in - // it. If this is false, a map will be merged. - ZeroFields bool - - // If WeaklyTypedInput is true, the decoder will make the following - // "weak" conversions: - // - // - bools to string (true = "1", false = "0") - // - numbers to string (base 10) - // - bools to int/uint (true = 1, false = 0) - // - strings to int/uint (base implied by prefix) - // - int to bool (true if value != 0) - // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, - // FALSE, false, False. Anything else is an error) - // - empty array = empty map and vice versa - // - negative numbers to overflowed uint values (base 10) - // - slice of maps to a merged map - // - single values are converted to slices if required. Each - // element is weakly decoded. For example: "4" can become []int{4} - // if the target type is an int slice. - // - WeaklyTypedInput bool - - // Metadata is the struct that will contain extra metadata about - // the decoding. If this is nil, then no metadata will be tracked. - Metadata *Metadata - - // Result is a pointer to the struct that will contain the decoded - // value. - Result interface{} - - // The tag name that mapstructure reads for field names. This - // defaults to "mapstructure" - TagName string -} - -// A Decoder takes a raw interface value and turns it into structured -// data, keeping track of rich error information along the way in case -// anything goes wrong. Unlike the basic top-level Decode method, you can -// more finely control how the Decoder behaves using the DecoderConfig -// structure. The top-level Decode method is just a convenience that sets -// up the most basic Decoder. -type Decoder struct { - config *DecoderConfig -} - -// Metadata contains information about decoding a structure that -// is tedious or difficult to get otherwise. -type Metadata struct { - // Keys are the keys of the structure which were successfully decoded - Keys []string - - // Unused is a slice of keys that were found in the raw value but - // weren't decoded since there was no matching field in the result interface - Unused []string -} - -// Decode takes a map and uses reflection to convert it into the -// given Go native structure. val must be a pointer to a struct. -func Decode(m interface{}, rawVal interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: rawVal, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(m) -} - -// WeakDecode is the same as Decode but is shorthand to enable -// WeaklyTypedInput. See DecoderConfig for more info. -func WeakDecode(input, output interface{}) error { - config := &DecoderConfig{ - Metadata: nil, - Result: output, - WeaklyTypedInput: true, - } - - decoder, err := NewDecoder(config) - if err != nil { - return err - } - - return decoder.Decode(input) -} - -// NewDecoder returns a new decoder for the given configuration. Once -// a decoder has been returned, the same configuration must not be used -// again. -func NewDecoder(config *DecoderConfig) (*Decoder, error) { - val := reflect.ValueOf(config.Result) - if val.Kind() != reflect.Ptr { - return nil, errors.New("result must be a pointer") - } - - val = val.Elem() - if !val.CanAddr() { - return nil, errors.New("result must be addressable (a pointer)") - } - - if config.Metadata != nil { - if config.Metadata.Keys == nil { - config.Metadata.Keys = make([]string, 0) - } - - if config.Metadata.Unused == nil { - config.Metadata.Unused = make([]string, 0) - } - } - - if config.TagName == "" { - config.TagName = "mapstructure" - } - - result := &Decoder{ - config: config, - } - - return result, nil -} - -// Decode decodes the given raw interface to the target pointer specified -// by the configuration. -func (d *Decoder) Decode(raw interface{}) error { - return d.decode("", raw, reflect.ValueOf(d.config.Result).Elem()) -} - -// Decodes an unknown data type into a specific reflection value. -func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { - if data == nil { - // If the data is nil, then we don't set anything. - return nil - } - - dataVal := reflect.ValueOf(data) - if !dataVal.IsValid() { - // If the data value is invalid, then we just set the value - // to be the zero value. - val.Set(reflect.Zero(val.Type())) - return nil - } - - if d.config.DecodeHook != nil { - // We have a DecodeHook, so let's pre-process the data. - var err error - data, err = DecodeHookExec( - d.config.DecodeHook, - dataVal.Type(), val.Type(), data) - if err != nil { - return fmt.Errorf("error decoding '%s': %s", name, err) - } - } - - var err error - dataKind := getKind(val) - switch dataKind { - case reflect.Bool: - err = d.decodeBool(name, data, val) - case reflect.Interface: - err = d.decodeBasic(name, data, val) - case reflect.String: - err = d.decodeString(name, data, val) - case reflect.Int: - err = d.decodeInt(name, data, val) - case reflect.Uint: - err = d.decodeUint(name, data, val) - case reflect.Float32: - err = d.decodeFloat(name, data, val) - case reflect.Struct: - err = d.decodeStruct(name, data, val) - case reflect.Map: - err = d.decodeMap(name, data, val) - case reflect.Ptr: - err = d.decodePtr(name, data, val) - case reflect.Slice: - err = d.decodeSlice(name, data, val) - case reflect.Func: - err = d.decodeFunc(name, data, val) - default: - // If we reached this point then we weren't able to decode it - return fmt.Errorf("%s: unsupported type: %s", name, dataKind) - } - - // If we reached here, then we successfully decoded SOMETHING, so - // mark the key as used if we're tracking metadata. - if d.config.Metadata != nil && name != "" { - d.config.Metadata.Keys = append(d.config.Metadata.Keys, name) - } - - return err -} - -// This decodes a basic type (bool, int, string, etc.) and sets the -// value to "data" of that type. -func (d *Decoder) decodeBasic(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - if !dataVal.IsValid() { - dataVal = reflect.Zero(val.Type()) - } - - dataValType := dataVal.Type() - if !dataValType.AssignableTo(val.Type()) { - return fmt.Errorf( - "'%s' expected type '%s', got '%s'", - name, val.Type(), dataValType) - } - - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - converted := true - switch { - case dataKind == reflect.String: - val.SetString(dataVal.String()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetString("1") - } else { - val.SetString("0") - } - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatInt(dataVal.Int(), 10)) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatUint(dataVal.Uint(), 10)) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetString(strconv.FormatFloat(dataVal.Float(), 'f', -1, 64)) - case dataKind == reflect.Slice && d.config.WeaklyTypedInput: - dataType := dataVal.Type() - elemKind := dataType.Elem().Kind() - switch { - case elemKind == reflect.Uint8: - val.SetString(string(dataVal.Interface().([]uint8))) - default: - converted = false - } - default: - converted = false - } - - if !converted { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetInt(dataVal.Int()) - case dataKind == reflect.Uint: - val.SetInt(int64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetInt(int64(dataVal.Float())) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetInt(1) - } else { - val.SetInt(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetInt(i) - } else { - return fmt.Errorf("cannot parse '%s' as int: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Int64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetInt(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Int: - i := dataVal.Int() - if i < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %d overflows uint", - name, i) - } - val.SetUint(uint64(i)) - case dataKind == reflect.Uint: - val.SetUint(dataVal.Uint()) - case dataKind == reflect.Float32: - f := dataVal.Float() - if f < 0 && !d.config.WeaklyTypedInput { - return fmt.Errorf("cannot parse '%s', %f overflows uint", - name, f) - } - val.SetUint(uint64(f)) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetUint(1) - } else { - val.SetUint(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - i, err := strconv.ParseUint(dataVal.String(), 0, val.Type().Bits()) - if err == nil { - val.SetUint(i) - } else { - return fmt.Errorf("cannot parse '%s' as uint: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - - switch { - case dataKind == reflect.Bool: - val.SetBool(dataVal.Bool()) - case dataKind == reflect.Int && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Int() != 0) - case dataKind == reflect.Uint && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Uint() != 0) - case dataKind == reflect.Float32 && d.config.WeaklyTypedInput: - val.SetBool(dataVal.Float() != 0) - case dataKind == reflect.String && d.config.WeaklyTypedInput: - b, err := strconv.ParseBool(dataVal.String()) - if err == nil { - val.SetBool(b) - } else if dataVal.String() == "" { - val.SetBool(false) - } else { - return fmt.Errorf("cannot parse '%s' as bool: %s", name, err) - } - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeFloat(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.ValueOf(data) - dataKind := getKind(dataVal) - dataType := dataVal.Type() - - switch { - case dataKind == reflect.Int: - val.SetFloat(float64(dataVal.Int())) - case dataKind == reflect.Uint: - val.SetFloat(float64(dataVal.Uint())) - case dataKind == reflect.Float32: - val.SetFloat(dataVal.Float()) - case dataKind == reflect.Bool && d.config.WeaklyTypedInput: - if dataVal.Bool() { - val.SetFloat(1) - } else { - val.SetFloat(0) - } - case dataKind == reflect.String && d.config.WeaklyTypedInput: - f, err := strconv.ParseFloat(dataVal.String(), val.Type().Bits()) - if err == nil { - val.SetFloat(f) - } else { - return fmt.Errorf("cannot parse '%s' as float: %s", name, err) - } - case dataType.PkgPath() == "encoding/json" && dataType.Name() == "Number": - jn := data.(json.Number) - i, err := jn.Float64() - if err != nil { - return fmt.Errorf( - "error decoding json.Number into %s: %s", name, err) - } - val.SetFloat(i) - default: - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - - return nil -} - -func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { - valType := val.Type() - valKeyType := valType.Key() - valElemType := valType.Elem() - - // By default we overwrite keys in the current map - valMap := val - - // If the map is nil or we're purposely zeroing fields, make a new map - if valMap.IsNil() || d.config.ZeroFields { - // Make a new map to hold our result - mapType := reflect.MapOf(valKeyType, valElemType) - valMap = reflect.MakeMap(mapType) - } - - // Check input type - dataVal := reflect.Indirect(reflect.ValueOf(data)) - if dataVal.Kind() != reflect.Map { - // In weak mode, we accept a slice of maps as an input... - if d.config.WeaklyTypedInput { - switch dataVal.Kind() { - case reflect.Array, reflect.Slice: - // Special case for BC reasons (covered by tests) - if dataVal.Len() == 0 { - val.Set(valMap) - return nil - } - - for i := 0; i < dataVal.Len(); i++ { - err := d.decode( - fmt.Sprintf("%s[%d]", name, i), - dataVal.Index(i).Interface(), val) - if err != nil { - return err - } - } - - return nil - } - } - - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) - } - - // Accumulate errors - errors := make([]string, 0) - - for _, k := range dataVal.MapKeys() { - fieldName := fmt.Sprintf("%s[%s]", name, k) - - // First decode the key into the proper type - currentKey := reflect.Indirect(reflect.New(valKeyType)) - if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { - errors = appendErrors(errors, err) - continue - } - - // Next decode the data into the proper type - v := dataVal.MapIndex(k).Interface() - currentVal := reflect.Indirect(reflect.New(valElemType)) - if err := d.decode(fieldName, v, currentVal); err != nil { - errors = appendErrors(errors, err) - continue - } - - valMap.SetMapIndex(currentKey, currentVal) - } - - // Set the built up map to the value - val.Set(valMap) - - // If we had errors, return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodePtr(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - valType := val.Type() - valElemType := valType.Elem() - - realVal := val - if realVal.IsNil() || d.config.ZeroFields { - realVal = reflect.New(valElemType) - } - - if err := d.decode(name, data, reflect.Indirect(realVal)); err != nil { - return err - } - - val.Set(realVal) - return nil -} - -func (d *Decoder) decodeFunc(name string, data interface{}, val reflect.Value) error { - // Create an element of the concrete (non pointer) type and decode - // into that. Then set the value of the pointer to this type. - dataVal := reflect.Indirect(reflect.ValueOf(data)) - if val.Type() != dataVal.Type() { - return fmt.Errorf( - "'%s' expected type '%s', got unconvertible type '%s'", - name, val.Type(), dataVal.Type()) - } - val.Set(dataVal) - return nil -} - -func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - dataValKind := dataVal.Kind() - valType := val.Type() - valElemType := valType.Elem() - sliceType := reflect.SliceOf(valElemType) - - valSlice := val - if valSlice.IsNil() || d.config.ZeroFields { - // Check input type - if dataValKind != reflect.Array && dataValKind != reflect.Slice { - if d.config.WeaklyTypedInput { - switch { - // Empty maps turn into empty slices - case dataValKind == reflect.Map: - if dataVal.Len() == 0 { - val.Set(reflect.MakeSlice(sliceType, 0, 0)) - return nil - } - - // All other types we try to convert to the slice type - // and "lift" it into it. i.e. a string becomes a string slice. - default: - // Just re-try this function with data as a slice. - return d.decodeSlice(name, []interface{}{data}, val) - } - } - - return fmt.Errorf( - "'%s': source data must be an array or slice, got %s", name, dataValKind) - - } - - // Make a new slice to hold our result, same size as the original data. - valSlice = reflect.MakeSlice(sliceType, dataVal.Len(), dataVal.Len()) - } - - // Accumulate any errors - errors := make([]string, 0) - - for i := 0; i < dataVal.Len(); i++ { - currentData := dataVal.Index(i).Interface() - for valSlice.Len() <= i { - valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) - } - currentField := valSlice.Index(i) - - fieldName := fmt.Sprintf("%s[%d]", name, i) - if err := d.decode(fieldName, currentData, currentField); err != nil { - errors = appendErrors(errors, err) - } - } - - // Finally, set the value to the slice we built up - val.Set(valSlice) - - // If there were errors, we return those - if len(errors) > 0 { - return &Error{errors} - } - - return nil -} - -func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { - dataVal := reflect.Indirect(reflect.ValueOf(data)) - - // If the type of the value to write to and the data match directly, - // then we just set it directly instead of recursing into the structure. - if dataVal.Type() == val.Type() { - val.Set(dataVal) - return nil - } - - dataValKind := dataVal.Kind() - if dataValKind != reflect.Map { - return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind) - } - - dataValType := dataVal.Type() - if kind := dataValType.Key().Kind(); kind != reflect.String && kind != reflect.Interface { - return fmt.Errorf( - "'%s' needs a map with string keys, has '%s' keys", - name, dataValType.Key().Kind()) - } - - dataValKeys := make(map[reflect.Value]struct{}) - dataValKeysUnused := make(map[interface{}]struct{}) - for _, dataValKey := range dataVal.MapKeys() { - dataValKeys[dataValKey] = struct{}{} - dataValKeysUnused[dataValKey.Interface()] = struct{}{} - } - - errors := make([]string, 0) - - // This slice will keep track of all the structs we'll be decoding. - // There can be more than one struct if there are embedded structs - // that are squashed. - structs := make([]reflect.Value, 1, 5) - structs[0] = val - - // Compile the list of all the fields that we're going to be decoding - // from all the structs. - fields := make(map[*reflect.StructField]reflect.Value) - for len(structs) > 0 { - structVal := structs[0] - structs = structs[1:] - - structType := structVal.Type() - - for i := 0; i < structType.NumField(); i++ { - fieldType := structType.Field(i) - fieldKind := fieldType.Type.Kind() - - // If "squash" is specified in the tag, we squash the field down. - squash := false - tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } - } - - if squash { - if fieldKind != reflect.Struct { - errors = appendErrors(errors, - fmt.Errorf("%s: unsupported type for squash: %s", fieldType.Name, fieldKind)) - } else { - structs = append(structs, val.FieldByName(fieldType.Name)) - } - continue - } - - // Normal struct field, store it away - fields[&fieldType] = structVal.Field(i) - } - } - - for fieldType, field := range fields { - fieldName := fieldType.Name - - tagValue := fieldType.Tag.Get(d.config.TagName) - tagValue = strings.SplitN(tagValue, ",", 2)[0] - if tagValue != "" { - fieldName = tagValue - } - - rawMapKey := reflect.ValueOf(fieldName) - rawMapVal := dataVal.MapIndex(rawMapKey) - if !rawMapVal.IsValid() { - // Do a slower search by iterating over each key and - // doing case-insensitive search. - for dataValKey := range dataValKeys { - mK, ok := dataValKey.Interface().(string) - if !ok { - // Not a string key - continue - } - - if strings.EqualFold(mK, fieldName) { - rawMapKey = dataValKey - rawMapVal = dataVal.MapIndex(dataValKey) - break - } - } - - if !rawMapVal.IsValid() { - // There was no matching key in the map for the value in - // the struct. Just ignore. - continue - } - } - - // Delete the key we're using from the unused map so we stop tracking - delete(dataValKeysUnused, rawMapKey.Interface()) - - if !field.IsValid() { - // This should never happen - panic("field is not valid") - } - - // If we can't set the field, then it is unexported or something, - // and we just continue onwards. - if !field.CanSet() { - continue - } - - // If the name is empty string, then we're at the root, and we - // don't dot-join the fields. - if name != "" { - fieldName = fmt.Sprintf("%s.%s", name, fieldName) - } - - if err := d.decode(fieldName, rawMapVal.Interface(), field); err != nil { - errors = appendErrors(errors, err) - } - } - - if d.config.ErrorUnused && len(dataValKeysUnused) > 0 { - keys := make([]string, 0, len(dataValKeysUnused)) - for rawKey := range dataValKeysUnused { - keys = append(keys, rawKey.(string)) - } - sort.Strings(keys) - - err := fmt.Errorf("'%s' has invalid keys: %s", name, strings.Join(keys, ", ")) - errors = appendErrors(errors, err) - } - - if len(errors) > 0 { - return &Error{errors} - } - - // Add the unused keys to the list of unused keys if we're tracking metadata - if d.config.Metadata != nil { - for rawKey := range dataValKeysUnused { - key := rawKey.(string) - if name != "" { - key = fmt.Sprintf("%s.%s", name, key) - } - - d.config.Metadata.Unused = append(d.config.Metadata.Unused, key) - } - } - - return nil -} - -func getKind(val reflect.Value) reflect.Kind { - kind := val.Kind() - - switch { - case kind >= reflect.Int && kind <= reflect.Int64: - return reflect.Int - case kind >= reflect.Uint && kind <= reflect.Uint64: - return reflect.Uint - case kind >= reflect.Float32 && kind <= reflect.Float64: - return reflect.Float32 - default: - return kind - } -} diff --git a/vendor/github.com/onsi/ginkgo/CHANGELOG.md b/vendor/github.com/onsi/ginkgo/CHANGELOG.md deleted file mode 100644 index 6a4ab3f14b..0000000000 --- a/vendor/github.com/onsi/ginkgo/CHANGELOG.md +++ /dev/null @@ -1,156 +0,0 @@ -## HEAD - -- When using custom reporters register the custom reporters *before* the default reporter. This allows users to see the output of any print statements in their customer reporters. [#365] - -## 1.4.0 7/16/2017 - -- `ginkgo` now provides a hint if you accidentally forget to run `ginkgo bootstrap` to generate a `*_suite_test.go` file that actually invokes the Ginkgo test runner. [#345](https://github.com/onsi/ginkgo/pull/345) -- thanks to improvements in `go test -c` `ginkgo` no longer needs to fix Go's compilation output to ensure compilation errors are expressed relative to the CWD. [#357] -- `ginkgo watch -watchRegExp=...` allows you to specify a custom regular expression to watch. Only files matching the regular expression are watched for changes (the default is `\.go$`) [#356] -- `ginkgo` now always emits compilation output. Previously, only failed compilation output was printed out. [#277] -- `ginkgo -requireSuite` now fails the test run if there are `*_test.go` files but `go test` fails to detect any tests. Typically this means you forgot to run `ginkgo bootstrap` to generate a suite file. [#344] -- `ginkgo -timeout=DURATION` allows you to adjust the timeout for the entire test suite (default is 24 hours) [#248] - -## 1.3.0 3/28/2017 - -Improvements: - -- Significantly improved parallel test distribution. Now instead of pre-sharding test cases across workers (which can result in idle workers and poor test performance) Ginkgo uses a shared queue to keep all workers busy until all tests are complete. This improves test-time performance and consistency. -- `Skip(message)` can be used to skip the current test. -- Added `extensions/table` - a Ginkgo DSL for [Table Driven Tests](http://onsi.github.io/ginkgo/#table-driven-tests) -- Add `GinkgoRandomSeed()` - shorthand for `config.GinkgoConfig.RandomSeed` -- Support for retrying flaky tests with `--flakeAttempts` -- `ginkgo ./...` now recurses as you'd expect -- Added `Specify` a synonym for `It` -- Support colorise on Windows -- Broader support for various go compilation flags in the `ginkgo` CLI - -Bug Fixes: - -- Ginkgo tests now fail when you `panic(nil)` (#167) - -## 1.2.0 5/31/2015 - -Improvements - -- `ginkgo -coverpkg` calls down to `go test -coverpkg` (#160) -- `ginkgo -afterSuiteHook COMMAND` invokes the passed-in `COMMAND` after a test suite completes (#152) -- Relaxed requirement for Go 1.4+. `ginkgo` now works with Go v1.3+ (#166) - -## 1.2.0-beta - -Ginkgo now requires Go 1.4+ - -Improvements: - -- Call reporters in reverse order when announcing spec completion -- allows custom reporters to emit output before the default reporter does. -- Improved focus behavior. Now, this: - - ```golang - FDescribe("Some describe", func() { - It("A", func() {}) - - FIt("B", func() {}) - }) - ``` - - will run `B` but *not* `A`. This tends to be a common usage pattern when in the thick of writing and debugging tests. -- When `SIGINT` is received, Ginkgo will emit the contents of the `GinkgoWriter` before running the `AfterSuite`. Useful for debugging stuck tests. -- When `--progress` is set, Ginkgo will write test progress (in particular, Ginkgo will say when it is about to run a BeforeEach, AfterEach, It, etc...) to the `GinkgoWriter`. This is useful for debugging stuck tests and tests that generate many logs. -- Improved output when an error occurs in a setup or teardown block. -- When `--dryRun` is set, Ginkgo will walk the spec tree and emit to its reporter *without* actually running anything. Best paired with `-v` to understand which specs will run in which order. -- Add `By` to help document long `It`s. `By` simply writes to the `GinkgoWriter`. -- Add support for precompiled tests: - - `ginkgo build ` will now compile the package, producing a file named `package.test` - - The compiled `package.test` file can be run directly. This runs the tests in series. - - To run precompiled tests in parallel, you can run: `ginkgo -p package.test` -- Support `bootstrap`ping and `generate`ing [Agouti](http://agouti.org) specs. -- `ginkgo generate` and `ginkgo bootstrap` now honor the package name already defined in a given directory -- The `ginkgo` CLI ignores `SIGQUIT`. Prevents its stack dump from interlacing with the underlying test suite's stack dump. -- The `ginkgo` CLI now compiles tests into a temporary directory instead of the package directory. This necessitates upgrading to Go v1.4+. -- `ginkgo -notify` now works on Linux - -Bug Fixes: - -- If --skipPackages is used and all packages are skipped, Ginkgo should exit 0. -- Fix tempfile leak when running in parallel -- Fix incorrect failure message when a panic occurs during a parallel test run -- Fixed an issue where a pending test within a focused context (or a focused test within a pending context) would skip all other tests. -- Be more consistent about handling SIGTERM as well as SIGINT -- When interupted while concurrently compiling test suites in the background, Ginkgo now cleans up the compiled artifacts. -- Fixed a long standing bug where `ginkgo -p` would hang if a process spawned by one of the Ginkgo parallel nodes does not exit. (Hooray!) - -## 1.1.0 (8/2/2014) - -No changes, just dropping the beta. - -## 1.1.0-beta (7/22/2014) -New Features: - -- `ginkgo watch` now monitors packages *and their dependencies* for changes. The depth of the dependency tree can be modified with the `-depth` flag. -- Test suites with a programmatic focus (`FIt`, `FDescribe`, etc...) exit with non-zero status code, even when they pass. This allows CI systems to detect accidental commits of focused test suites. -- `ginkgo -p` runs the testsuite in parallel with an auto-detected number of nodes. -- `ginkgo -tags=TAG_LIST` passes a list of tags down to the `go build` command. -- `ginkgo --failFast` aborts the test suite after the first failure. -- `ginkgo generate file_1 file_2` can take multiple file arguments. -- Ginkgo now summarizes any spec failures that occured at the end of the test run. -- `ginkgo --randomizeSuites` will run tests *suites* in random order using the generated/passed-in seed. - -Improvements: - -- `ginkgo -skipPackage` now takes a comma-separated list of strings. If the *relative path* to a package matches one of the entries in the comma-separated list, that package is skipped. -- `ginkgo --untilItFails` no longer recompiles between attempts. -- Ginkgo now panics when a runnable node (`It`, `BeforeEach`, `JustBeforeEach`, `AfterEach`, `Measure`) is nested within another runnable node. This is always a mistake. Any test suites that panic because of this change should be fixed. - -Bug Fixes: - -- `ginkgo boostrap` and `ginkgo generate` no longer fail when dealing with `hyphen-separated-packages`. -- parallel specs are now better distributed across nodes - fixed a crashing bug where (for example) distributing 11 tests across 7 nodes would panic - -## 1.0.0 (5/24/2014) -New Features: - -- Add `GinkgoParallelNode()` - shorthand for `config.GinkgoConfig.ParallelNode` - -Improvements: - -- When compilation fails, the compilation output is rewritten to present a correct *relative* path. Allows ⌘-clicking in iTerm open the file in your text editor. -- `--untilItFails` and `ginkgo watch` now generate new random seeds between test runs, unless a particular random seed is specified. - -Bug Fixes: - -- `-cover` now generates a correctly combined coverprofile when running with in parallel with multiple `-node`s. -- Print out the contents of the `GinkgoWriter` when `BeforeSuite` or `AfterSuite` fail. -- Fix all remaining race conditions in Ginkgo's test suite. - -## 1.0.0-beta (4/14/2014) -Breaking changes: - -- `thirdparty/gomocktestreporter` is gone. Use `GinkgoT()` instead -- Modified the Reporter interface -- `watch` is now a subcommand, not a flag. - -DSL changes: - -- `BeforeSuite` and `AfterSuite` for setting up and tearing down test suites. -- `AfterSuite` is triggered on interrupt (`^C`) as well as exit. -- `SynchronizedBeforeSuite` and `SynchronizedAfterSuite` for setting up and tearing down singleton resources across parallel nodes. - -CLI changes: - -- `watch` is now a subcommand, not a flag -- `--nodot` flag can be passed to `ginkgo generate` and `ginkgo bootstrap` to avoid dot imports. This explicitly imports all exported identifiers in Ginkgo and Gomega. Refreshing this list can be done by running `ginkgo nodot` -- Additional arguments can be passed to specs. Pass them after the `--` separator -- `--skipPackage` flag takes a regexp and ignores any packages with package names passing said regexp. -- `--trace` flag prints out full stack traces when errors occur, not just the line at which the error occurs. - -Misc: - -- Start using semantic versioning -- Start maintaining changelog - -Major refactor: - -- Pull out Ginkgo's internal to `internal` -- Rename `example` everywhere to `spec` -- Much more! diff --git a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md b/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md deleted file mode 100644 index bc0c54fe2b..0000000000 --- a/vendor/github.com/onsi/ginkgo/CONTRIBUTING.md +++ /dev/null @@ -1,12 +0,0 @@ -# Contributing to Ginkgo - -Your contributions to Ginkgo are essential for its long-term maintenance and improvement. To make a contribution: - -- Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code! -- Ensure adequate test coverage: - - If you're adding functionality to the Ginkgo library, make sure to add appropriate unit and/or integration tests (under the `integration` folder). - - If you're adding functionality to the Ginkgo CLI note that there are very few unit tests. Please add an integration test. - - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR -- Update the documentation. In addition to standard `godoc` comments Ginkgo has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. - -Thanks for supporting Ginkgo! \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/LICENSE b/vendor/github.com/onsi/ginkgo/LICENSE deleted file mode 100644 index 9415ee72c1..0000000000 --- a/vendor/github.com/onsi/ginkgo/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013-2014 Onsi Fakhouri - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/onsi/ginkgo/README.md b/vendor/github.com/onsi/ginkgo/README.md deleted file mode 100644 index 97e9cdc426..0000000000 --- a/vendor/github.com/onsi/ginkgo/README.md +++ /dev/null @@ -1,123 +0,0 @@ -![Ginkgo: A Golang BDD Testing Framework](http://onsi.github.io/ginkgo/images/ginkgo.png) - -[![Build Status](https://travis-ci.org/onsi/ginkgo.svg)](https://travis-ci.org/onsi/ginkgo) - -Jump to the [docs](http://onsi.github.io/ginkgo/) to learn more. To start rolling your Ginkgo tests *now* [keep reading](#set-me-up)! - -If you have a question, comment, bug report, feature request, etc. please open a GitHub issue. - -## Feature List - -- Ginkgo uses Go's `testing` package and can live alongside your existing `testing` tests. It's easy to [bootstrap](http://onsi.github.io/ginkgo/#bootstrapping-a-suite) and start writing your [first tests](http://onsi.github.io/ginkgo/#adding-specs-to-a-suite) - -- Structure your BDD-style tests expressively: - - Nestable [`Describe` and `Context` container blocks](http://onsi.github.io/ginkgo/#organizing-specs-with-containers-describe-and-context) - - [`BeforeEach` and `AfterEach` blocks](http://onsi.github.io/ginkgo/#extracting-common-setup-beforeeach) for setup and teardown - - [`It` blocks](http://onsi.github.io/ginkgo/#individual-specs-) that hold your assertions - - [`JustBeforeEach` blocks](http://onsi.github.io/ginkgo/#separating-creation-and-configuration-justbeforeeach) that separate creation from configuration (also known as the subject action pattern). - - [`BeforeSuite` and `AfterSuite` blocks](http://onsi.github.io/ginkgo/#global-setup-and-teardown-beforesuite-and-aftersuite) to prep for and cleanup after a suite. - -- A comprehensive test runner that lets you: - - Mark specs as [pending](http://onsi.github.io/ginkgo/#pending-specs) - - [Focus](http://onsi.github.io/ginkgo/#focused-specs) individual specs, and groups of specs, either programmatically or on the command line - - Run your tests in [random order](http://onsi.github.io/ginkgo/#spec-permutation), and then reuse random seeds to replicate the same order. - - Break up your test suite into parallel processes for straightforward [test parallelization](http://onsi.github.io/ginkgo/#parallel-specs) - -- `ginkgo`: a command line interface with plenty of handy command line arguments for [running your tests](http://onsi.github.io/ginkgo/#running-tests) and [generating](http://onsi.github.io/ginkgo/#generators) test files. Here are a few choice examples: - - `ginkgo -nodes=N` runs your tests in `N` parallel processes and print out coherent output in realtime - - `ginkgo -cover` runs your tests using Golang's code coverage tool - - `ginkgo convert` converts an XUnit-style `testing` package to a Ginkgo-style package - - `ginkgo -focus="REGEXP"` and `ginkgo -skip="REGEXP"` allow you to specify a subset of tests to run via regular expression - - `ginkgo -r` runs all tests suites under the current directory - - `ginkgo -v` prints out identifying information for each tests just before it runs - - And much more: run `ginkgo help` for details! - - The `ginkgo` CLI is convenient, but purely optional -- Ginkgo works just fine with `go test` - -- `ginkgo watch` [watches](https://onsi.github.io/ginkgo/#watching-for-changes) packages *and their dependencies* for changes, then reruns tests. Run tests immediately as you develop! - -- Built-in support for testing [asynchronicity](http://onsi.github.io/ginkgo/#asynchronous-tests) - -- Built-in support for [benchmarking](http://onsi.github.io/ginkgo/#benchmark-tests) your code. Control the number of benchmark samples as you gather runtimes and other, arbitrary, bits of numerical information about your code. - -- [Completions for Sublime Text](https://github.com/onsi/ginkgo-sublime-completions): just use [Package Control](https://sublime.wbond.net/) to install `Ginkgo Completions`. - -- [Completions for VSCode](https://github.com/onsi/vscode-ginkgo): just use VSCode's extension installer to install `vscode-ginkgo`. - -- Straightforward support for third-party testing libraries such as [Gomock](https://code.google.com/p/gomock/) and [Testify](https://github.com/stretchr/testify). Check out the [docs](http://onsi.github.io/ginkgo/#third-party-integrations) for details. - -- A modular architecture that lets you easily: - - Write [custom reporters](http://onsi.github.io/ginkgo/#writing-custom-reporters) (for example, Ginkgo comes with a [JUnit XML reporter](http://onsi.github.io/ginkgo/#generating-junit-xml-output) and a TeamCity reporter). - - [Adapt an existing matcher library (or write your own!)](http://onsi.github.io/ginkgo/#using-other-matcher-libraries) to work with Ginkgo - -## [Gomega](http://github.com/onsi/gomega): Ginkgo's Preferred Matcher Library - -Ginkgo is best paired with Gomega. Learn more about Gomega [here](http://onsi.github.io/gomega/) - -## [Agouti](http://github.com/sclevine/agouti): A Golang Acceptance Testing Framework - -Agouti allows you run WebDriver integration tests. Learn more about Agouti [here](http://agouti.org) - -## Set Me Up! - -You'll need Golang v1.3+ (Ubuntu users: you probably have Golang v1.0 -- you'll need to upgrade!) - -```bash - -go get github.com/onsi/ginkgo/ginkgo # installs the ginkgo CLI -go get github.com/onsi/gomega # fetches the matcher library - -cd path/to/package/you/want/to/test - -ginkgo bootstrap # set up a new ginkgo suite -ginkgo generate # will create a sample test file. edit this file and add your tests then... - -go test # to run your tests - -ginkgo # also runs your tests - -``` - -## I'm new to Go: What are my testing options? - -Of course, I heartily recommend [Ginkgo](https://github.com/onsi/ginkgo) and [Gomega](https://github.com/onsi/gomega). Both packages are seeing heavy, daily, production use on a number of projects and boast a mature and comprehensive feature-set. - -With that said, it's great to know what your options are :) - -### What Golang gives you out of the box - -Testing is a first class citizen in Golang, however Go's built-in testing primitives are somewhat limited: The [testing](http://golang.org/pkg/testing) package provides basic XUnit style tests and no assertion library. - -### Matcher libraries for Golang's XUnit style tests - -A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction: - -- [testify](https://github.com/stretchr/testify) -- [gocheck](http://labix.org/gocheck) - -You can also use Ginkgo's matcher library [Gomega](https://github.com/onsi/gomega) in [XUnit style tests](http://onsi.github.io/gomega/#using-gomega-with-golangs-xunitstyle-tests) - -### BDD style testing frameworks - -There are a handful of BDD-style testing frameworks written for Golang. Here are a few: - -- [Ginkgo](https://github.com/onsi/ginkgo) ;) -- [GoConvey](https://github.com/smartystreets/goconvey) -- [Goblin](https://github.com/franela/goblin) -- [Mao](https://github.com/azer/mao) -- [Zen](https://github.com/pranavraja/zen) - -Finally, @shageman has [put together](https://github.com/shageman/gotestit) a comprehensive comparison of golang testing libraries. - -Go explore! - -## License - -Ginkgo is MIT-Licensed - -## Contributing - -Since Ginkgo tests also internal packages, when you fork, you'll have to replace imports with your repository.
-Use `before_pr.sh` for that
-After you finished your changes and before you push your pull request, use `after_pr.sh` to revert those changes \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/before_pr.sh b/vendor/github.com/onsi/ginkgo/before_pr.sh deleted file mode 100755 index 3cf262f388..0000000000 --- a/vendor/github.com/onsi/ginkgo/before_pr.sh +++ /dev/null @@ -1,13 +0,0 @@ -# Take current path -path=$(pwd) - -# Split it -IFS='\/'; arrIN=($path); unset IFS; - -# Find directory before ginkgo -len=${#arrIN[@]} - -userDir=${arrIN[$len-2]} - -# Replace onsi with userdir -find . -type f -name '*.go' -exec sed -i '' s/github.com\\/onsi\\/ginkgo\\/internal/github.com\\/$userDir\\/ginkgo\\/internal/ {} + \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/config/config.go b/vendor/github.com/onsi/ginkgo/config/config.go deleted file mode 100644 index 60d5ea22e8..0000000000 --- a/vendor/github.com/onsi/ginkgo/config/config.go +++ /dev/null @@ -1,187 +0,0 @@ -/* -Ginkgo accepts a number of configuration options. - -These are documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli) - -You can also learn more via - - ginkgo help - -or (I kid you not): - - go test -asdf -*/ -package config - -import ( - "flag" - "time" - - "fmt" -) - -const VERSION = "1.4.0" - -type GinkgoConfigType struct { - RandomSeed int64 - RandomizeAllSpecs bool - RegexScansFilePath bool - FocusString string - SkipString string - SkipMeasurements bool - FailOnPending bool - FailFast bool - FlakeAttempts int - EmitSpecProgress bool - DryRun bool - - ParallelNode int - ParallelTotal int - SyncHost string - StreamHost string -} - -var GinkgoConfig = GinkgoConfigType{} - -type DefaultReporterConfigType struct { - NoColor bool - SlowSpecThreshold float64 - NoisyPendings bool - Succinct bool - Verbose bool - FullTrace bool -} - -var DefaultReporterConfig = DefaultReporterConfigType{} - -func processPrefix(prefix string) string { - if prefix != "" { - prefix = prefix + "." - } - return prefix -} - -func Flags(flagSet *flag.FlagSet, prefix string, includeParallelFlags bool) { - prefix = processPrefix(prefix) - flagSet.Int64Var(&(GinkgoConfig.RandomSeed), prefix+"seed", time.Now().Unix(), "The seed used to randomize the spec suite.") - flagSet.BoolVar(&(GinkgoConfig.RandomizeAllSpecs), prefix+"randomizeAllSpecs", false, "If set, ginkgo will randomize all specs together. By default, ginkgo only randomizes the top level Describe/Context groups.") - flagSet.BoolVar(&(GinkgoConfig.SkipMeasurements), prefix+"skipMeasurements", false, "If set, ginkgo will skip any measurement specs.") - flagSet.BoolVar(&(GinkgoConfig.FailOnPending), prefix+"failOnPending", false, "If set, ginkgo will mark the test suite as failed if any specs are pending.") - flagSet.BoolVar(&(GinkgoConfig.FailFast), prefix+"failFast", false, "If set, ginkgo will stop running a test suite after a failure occurs.") - - flagSet.BoolVar(&(GinkgoConfig.DryRun), prefix+"dryRun", false, "If set, ginkgo will walk the test hierarchy without actually running anything. Best paired with -v.") - - flagSet.StringVar(&(GinkgoConfig.FocusString), prefix+"focus", "", "If set, ginkgo will only run specs that match this regular expression.") - flagSet.StringVar(&(GinkgoConfig.SkipString), prefix+"skip", "", "If set, ginkgo will only run specs that do not match this regular expression.") - - flagSet.BoolVar(&(GinkgoConfig.RegexScansFilePath), prefix+"regexScansFilePath", false, "If set, ginkgo regex matching also will look at the file path (code location).") - - flagSet.IntVar(&(GinkgoConfig.FlakeAttempts), prefix+"flakeAttempts", 1, "Make up to this many attempts to run each spec. Please note that if any of the attempts succeed, the suite will not be failed. But any failures will still be recorded.") - - flagSet.BoolVar(&(GinkgoConfig.EmitSpecProgress), prefix+"progress", false, "If set, ginkgo will emit progress information as each spec runs to the GinkgoWriter.") - - if includeParallelFlags { - flagSet.IntVar(&(GinkgoConfig.ParallelNode), prefix+"parallel.node", 1, "This worker node's (one-indexed) node number. For running specs in parallel.") - flagSet.IntVar(&(GinkgoConfig.ParallelTotal), prefix+"parallel.total", 1, "The total number of worker nodes. For running specs in parallel.") - flagSet.StringVar(&(GinkgoConfig.SyncHost), prefix+"parallel.synchost", "", "The address for the server that will synchronize the running nodes.") - flagSet.StringVar(&(GinkgoConfig.StreamHost), prefix+"parallel.streamhost", "", "The address for the server that the running nodes should stream data to.") - } - - flagSet.BoolVar(&(DefaultReporterConfig.NoColor), prefix+"noColor", false, "If set, suppress color output in default reporter.") - flagSet.Float64Var(&(DefaultReporterConfig.SlowSpecThreshold), prefix+"slowSpecThreshold", 5.0, "(in seconds) Specs that take longer to run than this threshold are flagged as slow by the default reporter.") - flagSet.BoolVar(&(DefaultReporterConfig.NoisyPendings), prefix+"noisyPendings", true, "If set, default reporter will shout about pending tests.") - flagSet.BoolVar(&(DefaultReporterConfig.Verbose), prefix+"v", false, "If set, default reporter print out all specs as they begin.") - flagSet.BoolVar(&(DefaultReporterConfig.Succinct), prefix+"succinct", false, "If set, default reporter prints out a very succinct report") - flagSet.BoolVar(&(DefaultReporterConfig.FullTrace), prefix+"trace", false, "If set, default reporter prints out the full stack trace when a failure occurs") -} - -func BuildFlagArgs(prefix string, ginkgo GinkgoConfigType, reporter DefaultReporterConfigType) []string { - prefix = processPrefix(prefix) - result := make([]string, 0) - - if ginkgo.RandomSeed > 0 { - result = append(result, fmt.Sprintf("--%sseed=%d", prefix, ginkgo.RandomSeed)) - } - - if ginkgo.RandomizeAllSpecs { - result = append(result, fmt.Sprintf("--%srandomizeAllSpecs", prefix)) - } - - if ginkgo.SkipMeasurements { - result = append(result, fmt.Sprintf("--%sskipMeasurements", prefix)) - } - - if ginkgo.FailOnPending { - result = append(result, fmt.Sprintf("--%sfailOnPending", prefix)) - } - - if ginkgo.FailFast { - result = append(result, fmt.Sprintf("--%sfailFast", prefix)) - } - - if ginkgo.DryRun { - result = append(result, fmt.Sprintf("--%sdryRun", prefix)) - } - - if ginkgo.FocusString != "" { - result = append(result, fmt.Sprintf("--%sfocus=%s", prefix, ginkgo.FocusString)) - } - - if ginkgo.SkipString != "" { - result = append(result, fmt.Sprintf("--%sskip=%s", prefix, ginkgo.SkipString)) - } - - if ginkgo.FlakeAttempts > 1 { - result = append(result, fmt.Sprintf("--%sflakeAttempts=%d", prefix, ginkgo.FlakeAttempts)) - } - - if ginkgo.EmitSpecProgress { - result = append(result, fmt.Sprintf("--%sprogress", prefix)) - } - - if ginkgo.ParallelNode != 0 { - result = append(result, fmt.Sprintf("--%sparallel.node=%d", prefix, ginkgo.ParallelNode)) - } - - if ginkgo.ParallelTotal != 0 { - result = append(result, fmt.Sprintf("--%sparallel.total=%d", prefix, ginkgo.ParallelTotal)) - } - - if ginkgo.StreamHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.streamhost=%s", prefix, ginkgo.StreamHost)) - } - - if ginkgo.SyncHost != "" { - result = append(result, fmt.Sprintf("--%sparallel.synchost=%s", prefix, ginkgo.SyncHost)) - } - - if ginkgo.RegexScansFilePath { - result = append(result, fmt.Sprintf("--%sregexScansFilePath", prefix)) - } - - if reporter.NoColor { - result = append(result, fmt.Sprintf("--%snoColor", prefix)) - } - - if reporter.SlowSpecThreshold > 0 { - result = append(result, fmt.Sprintf("--%sslowSpecThreshold=%.5f", prefix, reporter.SlowSpecThreshold)) - } - - if !reporter.NoisyPendings { - result = append(result, fmt.Sprintf("--%snoisyPendings=false", prefix)) - } - - if reporter.Verbose { - result = append(result, fmt.Sprintf("--%sv", prefix)) - } - - if reporter.Succinct { - result = append(result, fmt.Sprintf("--%ssuccinct", prefix)) - } - - if reporter.FullTrace { - result = append(result, fmt.Sprintf("--%strace", prefix)) - } - - return result -} diff --git a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go b/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go deleted file mode 100644 index de6757c9f6..0000000000 --- a/vendor/github.com/onsi/ginkgo/ginkgo_dsl.go +++ /dev/null @@ -1,569 +0,0 @@ -/* -Ginkgo is a BDD-style testing framework for Golang - -The godoc documentation describes Ginkgo's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/ginkgo/ - -Ginkgo's preferred matcher library is [Gomega](http://github.com/onsi/gomega) - -Ginkgo on Github: http://github.com/onsi/ginkgo - -Ginkgo is MIT-Licensed -*/ -package ginkgo - -import ( - "flag" - "fmt" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/remote" - "github.com/onsi/ginkgo/internal/suite" - "github.com/onsi/ginkgo/internal/testingtproxy" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -const GINKGO_VERSION = config.VERSION -const GINKGO_PANIC = ` -Your test failed. -Ginkgo panics to prevent subsequent assertions from running. -Normally Ginkgo rescues this panic so you shouldn't see it. - -But, if you make an assertion in a goroutine, Ginkgo can't capture the panic. -To circumvent this, you should call - - defer GinkgoRecover() - -at the top of the goroutine that caused this panic. -` -const defaultTimeout = 1 - -var globalSuite *suite.Suite -var globalFailer *failer.Failer - -func init() { - config.Flags(flag.CommandLine, "ginkgo", true) - GinkgoWriter = writer.New(os.Stdout) - globalFailer = failer.New() - globalSuite = suite.New(globalFailer) -} - -//GinkgoWriter implements an io.Writer -//When running in verbose mode any writes to GinkgoWriter will be immediately printed -//to stdout. Otherwise, GinkgoWriter will buffer any writes produced during the current test and flush them to screen -//only if the current test fails. -var GinkgoWriter io.Writer - -//The interface by which Ginkgo receives *testing.T -type GinkgoTestingT interface { - Fail() -} - -//GinkgoRandomSeed returns the seed used to randomize spec execution order. It is -//useful for seeding your own pseudorandom number generators (PRNGs) to ensure -//consistent executions from run to run, where your tests contain variability (for -//example, when selecting random test data). -func GinkgoRandomSeed() int64 { - return config.GinkgoConfig.RandomSeed -} - -//GinkgoParallelNode returns the parallel node number for the current ginkgo process -//The node number is 1-indexed -func GinkgoParallelNode() int { - return config.GinkgoConfig.ParallelNode -} - -//Some matcher libraries or legacy codebases require a *testing.T -//GinkgoT implements an interface analogous to *testing.T and can be used if -//the library in question accepts *testing.T through an interface -// -// For example, with testify: -// assert.Equal(GinkgoT(), 123, 123, "they should be equal") -// -// Or with gomock: -// gomock.NewController(GinkgoT()) -// -// GinkgoT() takes an optional offset argument that can be used to get the -// correct line number associated with the failure. -func GinkgoT(optionalOffset ...int) GinkgoTInterface { - offset := 3 - if len(optionalOffset) > 0 { - offset = optionalOffset[0] - } - return testingtproxy.New(GinkgoWriter, Fail, offset) -} - -//The interface returned by GinkgoT(). This covers most of the methods -//in the testing package's T. -type GinkgoTInterface interface { - Fail() - Error(args ...interface{}) - Errorf(format string, args ...interface{}) - FailNow() - Fatal(args ...interface{}) - Fatalf(format string, args ...interface{}) - Log(args ...interface{}) - Logf(format string, args ...interface{}) - Failed() bool - Parallel() - Skip(args ...interface{}) - Skipf(format string, args ...interface{}) - SkipNow() - Skipped() bool -} - -//Custom Ginkgo test reporters must implement the Reporter interface. -// -//The custom reporter is passed in a SuiteSummary when the suite begins and ends, -//and a SpecSummary just before a spec begins and just after a spec ends -type Reporter reporters.Reporter - -//Asynchronous specs are given a channel of the Done type. You must close or write to the channel -//to tell Ginkgo that your async test is done. -type Done chan<- interface{} - -//GinkgoTestDescription represents the information about the current running test returned by CurrentGinkgoTestDescription -// FullTestText: a concatenation of ComponentTexts and the TestText -// ComponentTexts: a list of all texts for the Describes & Contexts leading up to the current test -// TestText: the text in the actual It or Measure node -// IsMeasurement: true if the current test is a measurement -// FileName: the name of the file containing the current test -// LineNumber: the line number for the current test -// Failed: if the current test has failed, this will be true (useful in an AfterEach) -type GinkgoTestDescription struct { - FullTestText string - ComponentTexts []string - TestText string - - IsMeasurement bool - - FileName string - LineNumber int - - Failed bool -} - -//CurrentGinkgoTestDescripton returns information about the current running test. -func CurrentGinkgoTestDescription() GinkgoTestDescription { - summary, ok := globalSuite.CurrentRunningSpecSummary() - if !ok { - return GinkgoTestDescription{} - } - - subjectCodeLocation := summary.ComponentCodeLocations[len(summary.ComponentCodeLocations)-1] - - return GinkgoTestDescription{ - ComponentTexts: summary.ComponentTexts[1:], - FullTestText: strings.Join(summary.ComponentTexts[1:], " "), - TestText: summary.ComponentTexts[len(summary.ComponentTexts)-1], - IsMeasurement: summary.IsMeasurement, - FileName: subjectCodeLocation.FileName, - LineNumber: subjectCodeLocation.LineNumber, - Failed: summary.HasFailureState(), - } -} - -//Measurement tests receive a Benchmarker. -// -//You use the Time() function to time how long the passed in body function takes to run -//You use the RecordValue() function to track arbitrary numerical measurements. -//The RecordValueWithPrecision() function can be used alternatively to provide the unit -//and resolution of the numeric measurement. -//The optional info argument is passed to the test reporter and can be used to -// provide the measurement data to a custom reporter with context. -// -//See http://onsi.github.io/ginkgo/#benchmark_tests for more details -type Benchmarker interface { - Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) - RecordValue(name string, value float64, info ...interface{}) - RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) -} - -//RunSpecs is the entry point for the Ginkgo test runner. -//You must call this within a Golang testing TestX(t *testing.T) function. -// -//To bootstrap a test suite you can use the Ginkgo CLI: -// -// ginkgo bootstrap -func RunSpecs(t GinkgoTestingT, description string) bool { - specReporters := []Reporter{buildDefaultReporter()} - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with Ginkgo's default reporter and your custom reporter(s), replace -//RunSpecs() with this method. -func RunSpecsWithDefaultAndCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - specReporters = append(specReporters, buildDefaultReporter()) - return RunSpecsWithCustomReporters(t, description, specReporters) -} - -//To run your tests with your custom reporter(s) (and *not* Ginkgo's default reporter), replace -//RunSpecs() with this method. Note that parallel tests will not work correctly without the default reporter -func RunSpecsWithCustomReporters(t GinkgoTestingT, description string, specReporters []Reporter) bool { - writer := GinkgoWriter.(*writer.Writer) - writer.SetStream(config.DefaultReporterConfig.Verbose) - reporters := make([]reporters.Reporter, len(specReporters)) - for i, reporter := range specReporters { - reporters[i] = reporter - } - passed, hasFocusedTests := globalSuite.Run(t, description, reporters, writer, config.GinkgoConfig) - if passed && hasFocusedTests { - fmt.Println("PASS | FOCUSED") - os.Exit(types.GINKGO_FOCUS_EXIT_CODE) - } - return passed -} - -func buildDefaultReporter() Reporter { - remoteReportingServer := config.GinkgoConfig.StreamHost - if remoteReportingServer == "" { - stenographer := stenographer.New(!config.DefaultReporterConfig.NoColor, config.GinkgoConfig.FlakeAttempts > 1) - return reporters.NewDefaultReporter(config.DefaultReporterConfig, stenographer) - } else { - return remote.NewForwardingReporter(remoteReportingServer, &http.Client{}, remote.NewOutputInterceptor()) - } -} - -//Skip notifies Ginkgo that the current spec should be skipped. -func Skip(message string, callerSkip ...int) { - skip := 0 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - - globalFailer.Skip(message, codelocation.New(skip+1)) - panic(GINKGO_PANIC) -} - -//Fail notifies Ginkgo that the current spec has failed. (Gomega will call Fail for you automatically when an assertion fails.) -func Fail(message string, callerSkip ...int) { - skip := 0 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - - globalFailer.Fail(message, codelocation.New(skip+1)) - panic(GINKGO_PANIC) -} - -//GinkgoRecover should be deferred at the top of any spawned goroutine that (may) call `Fail` -//Since Gomega assertions call fail, you should throw a `defer GinkgoRecover()` at the top of any goroutine that -//calls out to Gomega -// -//Here's why: Ginkgo's `Fail` method records the failure and then panics to prevent -//further assertions from running. This panic must be recovered. Ginkgo does this for you -//if the panic originates in a Ginkgo node (an It, BeforeEach, etc...) -// -//Unfortunately, if a panic originates on a goroutine *launched* from one of these nodes there's no -//way for Ginkgo to rescue the panic. To do this, you must remember to `defer GinkgoRecover()` at the top of such a goroutine. -func GinkgoRecover() { - e := recover() - if e != nil { - globalFailer.Panic(codelocation.New(1), e) - } -} - -//Describe blocks allow you to organize your specs. A Describe block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. -func Describe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FDescribe -func FDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PDescribe -func PDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XDescribe -func XDescribe(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//Context blocks allow you to organize your specs. A Context block can contain any number of -//BeforeEach, AfterEach, JustBeforeEach, It, and Measurement blocks. -// -//In addition you can nest Describe and Context blocks. Describe and Context blocks are functionally -//equivalent. The difference is purely semantic -- you typical Describe the behavior of an object -//or method and, within that Describe, outline a number of Contexts. -func Context(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeNone, codelocation.New(1)) - return true -} - -//You can focus the tests within a describe block using FContext -func FContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypeFocused, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using PContext -func PContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//You can mark the tests within a describe block as pending using XContext -func XContext(text string, body func()) bool { - globalSuite.PushContainerNode(text, body, types.FlagTypePending, codelocation.New(1)) - return true -} - -//It blocks contain your test code and assertions. You cannot nest any other Ginkgo blocks -//within an It block. -// -//Ginkgo will normally run It blocks synchronously. To perform asynchronous tests, pass a -//function that accepts a Done channel. When you do this, you can also provide an optional timeout. -func It(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeNone, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can focus individual Its using FIt -func FIt(text string, body interface{}, timeout ...float64) bool { - globalSuite.PushItNode(text, body, types.FlagTypeFocused, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//You can mark Its as pending using PIt -func PIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Its as pending using XIt -func XIt(text string, _ ...interface{}) bool { - globalSuite.PushItNode(text, func() {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//Specify blocks are aliases for It blocks and allow for more natural wording in situations -//which "It" does not fit into a natural sentence flow. All the same protocols apply for Specify blocks -//which apply to It blocks. -func Specify(text string, body interface{}, timeout ...float64) bool { - return It(text, body, timeout...) -} - -//You can focus individual Specifys using FSpecify -func FSpecify(text string, body interface{}, timeout ...float64) bool { - return FIt(text, body, timeout...) -} - -//You can mark Specifys as pending using PSpecify -func PSpecify(text string, is ...interface{}) bool { - return PIt(text, is...) -} - -//You can mark Specifys as pending using XSpecify -func XSpecify(text string, is ...interface{}) bool { - return XIt(text, is...) -} - -//By allows you to better document large Its. -// -//Generally you should try to keep your Its short and to the point. This is not always possible, however, -//especially in the context of integration tests that capture a particular workflow. -// -//By allows you to document such flows. By must be called within a runnable node (It, BeforeEach, Measure, etc...) -//By will simply log the passed in text to the GinkgoWriter. If By is handed a function it will immediately run the function. -func By(text string, callbacks ...func()) { - preamble := "\x1b[1mSTEP\x1b[0m" - if config.DefaultReporterConfig.NoColor { - preamble = "STEP" - } - fmt.Fprintln(GinkgoWriter, preamble+": "+text) - if len(callbacks) == 1 { - callbacks[0]() - } - if len(callbacks) > 1 { - panic("just one callback per By, please") - } -} - -//Measure blocks run the passed in body function repeatedly (determined by the samples argument) -//and accumulate metrics provided to the Benchmarker by the body function. -// -//The body function must have the signature: -// func(b Benchmarker) -func Measure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeNone, codelocation.New(1), samples) - return true -} - -//You can focus individual Measures using FMeasure -func FMeasure(text string, body interface{}, samples int) bool { - globalSuite.PushMeasureNode(text, body, types.FlagTypeFocused, codelocation.New(1), samples) - return true -} - -//You can mark Maeasurements as pending using PMeasure -func PMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//You can mark Maeasurements as pending using XMeasure -func XMeasure(text string, _ ...interface{}) bool { - globalSuite.PushMeasureNode(text, func(b Benchmarker) {}, types.FlagTypePending, codelocation.New(1), 0) - return true -} - -//BeforeSuite blocks are run just once before any specs are run. When running in parallel, each -//parallel node process will call BeforeSuite. -// -//BeforeSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* BeforeSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func BeforeSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetBeforeSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterSuite blocks are *always* run after all the specs regardless of whether specs have passed or failed. -//Moreover, if Ginkgo receives an interrupt signal (^C) it will attempt to run the AfterSuite before exiting. -// -//When running in parallel, each parallel node process will call AfterSuite. -// -//AfterSuite blocks can be made asynchronous by providing a body function that accepts a Done channel -// -//You may only register *one* AfterSuite handler per test suite. You typically do so in your bootstrap file at the top level. -func AfterSuite(body interface{}, timeout ...float64) bool { - globalSuite.SetAfterSuiteNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//SynchronizedBeforeSuite blocks are primarily meant to solve the problem of setting up singleton external resources shared across -//nodes when running tests in parallel. For example, say you have a shared database that you can only start one instance of that -//must be used in your tests. When running in parallel, only one node should set up the database and all other nodes should wait -//until that node is done before running. -// -//SynchronizedBeforeSuite accomplishes this by taking *two* function arguments. The first is only run on parallel node #1. The second is -//run on all nodes, but *only* after the first function completes succesfully. Ginkgo also makes it possible to send data from the first function (on Node 1) -//to the second function (on all the other nodes). -// -//The functions have the following signatures. The first function (which only runs on node 1) has the signature: -// -// func() []byte -// -//or, to run asynchronously: -// -// func(done Done) []byte -// -//The byte array returned by the first function is then passed to the second function, which has the signature: -// -// func(data []byte) -// -//or, to run asynchronously: -// -// func(data []byte, done Done) -// -//Here's a simple pseudo-code example that starts a shared database on Node 1 and shares the database's address with the other nodes: -// -// var dbClient db.Client -// var dbRunner db.Runner -// -// var _ = SynchronizedBeforeSuite(func() []byte { -// dbRunner = db.NewRunner() -// err := dbRunner.Start() -// Ω(err).ShouldNot(HaveOccurred()) -// return []byte(dbRunner.URL) -// }, func(data []byte) { -// dbClient = db.NewClient() -// err := dbClient.Connect(string(data)) -// Ω(err).ShouldNot(HaveOccurred()) -// }) -func SynchronizedBeforeSuite(node1Body interface{}, allNodesBody interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedBeforeSuiteNode( - node1Body, - allNodesBody, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//SynchronizedAfterSuite blocks complement the SynchronizedBeforeSuite blocks in solving the problem of setting up -//external singleton resources shared across nodes when running tests in parallel. -// -//SynchronizedAfterSuite accomplishes this by taking *two* function arguments. The first runs on all nodes. The second runs only on parallel node #1 -//and *only* after all other nodes have finished and exited. This ensures that node 1, and any resources it is running, remain alive until -//all other nodes are finished. -// -//Both functions have the same signature: either func() or func(done Done) to run asynchronously. -// -//Here's a pseudo-code example that complements that given in SynchronizedBeforeSuite. Here, SynchronizedAfterSuite is used to tear down the shared database -//only after all nodes have finished: -// -// var _ = SynchronizedAfterSuite(func() { -// dbClient.Cleanup() -// }, func() { -// dbRunner.Stop() -// }) -func SynchronizedAfterSuite(allNodesBody interface{}, node1Body interface{}, timeout ...float64) bool { - globalSuite.SetSynchronizedAfterSuiteNode( - allNodesBody, - node1Body, - codelocation.New(1), - parseTimeout(timeout...), - ) - return true -} - -//BeforeEach blocks are run before It blocks. When multiple BeforeEach blocks are defined in nested -//Describe and Context blocks the outermost BeforeEach blocks are run first. -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func BeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//JustBeforeEach blocks are run before It blocks but *after* all BeforeEach blocks. For more details, -//read the [documentation](http://onsi.github.io/ginkgo/#separating_creation_and_configuration_) -// -//Like It blocks, BeforeEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func JustBeforeEach(body interface{}, timeout ...float64) bool { - globalSuite.PushJustBeforeEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -//AfterEach blocks are run after It blocks. When multiple AfterEach blocks are defined in nested -//Describe and Context blocks the innermost AfterEach blocks are run first. -// -//Like It blocks, AfterEach blocks can be made asynchronous by providing a body function that accepts -//a Done channel -func AfterEach(body interface{}, timeout ...float64) bool { - globalSuite.PushAfterEachNode(body, codelocation.New(1), parseTimeout(timeout...)) - return true -} - -func parseTimeout(timeout ...float64) time.Duration { - if len(timeout) == 0 { - return time.Duration(defaultTimeout * int64(time.Second)) - } else { - return time.Duration(timeout[0] * float64(time.Second)) - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go b/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go deleted file mode 100644 index fa2f0bf730..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/codelocation/code_location.go +++ /dev/null @@ -1,32 +0,0 @@ -package codelocation - -import ( - "regexp" - "runtime" - "runtime/debug" - "strings" - - "github.com/onsi/ginkgo/types" -) - -func New(skip int) types.CodeLocation { - _, file, line, _ := runtime.Caller(skip + 1) - stackTrace := PruneStack(string(debug.Stack()), skip) - return types.CodeLocation{FileName: file, LineNumber: line, FullStackTrace: stackTrace} -} - -func PruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n") - if len(stack) > 2*(skip+1) { - stack = stack[2*(skip+1):] - } - prunedStack := []string{} - re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) - for i := 0; i < len(stack)/2; i++ { - if !re.Match([]byte(stack[i*2])) { - prunedStack = append(prunedStack, stack[i*2]) - prunedStack = append(prunedStack, stack[i*2+1]) - } - } - return strings.Join(prunedStack, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go b/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go deleted file mode 100644 index 0737746dcf..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/containernode/container_node.go +++ /dev/null @@ -1,151 +0,0 @@ -package containernode - -import ( - "math/rand" - "sort" - - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type subjectOrContainerNode struct { - containerNode *ContainerNode - subjectNode leafnodes.SubjectNode -} - -func (n subjectOrContainerNode) text() string { - if n.containerNode != nil { - return n.containerNode.Text() - } else { - return n.subjectNode.Text() - } -} - -type CollatedNodes struct { - Containers []*ContainerNode - Subject leafnodes.SubjectNode -} - -type ContainerNode struct { - text string - flag types.FlagType - codeLocation types.CodeLocation - - setupNodes []leafnodes.BasicNode - subjectAndContainerNodes []subjectOrContainerNode -} - -func New(text string, flag types.FlagType, codeLocation types.CodeLocation) *ContainerNode { - return &ContainerNode{ - text: text, - flag: flag, - codeLocation: codeLocation, - } -} - -func (container *ContainerNode) Shuffle(r *rand.Rand) { - sort.Sort(container) - permutation := r.Perm(len(container.subjectAndContainerNodes)) - shuffledNodes := make([]subjectOrContainerNode, len(container.subjectAndContainerNodes)) - for i, j := range permutation { - shuffledNodes[i] = container.subjectAndContainerNodes[j] - } - container.subjectAndContainerNodes = shuffledNodes -} - -func (node *ContainerNode) BackPropagateProgrammaticFocus() bool { - if node.flag == types.FlagTypePending { - return false - } - - shouldUnfocus := false - for _, subjectOrContainerNode := range node.subjectAndContainerNodes { - if subjectOrContainerNode.containerNode != nil { - shouldUnfocus = subjectOrContainerNode.containerNode.BackPropagateProgrammaticFocus() || shouldUnfocus - } else { - shouldUnfocus = (subjectOrContainerNode.subjectNode.Flag() == types.FlagTypeFocused) || shouldUnfocus - } - } - - if shouldUnfocus { - if node.flag == types.FlagTypeFocused { - node.flag = types.FlagTypeNone - } - return true - } - - return node.flag == types.FlagTypeFocused -} - -func (node *ContainerNode) Collate() []CollatedNodes { - return node.collate([]*ContainerNode{}) -} - -func (node *ContainerNode) collate(enclosingContainers []*ContainerNode) []CollatedNodes { - collated := make([]CollatedNodes, 0) - - containers := make([]*ContainerNode, len(enclosingContainers)) - copy(containers, enclosingContainers) - containers = append(containers, node) - - for _, subjectOrContainer := range node.subjectAndContainerNodes { - if subjectOrContainer.containerNode != nil { - collated = append(collated, subjectOrContainer.containerNode.collate(containers)...) - } else { - collated = append(collated, CollatedNodes{ - Containers: containers, - Subject: subjectOrContainer.subjectNode, - }) - } - } - - return collated -} - -func (node *ContainerNode) PushContainerNode(container *ContainerNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{containerNode: container}) -} - -func (node *ContainerNode) PushSubjectNode(subject leafnodes.SubjectNode) { - node.subjectAndContainerNodes = append(node.subjectAndContainerNodes, subjectOrContainerNode{subjectNode: subject}) -} - -func (node *ContainerNode) PushSetupNode(setupNode leafnodes.BasicNode) { - node.setupNodes = append(node.setupNodes, setupNode) -} - -func (node *ContainerNode) SetupNodesOfType(nodeType types.SpecComponentType) []leafnodes.BasicNode { - nodes := []leafnodes.BasicNode{} - for _, setupNode := range node.setupNodes { - if setupNode.Type() == nodeType { - nodes = append(nodes, setupNode) - } - } - return nodes -} - -func (node *ContainerNode) Text() string { - return node.text -} - -func (node *ContainerNode) CodeLocation() types.CodeLocation { - return node.codeLocation -} - -func (node *ContainerNode) Flag() types.FlagType { - return node.flag -} - -//sort.Interface - -func (node *ContainerNode) Len() int { - return len(node.subjectAndContainerNodes) -} - -func (node *ContainerNode) Less(i, j int) bool { - return node.subjectAndContainerNodes[i].text() < node.subjectAndContainerNodes[j].text() -} - -func (node *ContainerNode) Swap(i, j int) { - node.subjectAndContainerNodes[i], node.subjectAndContainerNodes[j] = node.subjectAndContainerNodes[j], node.subjectAndContainerNodes[i] -} diff --git a/vendor/github.com/onsi/ginkgo/internal/failer/failer.go b/vendor/github.com/onsi/ginkgo/internal/failer/failer.go deleted file mode 100644 index 678ea2514a..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/failer/failer.go +++ /dev/null @@ -1,92 +0,0 @@ -package failer - -import ( - "fmt" - "sync" - - "github.com/onsi/ginkgo/types" -) - -type Failer struct { - lock *sync.Mutex - failure types.SpecFailure - state types.SpecState -} - -func New() *Failer { - return &Failer{ - lock: &sync.Mutex{}, - state: types.SpecStatePassed, - } -} - -func (f *Failer) Panic(location types.CodeLocation, forwardedPanic interface{}) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStatePanicked - f.failure = types.SpecFailure{ - Message: "Test Panicked", - Location: location, - ForwardedPanic: fmt.Sprintf("%v", forwardedPanic), - } - } -} - -func (f *Failer) Timeout(location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateTimedOut - f.failure = types.SpecFailure{ - Message: "Timed out", - Location: location, - } - } -} - -func (f *Failer) Fail(message string, location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateFailed - f.failure = types.SpecFailure{ - Message: message, - Location: location, - } - } -} - -func (f *Failer) Drain(componentType types.SpecComponentType, componentIndex int, componentCodeLocation types.CodeLocation) (types.SpecFailure, types.SpecState) { - f.lock.Lock() - defer f.lock.Unlock() - - failure := f.failure - outcome := f.state - if outcome != types.SpecStatePassed { - failure.ComponentType = componentType - failure.ComponentIndex = componentIndex - failure.ComponentCodeLocation = componentCodeLocation - } - - f.state = types.SpecStatePassed - f.failure = types.SpecFailure{} - - return failure, outcome -} - -func (f *Failer) Skip(message string, location types.CodeLocation) { - f.lock.Lock() - defer f.lock.Unlock() - - if f.state == types.SpecStatePassed { - f.state = types.SpecStateSkipped - f.failure = types.SpecFailure{ - Message: message, - Location: location, - } - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go deleted file mode 100644 index 9c3eed2b6f..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/benchmarker.go +++ /dev/null @@ -1,103 +0,0 @@ -package leafnodes - -import ( - "math" - "time" - - "sync" - - "github.com/onsi/ginkgo/types" -) - -type benchmarker struct { - mu sync.Mutex - measurements map[string]*types.SpecMeasurement - orderCounter int -} - -func newBenchmarker() *benchmarker { - return &benchmarker{ - measurements: make(map[string]*types.SpecMeasurement, 0), - } -} - -func (b *benchmarker) Time(name string, body func(), info ...interface{}) (elapsedTime time.Duration) { - t := time.Now() - body() - elapsedTime = time.Since(t) - - b.mu.Lock() - defer b.mu.Unlock() - measurement := b.getMeasurement(name, "Fastest Time", "Slowest Time", "Average Time", "s", 3, info...) - measurement.Results = append(measurement.Results, elapsedTime.Seconds()) - - return -} - -func (b *benchmarker) RecordValue(name string, value float64, info ...interface{}) { - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", "", 3, info...) - b.mu.Lock() - defer b.mu.Unlock() - measurement.Results = append(measurement.Results, value) -} - -func (b *benchmarker) RecordValueWithPrecision(name string, value float64, units string, precision int, info ...interface{}) { - measurement := b.getMeasurement(name, "Smallest", " Largest", " Average", units, precision, info...) - b.mu.Lock() - defer b.mu.Unlock() - measurement.Results = append(measurement.Results, value) -} - -func (b *benchmarker) getMeasurement(name string, smallestLabel string, largestLabel string, averageLabel string, units string, precision int, info ...interface{}) *types.SpecMeasurement { - measurement, ok := b.measurements[name] - if !ok { - var computedInfo interface{} - computedInfo = nil - if len(info) > 0 { - computedInfo = info[0] - } - measurement = &types.SpecMeasurement{ - Name: name, - Info: computedInfo, - Order: b.orderCounter, - SmallestLabel: smallestLabel, - LargestLabel: largestLabel, - AverageLabel: averageLabel, - Units: units, - Precision: precision, - Results: make([]float64, 0), - } - b.measurements[name] = measurement - b.orderCounter++ - } - - return measurement -} - -func (b *benchmarker) measurementsReport() map[string]*types.SpecMeasurement { - b.mu.Lock() - defer b.mu.Unlock() - for _, measurement := range b.measurements { - measurement.Smallest = math.MaxFloat64 - measurement.Largest = -math.MaxFloat64 - sum := float64(0) - sumOfSquares := float64(0) - - for _, result := range measurement.Results { - if result > measurement.Largest { - measurement.Largest = result - } - if result < measurement.Smallest { - measurement.Smallest = result - } - sum += result - sumOfSquares += result * result - } - - n := float64(len(measurement.Results)) - measurement.Average = sum / n - measurement.StdDeviation = math.Sqrt(sumOfSquares/n - (sum/n)*(sum/n)) - } - - return b.measurements -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go deleted file mode 100644 index 8c3902d601..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/interfaces.go +++ /dev/null @@ -1,19 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/types" -) - -type BasicNode interface { - Type() types.SpecComponentType - Run() (types.SpecState, types.SpecFailure) - CodeLocation() types.CodeLocation -} - -type SubjectNode interface { - BasicNode - - Text() string - Flag() types.FlagType - Samples() int -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go deleted file mode 100644 index c76fe3a451..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/it_node.go +++ /dev/null @@ -1,46 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type ItNode struct { - runner *runner - - flag types.FlagType - text string -} - -func NewItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *ItNode { - return &ItNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeIt, componentIndex), - flag: flag, - text: text, - } -} - -func (node *ItNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *ItNode) Type() types.SpecComponentType { - return types.SpecComponentTypeIt -} - -func (node *ItNode) Text() string { - return node.text -} - -func (node *ItNode) Flag() types.FlagType { - return node.flag -} - -func (node *ItNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *ItNode) Samples() int { - return 1 -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go deleted file mode 100644 index efc3348c1b..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/measure_node.go +++ /dev/null @@ -1,61 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "reflect" -) - -type MeasureNode struct { - runner *runner - - text string - flag types.FlagType - samples int - benchmarker *benchmarker -} - -func NewMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int, failer *failer.Failer, componentIndex int) *MeasureNode { - benchmarker := newBenchmarker() - - wrappedBody := func() { - reflect.ValueOf(body).Call([]reflect.Value{reflect.ValueOf(benchmarker)}) - } - - return &MeasureNode{ - runner: newRunner(wrappedBody, codeLocation, 0, failer, types.SpecComponentTypeMeasure, componentIndex), - - text: text, - flag: flag, - samples: samples, - benchmarker: benchmarker, - } -} - -func (node *MeasureNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *MeasureNode) MeasurementsReport() map[string]*types.SpecMeasurement { - return node.benchmarker.measurementsReport() -} - -func (node *MeasureNode) Type() types.SpecComponentType { - return types.SpecComponentTypeMeasure -} - -func (node *MeasureNode) Text() string { - return node.text -} - -func (node *MeasureNode) Flag() types.FlagType { - return node.flag -} - -func (node *MeasureNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func (node *MeasureNode) Samples() int { - return node.samples -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go deleted file mode 100644 index 870ad826da..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/runner.go +++ /dev/null @@ -1,113 +0,0 @@ -package leafnodes - -import ( - "fmt" - "github.com/onsi/ginkgo/internal/codelocation" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "reflect" - "time" -) - -type runner struct { - isAsync bool - asyncFunc func(chan<- interface{}) - syncFunc func() - codeLocation types.CodeLocation - timeoutThreshold time.Duration - nodeType types.SpecComponentType - componentIndex int - failer *failer.Failer -} - -func newRunner(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, nodeType types.SpecComponentType, componentIndex int) *runner { - bodyType := reflect.TypeOf(body) - if bodyType.Kind() != reflect.Func { - panic(fmt.Sprintf("Expected a function but got something else at %v", codeLocation)) - } - - runner := &runner{ - codeLocation: codeLocation, - timeoutThreshold: timeout, - failer: failer, - nodeType: nodeType, - componentIndex: componentIndex, - } - - switch bodyType.NumIn() { - case 0: - runner.syncFunc = body.(func()) - return runner - case 1: - if !(bodyType.In(0).Kind() == reflect.Chan && bodyType.In(0).Elem().Kind() == reflect.Interface) { - panic(fmt.Sprintf("Must pass a Done channel to function at %v", codeLocation)) - } - - wrappedBody := func(done chan<- interface{}) { - bodyValue := reflect.ValueOf(body) - bodyValue.Call([]reflect.Value{reflect.ValueOf(done)}) - } - - runner.isAsync = true - runner.asyncFunc = wrappedBody - return runner - } - - panic(fmt.Sprintf("Too many arguments to function at %v", codeLocation)) -} - -func (r *runner) run() (outcome types.SpecState, failure types.SpecFailure) { - if r.isAsync { - return r.runAsync() - } else { - return r.runSync() - } -} - -func (r *runner) runAsync() (outcome types.SpecState, failure types.SpecFailure) { - done := make(chan interface{}, 1) - - go func() { - finished := false - - defer func() { - if e := recover(); e != nil || !finished { - r.failer.Panic(codelocation.New(2), e) - select { - case <-done: - break - default: - close(done) - } - } - }() - - r.asyncFunc(done) - finished = true - }() - - select { - case <-done: - case <-time.After(r.timeoutThreshold): - r.failer.Timeout(r.codeLocation) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - return -} -func (r *runner) runSync() (outcome types.SpecState, failure types.SpecFailure) { - finished := false - - defer func() { - if e := recover(); e != nil || !finished { - r.failer.Panic(codelocation.New(2), e) - } - - failure, outcome = r.failer.Drain(r.nodeType, r.componentIndex, r.codeLocation) - }() - - r.syncFunc() - finished = true - - return -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go deleted file mode 100644 index 6b725a6315..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/setup_nodes.go +++ /dev/null @@ -1,41 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type SetupNode struct { - runner *runner -} - -func (node *SetupNode) Run() (outcome types.SpecState, failure types.SpecFailure) { - return node.runner.run() -} - -func (node *SetupNode) Type() types.SpecComponentType { - return node.runner.nodeType -} - -func (node *SetupNode) CodeLocation() types.CodeLocation { - return node.runner.codeLocation -} - -func NewBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeEach, componentIndex), - } -} - -func NewAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterEach, componentIndex), - } -} - -func NewJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer, componentIndex int) *SetupNode { - return &SetupNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeJustBeforeEach, componentIndex), - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go deleted file mode 100644 index 2ccc7dc0fb..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/suite_nodes.go +++ /dev/null @@ -1,54 +0,0 @@ -package leafnodes - -import ( - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "time" -) - -type SuiteNode interface { - Run(parallelNode int, parallelTotal int, syncHost string) bool - Passed() bool - Summary() *types.SetupSummary -} - -type simpleSuiteNode struct { - runner *runner - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func (node *simpleSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - node.outcome, node.failure = node.runner.run() - node.runTime = time.Since(t) - - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *simpleSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runner.nodeType, - CodeLocation: node.runner.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func NewBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0), - } -} - -func NewAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &simpleSuiteNode{ - runner: newRunner(body, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go deleted file mode 100644 index e7030d9149..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_after_suite_node.go +++ /dev/null @@ -1,89 +0,0 @@ -package leafnodes - -import ( - "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "io/ioutil" - "net/http" - "time" -) - -type synchronizedAfterSuiteNode struct { - runnerA *runner - runnerB *runner - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - return &synchronizedAfterSuiteNode{ - runnerA: newRunner(bodyA, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - runnerB: newRunner(bodyB, codeLocation, timeout, failer, types.SpecComponentTypeAfterSuite, 0), - } -} - -func (node *synchronizedAfterSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - node.outcome, node.failure = node.runnerA.run() - - if parallelNode == 1 { - if parallelTotal > 1 { - node.waitUntilOtherNodesAreDone(syncHost) - } - - outcome, failure := node.runnerB.run() - - if node.outcome == types.SpecStatePassed { - node.outcome, node.failure = outcome, failure - } - } - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedAfterSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedAfterSuiteNode) waitUntilOtherNodesAreDone(syncHost string) { - for { - if node.canRun(syncHost) { - return - } - - time.Sleep(50 * time.Millisecond) - } -} - -func (node *synchronizedAfterSuiteNode) canRun(syncHost string) bool { - resp, err := http.Get(syncHost + "/RemoteAfterSuiteData") - if err != nil || resp.StatusCode != http.StatusOK { - return false - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return false - } - resp.Body.Close() - - afterSuiteData := types.RemoteAfterSuiteData{} - err = json.Unmarshal(body, &afterSuiteData) - if err != nil { - return false - } - - return afterSuiteData.CanRun -} diff --git a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go b/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go deleted file mode 100644 index 76a9679813..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/leafnodes/synchronized_before_suite_node.go +++ /dev/null @@ -1,182 +0,0 @@ -package leafnodes - -import ( - "bytes" - "encoding/json" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/types" - "io/ioutil" - "net/http" - "reflect" - "time" -) - -type synchronizedBeforeSuiteNode struct { - runnerA *runner - runnerB *runner - - data []byte - - outcome types.SpecState - failure types.SpecFailure - runTime time.Duration -} - -func NewSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration, failer *failer.Failer) SuiteNode { - node := &synchronizedBeforeSuiteNode{} - - node.runnerA = newRunner(node.wrapA(bodyA), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - node.runnerB = newRunner(node.wrapB(bodyB), codeLocation, timeout, failer, types.SpecComponentTypeBeforeSuite, 0) - - return node -} - -func (node *synchronizedBeforeSuiteNode) Run(parallelNode int, parallelTotal int, syncHost string) bool { - t := time.Now() - defer func() { - node.runTime = time.Since(t) - }() - - if parallelNode == 1 { - node.outcome, node.failure = node.runA(parallelTotal, syncHost) - } else { - node.outcome, node.failure = node.waitForA(syncHost) - } - - if node.outcome != types.SpecStatePassed { - return false - } - node.outcome, node.failure = node.runnerB.run() - - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) runA(parallelTotal int, syncHost string) (types.SpecState, types.SpecFailure) { - outcome, failure := node.runnerA.run() - - if parallelTotal > 1 { - state := types.RemoteBeforeSuiteStatePassed - if outcome != types.SpecStatePassed { - state = types.RemoteBeforeSuiteStateFailed - } - json := (types.RemoteBeforeSuiteData{ - Data: node.data, - State: state, - }).ToJSON() - http.Post(syncHost+"/BeforeSuiteState", "application/json", bytes.NewBuffer(json)) - } - - return outcome, failure -} - -func (node *synchronizedBeforeSuiteNode) waitForA(syncHost string) (types.SpecState, types.SpecFailure) { - failure := func(message string) types.SpecFailure { - return types.SpecFailure{ - Message: message, - Location: node.runnerA.codeLocation, - ComponentType: node.runnerA.nodeType, - ComponentIndex: node.runnerA.componentIndex, - ComponentCodeLocation: node.runnerA.codeLocation, - } - } - for { - resp, err := http.Get(syncHost + "/BeforeSuiteState") - if err != nil || resp.StatusCode != http.StatusOK { - return types.SpecStateFailed, failure("Failed to fetch BeforeSuite state") - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return types.SpecStateFailed, failure("Failed to read BeforeSuite state") - } - resp.Body.Close() - - beforeSuiteData := types.RemoteBeforeSuiteData{} - err = json.Unmarshal(body, &beforeSuiteData) - if err != nil { - return types.SpecStateFailed, failure("Failed to decode BeforeSuite state") - } - - switch beforeSuiteData.State { - case types.RemoteBeforeSuiteStatePassed: - node.data = beforeSuiteData.Data - return types.SpecStatePassed, types.SpecFailure{} - case types.RemoteBeforeSuiteStateFailed: - return types.SpecStateFailed, failure("BeforeSuite on Node 1 failed") - case types.RemoteBeforeSuiteStateDisappeared: - return types.SpecStateFailed, failure("Node 1 disappeared before completing BeforeSuite") - } - - time.Sleep(50 * time.Millisecond) - } - - return types.SpecStateFailed, failure("Shouldn't get here!") -} - -func (node *synchronizedBeforeSuiteNode) Passed() bool { - return node.outcome == types.SpecStatePassed -} - -func (node *synchronizedBeforeSuiteNode) Summary() *types.SetupSummary { - return &types.SetupSummary{ - ComponentType: node.runnerA.nodeType, - CodeLocation: node.runnerA.codeLocation, - State: node.outcome, - RunTime: node.runTime, - Failure: node.failure, - } -} - -func (node *synchronizedBeforeSuiteNode) wrapA(bodyA interface{}) interface{} { - typeA := reflect.TypeOf(bodyA) - if typeA.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its first argument") - } - - takesNothing := typeA.NumIn() == 0 - takesADoneChannel := typeA.NumIn() == 1 && typeA.In(0).Kind() == reflect.Chan && typeA.In(0).Elem().Kind() == reflect.Interface - returnsBytes := typeA.NumOut() == 1 && typeA.Out(0).Kind() == reflect.Slice && typeA.Out(0).Elem().Kind() == reflect.Uint8 - - if !((takesNothing || takesADoneChannel) && returnsBytes) { - panic("SynchronizedBeforeSuite's first argument should be a function that returns []byte and either takes no arguments or takes a Done channel.") - } - - if takesADoneChannel { - return func(done chan<- interface{}) { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{reflect.ValueOf(done)}) - node.data = out[0].Interface().([]byte) - } - } - - return func() { - out := reflect.ValueOf(bodyA).Call([]reflect.Value{}) - node.data = out[0].Interface().([]byte) - } -} - -func (node *synchronizedBeforeSuiteNode) wrapB(bodyB interface{}) interface{} { - typeB := reflect.TypeOf(bodyB) - if typeB.Kind() != reflect.Func { - panic("SynchronizedBeforeSuite expects a function as its second argument") - } - - returnsNothing := typeB.NumOut() == 0 - takesBytesOnly := typeB.NumIn() == 1 && typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 - takesBytesAndDone := typeB.NumIn() == 2 && - typeB.In(0).Kind() == reflect.Slice && typeB.In(0).Elem().Kind() == reflect.Uint8 && - typeB.In(1).Kind() == reflect.Chan && typeB.In(1).Elem().Kind() == reflect.Interface - - if !((takesBytesOnly || takesBytesAndDone) && returnsNothing) { - panic("SynchronizedBeforeSuite's second argument should be a function that returns nothing and either takes []byte or ([]byte, Done)") - } - - if takesBytesAndDone { - return func(done chan<- interface{}) { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data), reflect.ValueOf(done)}) - } - } - - return func() { - reflect.ValueOf(bodyB).Call([]reflect.Value{reflect.ValueOf(node.data)}) - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go b/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go deleted file mode 100644 index 522d44e357..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/aggregator.go +++ /dev/null @@ -1,249 +0,0 @@ -/* - -Aggregator is a reporter used by the Ginkgo CLI to aggregate and present parallel test output -coherently as tests complete. You shouldn't need to use this in your code. To run tests in parallel: - - ginkgo -nodes=N - -where N is the number of nodes you desire. -*/ -package remote - -import ( - "time" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type configAndSuite struct { - config config.GinkgoConfigType - summary *types.SuiteSummary -} - -type Aggregator struct { - nodeCount int - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - result chan bool - - suiteBeginnings chan configAndSuite - aggregatedSuiteBeginnings []configAndSuite - - beforeSuites chan *types.SetupSummary - aggregatedBeforeSuites []*types.SetupSummary - - afterSuites chan *types.SetupSummary - aggregatedAfterSuites []*types.SetupSummary - - specCompletions chan *types.SpecSummary - completedSpecs []*types.SpecSummary - - suiteEndings chan *types.SuiteSummary - aggregatedSuiteEndings []*types.SuiteSummary - specs []*types.SpecSummary - - startTime time.Time -} - -func NewAggregator(nodeCount int, result chan bool, config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *Aggregator { - aggregator := &Aggregator{ - nodeCount: nodeCount, - result: result, - config: config, - stenographer: stenographer, - - suiteBeginnings: make(chan configAndSuite, 0), - beforeSuites: make(chan *types.SetupSummary, 0), - afterSuites: make(chan *types.SetupSummary, 0), - specCompletions: make(chan *types.SpecSummary, 0), - suiteEndings: make(chan *types.SuiteSummary, 0), - } - - go aggregator.mux() - - return aggregator -} - -func (aggregator *Aggregator) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - aggregator.suiteBeginnings <- configAndSuite{config, summary} -} - -func (aggregator *Aggregator) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.beforeSuites <- setupSummary -} - -func (aggregator *Aggregator) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - aggregator.afterSuites <- setupSummary -} - -func (aggregator *Aggregator) SpecWillRun(specSummary *types.SpecSummary) { - //noop -} - -func (aggregator *Aggregator) SpecDidComplete(specSummary *types.SpecSummary) { - aggregator.specCompletions <- specSummary -} - -func (aggregator *Aggregator) SpecSuiteDidEnd(summary *types.SuiteSummary) { - aggregator.suiteEndings <- summary -} - -func (aggregator *Aggregator) mux() { -loop: - for { - select { - case configAndSuite := <-aggregator.suiteBeginnings: - aggregator.registerSuiteBeginning(configAndSuite) - case setupSummary := <-aggregator.beforeSuites: - aggregator.registerBeforeSuite(setupSummary) - case setupSummary := <-aggregator.afterSuites: - aggregator.registerAfterSuite(setupSummary) - case specSummary := <-aggregator.specCompletions: - aggregator.registerSpecCompletion(specSummary) - case suite := <-aggregator.suiteEndings: - finished, passed := aggregator.registerSuiteEnding(suite) - if finished { - aggregator.result <- passed - break loop - } - } - } -} - -func (aggregator *Aggregator) registerSuiteBeginning(configAndSuite configAndSuite) { - aggregator.aggregatedSuiteBeginnings = append(aggregator.aggregatedSuiteBeginnings, configAndSuite) - - if len(aggregator.aggregatedSuiteBeginnings) == 1 { - aggregator.startTime = time.Now() - } - - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - aggregator.stenographer.AnnounceSuite(configAndSuite.summary.SuiteDescription, configAndSuite.config.RandomSeed, configAndSuite.config.RandomizeAllSpecs, aggregator.config.Succinct) - - totalNumberOfSpecs := 0 - if len(aggregator.aggregatedSuiteBeginnings) > 0 { - totalNumberOfSpecs = configAndSuite.summary.NumberOfSpecsBeforeParallelization - } - - aggregator.stenographer.AnnounceTotalNumberOfSpecs(totalNumberOfSpecs, aggregator.config.Succinct) - aggregator.stenographer.AnnounceAggregatedParallelRun(aggregator.nodeCount, aggregator.config.Succinct) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedBeforeSuites = append(aggregator.aggregatedBeforeSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerAfterSuite(setupSummary *types.SetupSummary) { - aggregator.aggregatedAfterSuites = append(aggregator.aggregatedAfterSuites, setupSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) registerSpecCompletion(specSummary *types.SpecSummary) { - aggregator.completedSpecs = append(aggregator.completedSpecs, specSummary) - aggregator.specs = append(aggregator.specs, specSummary) - aggregator.flushCompletedSpecs() -} - -func (aggregator *Aggregator) flushCompletedSpecs() { - if len(aggregator.aggregatedSuiteBeginnings) != aggregator.nodeCount { - return - } - - for _, setupSummary := range aggregator.aggregatedBeforeSuites { - aggregator.announceBeforeSuite(setupSummary) - } - - for _, specSummary := range aggregator.completedSpecs { - aggregator.announceSpec(specSummary) - } - - for _, setupSummary := range aggregator.aggregatedAfterSuites { - aggregator.announceAfterSuite(setupSummary) - } - - aggregator.aggregatedBeforeSuites = []*types.SetupSummary{} - aggregator.completedSpecs = []*types.SpecSummary{} - aggregator.aggregatedAfterSuites = []*types.SetupSummary{} -} - -func (aggregator *Aggregator) announceBeforeSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceBeforeSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceAfterSuite(setupSummary *types.SetupSummary) { - aggregator.stenographer.AnnounceCapturedOutput(setupSummary.CapturedOutput) - if setupSummary.State != types.SpecStatePassed { - aggregator.stenographer.AnnounceAfterSuiteFailure(setupSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) announceSpec(specSummary *types.SpecSummary) { - if aggregator.config.Verbose && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - aggregator.stenographer.AnnounceSpecWillRun(specSummary) - } - - aggregator.stenographer.AnnounceCapturedOutput(specSummary.CapturedOutput) - - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - aggregator.stenographer.AnnounceSuccesfulMeasurement(specSummary, aggregator.config.Succinct) - } else if specSummary.RunTime.Seconds() >= aggregator.config.SlowSpecThreshold { - aggregator.stenographer.AnnounceSuccesfulSlowSpec(specSummary, aggregator.config.Succinct) - } else { - aggregator.stenographer.AnnounceSuccesfulSpec(specSummary) - } - - case types.SpecStatePending: - aggregator.stenographer.AnnouncePendingSpec(specSummary, aggregator.config.NoisyPendings && !aggregator.config.Succinct) - case types.SpecStateSkipped: - aggregator.stenographer.AnnounceSkippedSpec(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStateTimedOut: - aggregator.stenographer.AnnounceSpecTimedOut(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStatePanicked: - aggregator.stenographer.AnnounceSpecPanicked(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - case types.SpecStateFailed: - aggregator.stenographer.AnnounceSpecFailed(specSummary, aggregator.config.Succinct, aggregator.config.FullTrace) - } -} - -func (aggregator *Aggregator) registerSuiteEnding(suite *types.SuiteSummary) (finished bool, passed bool) { - aggregator.aggregatedSuiteEndings = append(aggregator.aggregatedSuiteEndings, suite) - if len(aggregator.aggregatedSuiteEndings) < aggregator.nodeCount { - return false, false - } - - aggregatedSuiteSummary := &types.SuiteSummary{} - aggregatedSuiteSummary.SuiteSucceeded = true - - for _, suiteSummary := range aggregator.aggregatedSuiteEndings { - if suiteSummary.SuiteSucceeded == false { - aggregatedSuiteSummary.SuiteSucceeded = false - } - - aggregatedSuiteSummary.NumberOfSpecsThatWillBeRun += suiteSummary.NumberOfSpecsThatWillBeRun - aggregatedSuiteSummary.NumberOfTotalSpecs += suiteSummary.NumberOfTotalSpecs - aggregatedSuiteSummary.NumberOfPassedSpecs += suiteSummary.NumberOfPassedSpecs - aggregatedSuiteSummary.NumberOfFailedSpecs += suiteSummary.NumberOfFailedSpecs - aggregatedSuiteSummary.NumberOfPendingSpecs += suiteSummary.NumberOfPendingSpecs - aggregatedSuiteSummary.NumberOfSkippedSpecs += suiteSummary.NumberOfSkippedSpecs - aggregatedSuiteSummary.NumberOfFlakedSpecs += suiteSummary.NumberOfFlakedSpecs - } - - aggregatedSuiteSummary.RunTime = time.Since(aggregator.startTime) - - aggregator.stenographer.SummarizeFailures(aggregator.specs) - aggregator.stenographer.AnnounceSpecRunCompletion(aggregatedSuiteSummary, aggregator.config.Succinct) - - return true, aggregatedSuiteSummary.SuiteSucceeded -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go b/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go deleted file mode 100644 index 025eb50644..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/forwarding_reporter.go +++ /dev/null @@ -1,90 +0,0 @@ -package remote - -import ( - "bytes" - "encoding/json" - "io" - "net/http" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//An interface to net/http's client to allow the injection of fakes under test -type Poster interface { - Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) -} - -/* -The ForwardingReporter is a Ginkgo reporter that forwards information to -a Ginkgo remote server. - -When streaming parallel test output, this repoter is automatically installed by Ginkgo. - -This is accomplished by passing in the GINKGO_REMOTE_REPORTING_SERVER environment variable to `go test`, the Ginkgo test runner -detects this environment variable (which should contain the host of the server) and automatically installs a ForwardingReporter -in place of Ginkgo's DefaultReporter. -*/ - -type ForwardingReporter struct { - serverHost string - poster Poster - outputInterceptor OutputInterceptor -} - -func NewForwardingReporter(serverHost string, poster Poster, outputInterceptor OutputInterceptor) *ForwardingReporter { - return &ForwardingReporter{ - serverHost: serverHost, - poster: poster, - outputInterceptor: outputInterceptor, - } -} - -func (reporter *ForwardingReporter) post(path string, data interface{}) { - encoded, _ := json.Marshal(data) - buffer := bytes.NewBuffer(encoded) - reporter.poster.Post(reporter.serverHost+path, "application/json", buffer) -} - -func (reporter *ForwardingReporter) SpecSuiteWillBegin(conf config.GinkgoConfigType, summary *types.SuiteSummary) { - data := struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - }{ - conf, - summary, - } - - reporter.outputInterceptor.StartInterceptingOutput() - reporter.post("/SpecSuiteWillBegin", data) -} - -func (reporter *ForwardingReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - reporter.post("/BeforeSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecWillRun(specSummary *types.SpecSummary) { - reporter.post("/SpecWillRun", specSummary) -} - -func (reporter *ForwardingReporter) SpecDidComplete(specSummary *types.SpecSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - specSummary.CapturedOutput = output - reporter.post("/SpecDidComplete", specSummary) -} - -func (reporter *ForwardingReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - output, _ := reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.outputInterceptor.StartInterceptingOutput() - setupSummary.CapturedOutput = output - reporter.post("/AfterSuiteDidRun", setupSummary) -} - -func (reporter *ForwardingReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.outputInterceptor.StopInterceptingAndReturnOutput() - reporter.post("/SpecSuiteDidEnd", summary) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go deleted file mode 100644 index 093f4513c0..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor.go +++ /dev/null @@ -1,10 +0,0 @@ -package remote - -/* -The OutputInterceptor is used by the ForwardingReporter to -intercept and capture all stdin and stderr output during a test run. -*/ -type OutputInterceptor interface { - StartInterceptingOutput() error - StopInterceptingAndReturnOutput() (string, error) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go deleted file mode 100644 index 980065da57..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_unix.go +++ /dev/null @@ -1,55 +0,0 @@ -// +build freebsd openbsd netbsd dragonfly darwin linux solaris - -package remote - -import ( - "errors" - "io/ioutil" - "os" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - redirectFile *os.File - intercepting bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - var err error - - interceptor.redirectFile, err = ioutil.TempFile("", "ginkgo-output") - if err != nil { - return err - } - - // Call a function in ./syscall_dup_*.go - // If building for everything other than linux_arm64, - // use a "normal" syscall.Dup2(oldfd, newfd) call. If building for linux_arm64 (which doesn't have syscall.Dup2) - // call syscall.Dup3(oldfd, newfd, 0). They are nearly identical, see: http://linux.die.net/man/2/dup3 - syscallDup(int(interceptor.redirectFile.Fd()), 1) - syscallDup(int(interceptor.redirectFile.Fd()), 2) - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - if !interceptor.intercepting { - return "", errors.New("Not intercepting output!") - } - - interceptor.redirectFile.Close() - output, err := ioutil.ReadFile(interceptor.redirectFile.Name()) - os.Remove(interceptor.redirectFile.Name()) - - interceptor.intercepting = false - - return string(output), err -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go b/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go deleted file mode 100644 index c8f97d97f0..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/output_interceptor_win.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build windows - -package remote - -import ( - "errors" -) - -func NewOutputInterceptor() OutputInterceptor { - return &outputInterceptor{} -} - -type outputInterceptor struct { - intercepting bool -} - -func (interceptor *outputInterceptor) StartInterceptingOutput() error { - if interceptor.intercepting { - return errors.New("Already intercepting output!") - } - interceptor.intercepting = true - - // not working on windows... - - return nil -} - -func (interceptor *outputInterceptor) StopInterceptingAndReturnOutput() (string, error) { - // not working on windows... - interceptor.intercepting = false - - return "", nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/server.go b/vendor/github.com/onsi/ginkgo/internal/remote/server.go deleted file mode 100644 index 297af2ebff..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/server.go +++ /dev/null @@ -1,224 +0,0 @@ -/* - -The remote package provides the pieces to allow Ginkgo test suites to report to remote listeners. -This is used, primarily, to enable streaming parallel test output but has, in principal, broader applications (e.g. streaming test output to a browser). - -*/ - -package remote - -import ( - "encoding/json" - "io/ioutil" - "net" - "net/http" - "sync" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -/* -Server spins up on an automatically selected port and listens for communication from the forwarding reporter. -It then forwards that communication to attached reporters. -*/ -type Server struct { - listener net.Listener - reporters []reporters.Reporter - alives []func() bool - lock *sync.Mutex - beforeSuiteData types.RemoteBeforeSuiteData - parallelTotal int - counter int -} - -//Create a new server, automatically selecting a port -func NewServer(parallelTotal int) (*Server, error) { - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return nil, err - } - return &Server{ - listener: listener, - lock: &sync.Mutex{}, - alives: make([]func() bool, parallelTotal), - beforeSuiteData: types.RemoteBeforeSuiteData{nil, types.RemoteBeforeSuiteStatePending}, - parallelTotal: parallelTotal, - }, nil -} - -//Start the server. You don't need to `go s.Start()`, just `s.Start()` -func (server *Server) Start() { - httpServer := &http.Server{} - mux := http.NewServeMux() - httpServer.Handler = mux - - //streaming endpoints - mux.HandleFunc("/SpecSuiteWillBegin", server.specSuiteWillBegin) - mux.HandleFunc("/BeforeSuiteDidRun", server.beforeSuiteDidRun) - mux.HandleFunc("/AfterSuiteDidRun", server.afterSuiteDidRun) - mux.HandleFunc("/SpecWillRun", server.specWillRun) - mux.HandleFunc("/SpecDidComplete", server.specDidComplete) - mux.HandleFunc("/SpecSuiteDidEnd", server.specSuiteDidEnd) - - //synchronization endpoints - mux.HandleFunc("/BeforeSuiteState", server.handleBeforeSuiteState) - mux.HandleFunc("/RemoteAfterSuiteData", server.handleRemoteAfterSuiteData) - mux.HandleFunc("/counter", server.handleCounter) - mux.HandleFunc("/has-counter", server.handleHasCounter) //for backward compatibility - - go httpServer.Serve(server.listener) -} - -//Stop the server -func (server *Server) Close() { - server.listener.Close() -} - -//The address the server can be reached it. Pass this into the `ForwardingReporter`. -func (server *Server) Address() string { - return "http://" + server.listener.Addr().String() -} - -// -// Streaming Endpoints -// - -//The server will forward all received messages to Ginkgo reporters registered with `RegisterReporters` -func (server *Server) readAll(request *http.Request) []byte { - defer request.Body.Close() - body, _ := ioutil.ReadAll(request.Body) - return body -} - -func (server *Server) RegisterReporters(reporters ...reporters.Reporter) { - server.reporters = reporters -} - -func (server *Server) specSuiteWillBegin(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - - var data struct { - Config config.GinkgoConfigType `json:"config"` - Summary *types.SuiteSummary `json:"suite-summary"` - } - - json.Unmarshal(body, &data) - - for _, reporter := range server.reporters { - reporter.SpecSuiteWillBegin(data.Config, data.Summary) - } -} - -func (server *Server) beforeSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.BeforeSuiteDidRun(setupSummary) - } -} - -func (server *Server) afterSuiteDidRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var setupSummary *types.SetupSummary - json.Unmarshal(body, &setupSummary) - - for _, reporter := range server.reporters { - reporter.AfterSuiteDidRun(setupSummary) - } -} - -func (server *Server) specWillRun(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecWillRun(specSummary) - } -} - -func (server *Server) specDidComplete(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var specSummary *types.SpecSummary - json.Unmarshal(body, &specSummary) - - for _, reporter := range server.reporters { - reporter.SpecDidComplete(specSummary) - } -} - -func (server *Server) specSuiteDidEnd(writer http.ResponseWriter, request *http.Request) { - body := server.readAll(request) - var suiteSummary *types.SuiteSummary - json.Unmarshal(body, &suiteSummary) - - for _, reporter := range server.reporters { - reporter.SpecSuiteDidEnd(suiteSummary) - } -} - -// -// Synchronization Endpoints -// - -func (server *Server) RegisterAlive(node int, alive func() bool) { - server.lock.Lock() - defer server.lock.Unlock() - server.alives[node-1] = alive -} - -func (server *Server) nodeIsAlive(node int) bool { - server.lock.Lock() - defer server.lock.Unlock() - alive := server.alives[node-1] - if alive == nil { - return true - } - return alive() -} - -func (server *Server) handleBeforeSuiteState(writer http.ResponseWriter, request *http.Request) { - if request.Method == "POST" { - dec := json.NewDecoder(request.Body) - dec.Decode(&(server.beforeSuiteData)) - } else { - beforeSuiteData := server.beforeSuiteData - if beforeSuiteData.State == types.RemoteBeforeSuiteStatePending && !server.nodeIsAlive(1) { - beforeSuiteData.State = types.RemoteBeforeSuiteStateDisappeared - } - enc := json.NewEncoder(writer) - enc.Encode(beforeSuiteData) - } -} - -func (server *Server) handleRemoteAfterSuiteData(writer http.ResponseWriter, request *http.Request) { - afterSuiteData := types.RemoteAfterSuiteData{ - CanRun: true, - } - for i := 2; i <= server.parallelTotal; i++ { - afterSuiteData.CanRun = afterSuiteData.CanRun && !server.nodeIsAlive(i) - } - - enc := json.NewEncoder(writer) - enc.Encode(afterSuiteData) -} - -func (server *Server) handleCounter(writer http.ResponseWriter, request *http.Request) { - c := spec_iterator.Counter{} - server.lock.Lock() - c.Index = server.counter - server.counter = server.counter + 1 - server.lock.Unlock() - - json.NewEncoder(writer).Encode(c) -} - -func (server *Server) handleHasCounter(writer http.ResponseWriter, request *http.Request) { - writer.Write([]byte("")) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go deleted file mode 100644 index 5c59728ea9..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_linux_arm64.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build linux,arm64 - -package remote - -import "syscall" - -// linux_arm64 doesn't have syscall.Dup2 which ginkgo uses, so -// use the nearly identical syscall.Dup3 instead -func syscallDup(oldfd int, newfd int) (err error) { - return syscall.Dup3(oldfd, newfd, 0) -} \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go deleted file mode 100644 index ecf9cafb66..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_solaris.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build solaris - -package remote - -import "golang.org/x/sys/unix" - -func syscallDup(oldfd int, newfd int) (err error) { - return unix.Dup2(oldfd, newfd) -} \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go b/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go deleted file mode 100644 index cacdd0e649..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/remote/syscall_dup_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !linux !arm64 -// +build !windows -// +build !solaris - -package remote - -import "syscall" - -func syscallDup(oldfd int, newfd int) (err error) { - return syscall.Dup2(oldfd, newfd) -} \ No newline at end of file diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go b/vendor/github.com/onsi/ginkgo/internal/spec/spec.go deleted file mode 100644 index d32dec6997..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/spec.go +++ /dev/null @@ -1,206 +0,0 @@ -package spec - -import ( - "fmt" - "io" - "time" - - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/types" -) - -type Spec struct { - subject leafnodes.SubjectNode - focused bool - announceProgress bool - - containers []*containernode.ContainerNode - - state types.SpecState - runTime time.Duration - failure types.SpecFailure - previousFailures bool -} - -func New(subject leafnodes.SubjectNode, containers []*containernode.ContainerNode, announceProgress bool) *Spec { - spec := &Spec{ - subject: subject, - containers: containers, - focused: subject.Flag() == types.FlagTypeFocused, - announceProgress: announceProgress, - } - - spec.processFlag(subject.Flag()) - for i := len(containers) - 1; i >= 0; i-- { - spec.processFlag(containers[i].Flag()) - } - - return spec -} - -func (spec *Spec) processFlag(flag types.FlagType) { - if flag == types.FlagTypeFocused { - spec.focused = true - } else if flag == types.FlagTypePending { - spec.state = types.SpecStatePending - } -} - -func (spec *Spec) Skip() { - spec.state = types.SpecStateSkipped -} - -func (spec *Spec) Failed() bool { - return spec.state == types.SpecStateFailed || spec.state == types.SpecStatePanicked || spec.state == types.SpecStateTimedOut -} - -func (spec *Spec) Passed() bool { - return spec.state == types.SpecStatePassed -} - -func (spec *Spec) Flaked() bool { - return spec.state == types.SpecStatePassed && spec.previousFailures -} - -func (spec *Spec) Pending() bool { - return spec.state == types.SpecStatePending -} - -func (spec *Spec) Skipped() bool { - return spec.state == types.SpecStateSkipped -} - -func (spec *Spec) Focused() bool { - return spec.focused -} - -func (spec *Spec) IsMeasurement() bool { - return spec.subject.Type() == types.SpecComponentTypeMeasure -} - -func (spec *Spec) Summary(suiteID string) *types.SpecSummary { - componentTexts := make([]string, len(spec.containers)+1) - componentCodeLocations := make([]types.CodeLocation, len(spec.containers)+1) - - for i, container := range spec.containers { - componentTexts[i] = container.Text() - componentCodeLocations[i] = container.CodeLocation() - } - - componentTexts[len(spec.containers)] = spec.subject.Text() - componentCodeLocations[len(spec.containers)] = spec.subject.CodeLocation() - - return &types.SpecSummary{ - IsMeasurement: spec.IsMeasurement(), - NumberOfSamples: spec.subject.Samples(), - ComponentTexts: componentTexts, - ComponentCodeLocations: componentCodeLocations, - State: spec.state, - RunTime: spec.runTime, - Failure: spec.failure, - Measurements: spec.measurementsReport(), - SuiteID: suiteID, - } -} - -func (spec *Spec) ConcatenatedString() string { - s := "" - for _, container := range spec.containers { - s += container.Text() + " " - } - - return s + spec.subject.Text() -} - -func (spec *Spec) Run(writer io.Writer) { - if spec.state == types.SpecStateFailed { - spec.previousFailures = true - } - - startTime := time.Now() - defer func() { - spec.runTime = time.Since(startTime) - }() - - for sample := 0; sample < spec.subject.Samples(); sample++ { - spec.runSample(sample, writer) - - if spec.state != types.SpecStatePassed { - return - } - } -} - -func (spec *Spec) runSample(sample int, writer io.Writer) { - spec.state = types.SpecStatePassed - spec.failure = types.SpecFailure{} - innerMostContainerIndexToUnwind := -1 - - defer func() { - for i := innerMostContainerIndexToUnwind; i >= 0; i-- { - container := spec.containers[i] - for _, afterEach := range container.SetupNodesOfType(types.SpecComponentTypeAfterEach) { - spec.announceSetupNode(writer, "AfterEach", container, afterEach) - afterEachState, afterEachFailure := afterEach.Run() - if afterEachState != types.SpecStatePassed && spec.state == types.SpecStatePassed { - spec.state = afterEachState - spec.failure = afterEachFailure - } - } - } - }() - - for i, container := range spec.containers { - innerMostContainerIndexToUnwind = i - for _, beforeEach := range container.SetupNodesOfType(types.SpecComponentTypeBeforeEach) { - spec.announceSetupNode(writer, "BeforeEach", container, beforeEach) - spec.state, spec.failure = beforeEach.Run() - if spec.state != types.SpecStatePassed { - return - } - } - } - - for _, container := range spec.containers { - for _, justBeforeEach := range container.SetupNodesOfType(types.SpecComponentTypeJustBeforeEach) { - spec.announceSetupNode(writer, "JustBeforeEach", container, justBeforeEach) - spec.state, spec.failure = justBeforeEach.Run() - if spec.state != types.SpecStatePassed { - return - } - } - } - - spec.announceSubject(writer, spec.subject) - spec.state, spec.failure = spec.subject.Run() -} - -func (spec *Spec) announceSetupNode(writer io.Writer, nodeType string, container *containernode.ContainerNode, setupNode leafnodes.BasicNode) { - if spec.announceProgress { - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, container.Text(), setupNode.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) announceSubject(writer io.Writer, subject leafnodes.SubjectNode) { - if spec.announceProgress { - nodeType := "" - switch subject.Type() { - case types.SpecComponentTypeIt: - nodeType = "It" - case types.SpecComponentTypeMeasure: - nodeType = "Measure" - } - s := fmt.Sprintf("[%s] %s\n %s\n", nodeType, subject.Text(), subject.CodeLocation().String()) - writer.Write([]byte(s)) - } -} - -func (spec *Spec) measurementsReport() map[string]*types.SpecMeasurement { - if !spec.IsMeasurement() || spec.Failed() { - return map[string]*types.SpecMeasurement{} - } - - return spec.subject.(*leafnodes.MeasureNode).MeasurementsReport() -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec/specs.go b/vendor/github.com/onsi/ginkgo/internal/spec/specs.go deleted file mode 100644 index 006185ab5d..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec/specs.go +++ /dev/null @@ -1,123 +0,0 @@ -package spec - -import ( - "math/rand" - "regexp" - "sort" -) - -type Specs struct { - specs []*Spec - hasProgrammaticFocus bool - RegexScansFilePath bool -} - -func NewSpecs(specs []*Spec) *Specs { - return &Specs{ - specs: specs, - } -} - -func (e *Specs) Specs() []*Spec { - return e.specs -} - -func (e *Specs) HasProgrammaticFocus() bool { - return e.hasProgrammaticFocus -} - -func (e *Specs) Shuffle(r *rand.Rand) { - sort.Sort(e) - permutation := r.Perm(len(e.specs)) - shuffledSpecs := make([]*Spec, len(e.specs)) - for i, j := range permutation { - shuffledSpecs[i] = e.specs[j] - } - e.specs = shuffledSpecs -} - -func (e *Specs) ApplyFocus(description string, focusString string, skipString string) { - if focusString == "" && skipString == "" { - e.applyProgrammaticFocus() - } else { - e.applyRegExpFocusAndSkip(description, focusString, skipString) - } -} - -func (e *Specs) applyProgrammaticFocus() { - e.hasProgrammaticFocus = false - for _, spec := range e.specs { - if spec.Focused() && !spec.Pending() { - e.hasProgrammaticFocus = true - break - } - } - - if e.hasProgrammaticFocus { - for _, spec := range e.specs { - if !spec.Focused() { - spec.Skip() - } - } - } -} - -// toMatch returns a byte[] to be used by regex matchers. When adding new behaviours to the matching function, -// this is the place which we append to. -func (e *Specs) toMatch(description string, spec *Spec) []byte { - if e.RegexScansFilePath { - return []byte( - description + " " + - spec.ConcatenatedString() + " " + - spec.subject.CodeLocation().FileName) - } else { - return []byte( - description + " " + - spec.ConcatenatedString()) - } -} - -func (e *Specs) applyRegExpFocusAndSkip(description string, focusString string, skipString string) { - for _, spec := range e.specs { - matchesFocus := true - matchesSkip := false - - toMatch := e.toMatch(description, spec) - - if focusString != "" { - focusFilter := regexp.MustCompile(focusString) - matchesFocus = focusFilter.Match([]byte(toMatch)) - } - - if skipString != "" { - skipFilter := regexp.MustCompile(skipString) - matchesSkip = skipFilter.Match([]byte(toMatch)) - } - - if !matchesFocus || matchesSkip { - spec.Skip() - } - } -} - -func (e *Specs) SkipMeasurements() { - for _, spec := range e.specs { - if spec.IsMeasurement() { - spec.Skip() - } - } -} - -//sort.Interface - -func (e *Specs) Len() int { - return len(e.specs) -} - -func (e *Specs) Less(i, j int) bool { - return e.specs[i].ConcatenatedString() < e.specs[j].ConcatenatedString() -} - -func (e *Specs) Swap(i, j int) { - e.specs[i], e.specs[j] = e.specs[j], e.specs[i] -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go deleted file mode 100644 index 82272554aa..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/index_computer.go +++ /dev/null @@ -1,55 +0,0 @@ -package spec_iterator - -func ParallelizedIndexRange(length int, parallelTotal int, parallelNode int) (startIndex int, count int) { - if length == 0 { - return 0, 0 - } - - // We have more nodes than tests. Trivial case. - if parallelTotal >= length { - if parallelNode > length { - return 0, 0 - } else { - return parallelNode - 1, 1 - } - } - - // This is the minimum amount of tests that a node will be required to run - minTestsPerNode := length / parallelTotal - - // This is the maximum amount of tests that a node will be required to run - // The algorithm guarantees that this would be equal to at least the minimum amount - // and at most one more - maxTestsPerNode := minTestsPerNode - if length%parallelTotal != 0 { - maxTestsPerNode++ - } - - // Number of nodes that will have to run the maximum amount of tests per node - numMaxLoadNodes := length % parallelTotal - - // Number of nodes that precede the current node and will have to run the maximum amount of tests per node - var numPrecedingMaxLoadNodes int - if parallelNode > numMaxLoadNodes { - numPrecedingMaxLoadNodes = numMaxLoadNodes - } else { - numPrecedingMaxLoadNodes = parallelNode - 1 - } - - // Number of nodes that precede the current node and will have to run the minimum amount of tests per node - var numPrecedingMinLoadNodes int - if parallelNode <= numMaxLoadNodes { - numPrecedingMinLoadNodes = 0 - } else { - numPrecedingMinLoadNodes = parallelNode - numMaxLoadNodes - 1 - } - - // Evaluate the test start index and number of tests to run - startIndex = numPrecedingMaxLoadNodes*maxTestsPerNode + numPrecedingMinLoadNodes*minTestsPerNode - if parallelNode > numMaxLoadNodes { - count = minTestsPerNode - } else { - count = maxTestsPerNode - } - return -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go deleted file mode 100644 index 54e61ecb46..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/parallel_spec_iterator.go +++ /dev/null @@ -1,60 +0,0 @@ -package spec_iterator - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - - "github.com/onsi/ginkgo/internal/spec" -) - -type ParallelIterator struct { - specs []*spec.Spec - host string - client *http.Client -} - -func NewParallelIterator(specs []*spec.Spec, host string) *ParallelIterator { - return &ParallelIterator{ - specs: specs, - host: host, - client: &http.Client{}, - } -} - -func (s *ParallelIterator) Next() (*spec.Spec, error) { - resp, err := s.client.Get(s.host + "/counter") - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, errors.New(fmt.Sprintf("unexpected status code %d", resp.StatusCode)) - } - - var counter Counter - err = json.NewDecoder(resp.Body).Decode(&counter) - if err != nil { - return nil, err - } - - if counter.Index >= len(s.specs) { - return nil, ErrClosed - } - - return s.specs[counter.Index], nil -} - -func (s *ParallelIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *ParallelIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return -1, false -} - -func (s *ParallelIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - return -1, false -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go deleted file mode 100644 index a51c93b8b6..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/serial_spec_iterator.go +++ /dev/null @@ -1,45 +0,0 @@ -package spec_iterator - -import ( - "github.com/onsi/ginkgo/internal/spec" -) - -type SerialIterator struct { - specs []*spec.Spec - index int -} - -func NewSerialIterator(specs []*spec.Spec) *SerialIterator { - return &SerialIterator{ - specs: specs, - index: 0, - } -} - -func (s *SerialIterator) Next() (*spec.Spec, error) { - if s.index >= len(s.specs) { - return nil, ErrClosed - } - - spec := s.specs[s.index] - s.index += 1 - return spec, nil -} - -func (s *SerialIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *SerialIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return len(s.specs), true -} - -func (s *SerialIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - count := 0 - for _, s := range s.specs { - if !s.Skipped() && !s.Pending() { - count += 1 - } - } - return count, true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go deleted file mode 100644 index ad4a3ea3c6..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/sharded_parallel_spec_iterator.go +++ /dev/null @@ -1,47 +0,0 @@ -package spec_iterator - -import "github.com/onsi/ginkgo/internal/spec" - -type ShardedParallelIterator struct { - specs []*spec.Spec - index int - maxIndex int -} - -func NewShardedParallelIterator(specs []*spec.Spec, total int, node int) *ShardedParallelIterator { - startIndex, count := ParallelizedIndexRange(len(specs), total, node) - - return &ShardedParallelIterator{ - specs: specs, - index: startIndex, - maxIndex: startIndex + count, - } -} - -func (s *ShardedParallelIterator) Next() (*spec.Spec, error) { - if s.index >= s.maxIndex { - return nil, ErrClosed - } - - spec := s.specs[s.index] - s.index += 1 - return spec, nil -} - -func (s *ShardedParallelIterator) NumberOfSpecsPriorToIteration() int { - return len(s.specs) -} - -func (s *ShardedParallelIterator) NumberOfSpecsToProcessIfKnown() (int, bool) { - return s.maxIndex - s.index, true -} - -func (s *ShardedParallelIterator) NumberOfSpecsThatWillBeRunIfKnown() (int, bool) { - count := 0 - for i := s.index; i < s.maxIndex; i += 1 { - if !s.specs[i].Skipped() && !s.specs[i].Pending() { - count += 1 - } - } - return count, true -} diff --git a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go b/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go deleted file mode 100644 index 74bffad646..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/spec_iterator/spec_iterator.go +++ /dev/null @@ -1,20 +0,0 @@ -package spec_iterator - -import ( - "errors" - - "github.com/onsi/ginkgo/internal/spec" -) - -var ErrClosed = errors.New("no more specs to run") - -type SpecIterator interface { - Next() (*spec.Spec, error) - NumberOfSpecsPriorToIteration() int - NumberOfSpecsToProcessIfKnown() (int, bool) - NumberOfSpecsThatWillBeRunIfKnown() (int, bool) -} - -type Counter struct { - Index int `json:"index"` -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go deleted file mode 100644 index a0b8b62d52..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/random_id.go +++ /dev/null @@ -1,15 +0,0 @@ -package specrunner - -import ( - "crypto/rand" - "fmt" -) - -func randomID() string { - b := make([]byte, 8) - _, err := rand.Read(b) - if err != nil { - return "" - } - return fmt.Sprintf("%x-%x-%x-%x", b[0:2], b[2:4], b[4:6], b[6:8]) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go b/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go deleted file mode 100644 index d4dd909ecf..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/specrunner/spec_runner.go +++ /dev/null @@ -1,408 +0,0 @@ -package specrunner - -import ( - "fmt" - "os" - "os/signal" - "sync" - "syscall" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - Writer "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" - - "time" -) - -type SpecRunner struct { - description string - beforeSuiteNode leafnodes.SuiteNode - iterator spec_iterator.SpecIterator - afterSuiteNode leafnodes.SuiteNode - reporters []reporters.Reporter - startTime time.Time - suiteID string - runningSpec *spec.Spec - writer Writer.WriterInterface - config config.GinkgoConfigType - interrupted bool - processedSpecs []*spec.Spec - lock *sync.Mutex -} - -func New(description string, beforeSuiteNode leafnodes.SuiteNode, iterator spec_iterator.SpecIterator, afterSuiteNode leafnodes.SuiteNode, reporters []reporters.Reporter, writer Writer.WriterInterface, config config.GinkgoConfigType) *SpecRunner { - return &SpecRunner{ - description: description, - beforeSuiteNode: beforeSuiteNode, - iterator: iterator, - afterSuiteNode: afterSuiteNode, - reporters: reporters, - writer: writer, - config: config, - suiteID: randomID(), - lock: &sync.Mutex{}, - } -} - -func (runner *SpecRunner) Run() bool { - if runner.config.DryRun { - runner.performDryRun() - return true - } - - runner.reportSuiteWillBegin() - go runner.registerForInterrupts() - - suitePassed := runner.runBeforeSuite() - - if suitePassed { - suitePassed = runner.runSpecs() - } - - runner.blockForeverIfInterrupted() - - suitePassed = runner.runAfterSuite() && suitePassed - - runner.reportSuiteDidEnd(suitePassed) - - return suitePassed -} - -func (runner *SpecRunner) performDryRun() { - runner.reportSuiteWillBegin() - - if runner.beforeSuiteNode != nil { - summary := runner.beforeSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportBeforeSuite(summary) - } - - for { - spec, err := runner.iterator.Next() - if err == spec_iterator.ErrClosed { - break - } - if err != nil { - fmt.Println("failed to iterate over tests:\n" + err.Error()) - break - } - - runner.processedSpecs = append(runner.processedSpecs, spec) - - summary := spec.Summary(runner.suiteID) - runner.reportSpecWillRun(summary) - if summary.State == types.SpecStateInvalid { - summary.State = types.SpecStatePassed - } - runner.reportSpecDidComplete(summary, false) - } - - if runner.afterSuiteNode != nil { - summary := runner.afterSuiteNode.Summary() - summary.State = types.SpecStatePassed - runner.reportAfterSuite(summary) - } - - runner.reportSuiteDidEnd(true) -} - -func (runner *SpecRunner) runBeforeSuite() bool { - if runner.beforeSuiteNode == nil || runner.wasInterrupted() { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.beforeSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportBeforeSuite(runner.beforeSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runAfterSuite() bool { - if runner.afterSuiteNode == nil { - return true - } - - runner.writer.Truncate() - conf := runner.config - passed := runner.afterSuiteNode.Run(conf.ParallelNode, conf.ParallelTotal, conf.SyncHost) - if !passed { - runner.writer.DumpOut() - } - runner.reportAfterSuite(runner.afterSuiteNode.Summary()) - return passed -} - -func (runner *SpecRunner) runSpecs() bool { - suiteFailed := false - skipRemainingSpecs := false - for { - spec, err := runner.iterator.Next() - if err == spec_iterator.ErrClosed { - break - } - if err != nil { - fmt.Println("failed to iterate over tests:\n" + err.Error()) - suiteFailed = true - break - } - - runner.processedSpecs = append(runner.processedSpecs, spec) - - if runner.wasInterrupted() { - break - } - if skipRemainingSpecs { - spec.Skip() - } - - if !spec.Skipped() && !spec.Pending() { - if passed := runner.runSpec(spec); !passed { - suiteFailed = true - } - } else if spec.Pending() && runner.config.FailOnPending { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - suiteFailed = true - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - } else { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - } - - if spec.Failed() && runner.config.FailFast { - skipRemainingSpecs = true - } - } - - return !suiteFailed -} - -func (runner *SpecRunner) runSpec(spec *spec.Spec) (passed bool) { - maxAttempts := 1 - if runner.config.FlakeAttempts > 0 { - // uninitialized configs count as 1 - maxAttempts = runner.config.FlakeAttempts - } - - for i := 0; i < maxAttempts; i++ { - runner.reportSpecWillRun(spec.Summary(runner.suiteID)) - runner.runningSpec = spec - spec.Run(runner.writer) - runner.runningSpec = nil - runner.reportSpecDidComplete(spec.Summary(runner.suiteID), spec.Failed()) - if !spec.Failed() { - return true - } - } - return false -} - -func (runner *SpecRunner) CurrentSpecSummary() (*types.SpecSummary, bool) { - if runner.runningSpec == nil { - return nil, false - } - - return runner.runningSpec.Summary(runner.suiteID), true -} - -func (runner *SpecRunner) registerForInterrupts() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - signal.Stop(c) - runner.markInterrupted() - go runner.registerForHardInterrupts() - runner.writer.DumpOutWithHeader(` -Received interrupt. Emitting contents of GinkgoWriter... ---------------------------------------------------------- -`) - if runner.afterSuiteNode != nil { - fmt.Fprint(os.Stderr, ` ---------------------------------------------------------- -Received interrupt. Running AfterSuite... -^C again to terminate immediately -`) - runner.runAfterSuite() - } - runner.reportSuiteDidEnd(false) - os.Exit(1) -} - -func (runner *SpecRunner) registerForHardInterrupts() { - c := make(chan os.Signal, 1) - signal.Notify(c, os.Interrupt, syscall.SIGTERM) - - <-c - fmt.Fprintln(os.Stderr, "\nReceived second interrupt. Shutting down.") - os.Exit(1) -} - -func (runner *SpecRunner) blockForeverIfInterrupted() { - runner.lock.Lock() - interrupted := runner.interrupted - runner.lock.Unlock() - - if interrupted { - select {} - } -} - -func (runner *SpecRunner) markInterrupted() { - runner.lock.Lock() - defer runner.lock.Unlock() - runner.interrupted = true -} - -func (runner *SpecRunner) wasInterrupted() bool { - runner.lock.Lock() - defer runner.lock.Unlock() - return runner.interrupted -} - -func (runner *SpecRunner) reportSuiteWillBegin() { - runner.startTime = time.Now() - summary := runner.suiteWillBeginSummary() - for _, reporter := range runner.reporters { - reporter.SpecSuiteWillBegin(runner.config, summary) - } -} - -func (runner *SpecRunner) reportBeforeSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.BeforeSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportAfterSuite(summary *types.SetupSummary) { - for _, reporter := range runner.reporters { - reporter.AfterSuiteDidRun(summary) - } -} - -func (runner *SpecRunner) reportSpecWillRun(summary *types.SpecSummary) { - runner.writer.Truncate() - - for _, reporter := range runner.reporters { - reporter.SpecWillRun(summary) - } -} - -func (runner *SpecRunner) reportSpecDidComplete(summary *types.SpecSummary, failed bool) { - if failed && len(summary.CapturedOutput) == 0 { - summary.CapturedOutput = string(runner.writer.Bytes()) - } - for i := len(runner.reporters) - 1; i >= 1; i-- { - runner.reporters[i].SpecDidComplete(summary) - } - - if failed { - runner.writer.DumpOut() - } - - runner.reporters[0].SpecDidComplete(summary) -} - -func (runner *SpecRunner) reportSuiteDidEnd(success bool) { - summary := runner.suiteDidEndSummary(success) - summary.RunTime = time.Since(runner.startTime) - for _, reporter := range runner.reporters { - reporter.SpecSuiteDidEnd(summary) - } -} - -func (runner *SpecRunner) countSpecsThatRanSatisfying(filter func(ex *spec.Spec) bool) (count int) { - count = 0 - - for _, spec := range runner.processedSpecs { - if filter(spec) { - count++ - } - } - - return count -} - -func (runner *SpecRunner) suiteDidEndSummary(success bool) *types.SuiteSummary { - numberOfSpecsThatWillBeRun := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return !ex.Skipped() && !ex.Pending() - }) - - numberOfPendingSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Pending() - }) - - numberOfSkippedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Skipped() - }) - - numberOfPassedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Passed() - }) - - numberOfFlakedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Flaked() - }) - - numberOfFailedSpecs := runner.countSpecsThatRanSatisfying(func(ex *spec.Spec) bool { - return ex.Failed() - }) - - if runner.beforeSuiteNode != nil && !runner.beforeSuiteNode.Passed() && !runner.config.DryRun { - var known bool - numberOfSpecsThatWillBeRun, known = runner.iterator.NumberOfSpecsThatWillBeRunIfKnown() - if !known { - numberOfSpecsThatWillBeRun = runner.iterator.NumberOfSpecsPriorToIteration() - } - numberOfFailedSpecs = numberOfSpecsThatWillBeRun - } - - return &types.SuiteSummary{ - SuiteDescription: runner.description, - SuiteSucceeded: success, - SuiteID: runner.suiteID, - - NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(), - NumberOfTotalSpecs: len(runner.processedSpecs), - NumberOfSpecsThatWillBeRun: numberOfSpecsThatWillBeRun, - NumberOfPendingSpecs: numberOfPendingSpecs, - NumberOfSkippedSpecs: numberOfSkippedSpecs, - NumberOfPassedSpecs: numberOfPassedSpecs, - NumberOfFailedSpecs: numberOfFailedSpecs, - NumberOfFlakedSpecs: numberOfFlakedSpecs, - } -} - -func (runner *SpecRunner) suiteWillBeginSummary() *types.SuiteSummary { - numTotal, known := runner.iterator.NumberOfSpecsToProcessIfKnown() - if !known { - numTotal = -1 - } - - numToRun, known := runner.iterator.NumberOfSpecsThatWillBeRunIfKnown() - if !known { - numToRun = -1 - } - - return &types.SuiteSummary{ - SuiteDescription: runner.description, - SuiteID: runner.suiteID, - - NumberOfSpecsBeforeParallelization: runner.iterator.NumberOfSpecsPriorToIteration(), - NumberOfTotalSpecs: numTotal, - NumberOfSpecsThatWillBeRun: numToRun, - NumberOfPendingSpecs: -1, - NumberOfSkippedSpecs: -1, - NumberOfPassedSpecs: -1, - NumberOfFailedSpecs: -1, - NumberOfFlakedSpecs: -1, - } -} diff --git a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go b/vendor/github.com/onsi/ginkgo/internal/suite/suite.go deleted file mode 100644 index 698a6e5689..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/suite/suite.go +++ /dev/null @@ -1,183 +0,0 @@ -package suite - -import ( - "math/rand" - "net/http" - "time" - - "github.com/onsi/ginkgo/internal/spec_iterator" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/internal/containernode" - "github.com/onsi/ginkgo/internal/failer" - "github.com/onsi/ginkgo/internal/leafnodes" - "github.com/onsi/ginkgo/internal/spec" - "github.com/onsi/ginkgo/internal/specrunner" - "github.com/onsi/ginkgo/internal/writer" - "github.com/onsi/ginkgo/reporters" - "github.com/onsi/ginkgo/types" -) - -type ginkgoTestingT interface { - Fail() -} - -type Suite struct { - topLevelContainer *containernode.ContainerNode - currentContainer *containernode.ContainerNode - containerIndex int - beforeSuiteNode leafnodes.SuiteNode - afterSuiteNode leafnodes.SuiteNode - runner *specrunner.SpecRunner - failer *failer.Failer - running bool -} - -func New(failer *failer.Failer) *Suite { - topLevelContainer := containernode.New("[Top Level]", types.FlagTypeNone, types.CodeLocation{}) - - return &Suite{ - topLevelContainer: topLevelContainer, - currentContainer: topLevelContainer, - failer: failer, - containerIndex: 1, - } -} - -func (suite *Suite) Run(t ginkgoTestingT, description string, reporters []reporters.Reporter, writer writer.WriterInterface, config config.GinkgoConfigType) (bool, bool) { - if config.ParallelTotal < 1 { - panic("ginkgo.parallel.total must be >= 1") - } - - if config.ParallelNode > config.ParallelTotal || config.ParallelNode < 1 { - panic("ginkgo.parallel.node is one-indexed and must be <= ginkgo.parallel.total") - } - - r := rand.New(rand.NewSource(config.RandomSeed)) - suite.topLevelContainer.Shuffle(r) - iterator, hasProgrammaticFocus := suite.generateSpecsIterator(description, config) - suite.runner = specrunner.New(description, suite.beforeSuiteNode, iterator, suite.afterSuiteNode, reporters, writer, config) - - suite.running = true - success := suite.runner.Run() - if !success { - t.Fail() - } - return success, hasProgrammaticFocus -} - -func (suite *Suite) generateSpecsIterator(description string, config config.GinkgoConfigType) (spec_iterator.SpecIterator, bool) { - specsSlice := []*spec.Spec{} - suite.topLevelContainer.BackPropagateProgrammaticFocus() - for _, collatedNodes := range suite.topLevelContainer.Collate() { - specsSlice = append(specsSlice, spec.New(collatedNodes.Subject, collatedNodes.Containers, config.EmitSpecProgress)) - } - - specs := spec.NewSpecs(specsSlice) - specs.RegexScansFilePath = config.RegexScansFilePath - - if config.RandomizeAllSpecs { - specs.Shuffle(rand.New(rand.NewSource(config.RandomSeed))) - } - - specs.ApplyFocus(description, config.FocusString, config.SkipString) - - if config.SkipMeasurements { - specs.SkipMeasurements() - } - - var iterator spec_iterator.SpecIterator - - if config.ParallelTotal > 1 { - iterator = spec_iterator.NewParallelIterator(specs.Specs(), config.SyncHost) - resp, err := http.Get(config.SyncHost + "/has-counter") - if err != nil || resp.StatusCode != http.StatusOK { - iterator = spec_iterator.NewShardedParallelIterator(specs.Specs(), config.ParallelTotal, config.ParallelNode) - } - } else { - iterator = spec_iterator.NewSerialIterator(specs.Specs()) - } - - return iterator, specs.HasProgrammaticFocus() -} - -func (suite *Suite) CurrentRunningSpecSummary() (*types.SpecSummary, bool) { - return suite.runner.CurrentSpecSummary() -} - -func (suite *Suite) SetBeforeSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewBeforeSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetAfterSuiteNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewAfterSuiteNode(body, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedBeforeSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.beforeSuiteNode != nil { - panic("You may only call BeforeSuite once!") - } - suite.beforeSuiteNode = leafnodes.NewSynchronizedBeforeSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) SetSynchronizedAfterSuiteNode(bodyA interface{}, bodyB interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.afterSuiteNode != nil { - panic("You may only call AfterSuite once!") - } - suite.afterSuiteNode = leafnodes.NewSynchronizedAfterSuiteNode(bodyA, bodyB, codeLocation, timeout, suite.failer) -} - -func (suite *Suite) PushContainerNode(text string, body func(), flag types.FlagType, codeLocation types.CodeLocation) { - container := containernode.New(text, flag, codeLocation) - suite.currentContainer.PushContainerNode(container) - - previousContainer := suite.currentContainer - suite.currentContainer = container - suite.containerIndex++ - - body() - - suite.containerIndex-- - suite.currentContainer = previousContainer -} - -func (suite *Suite) PushItNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call It from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewItNode(text, body, flag, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushMeasureNode(text string, body interface{}, flag types.FlagType, codeLocation types.CodeLocation, samples int) { - if suite.running { - suite.failer.Fail("You may only call Measure from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSubjectNode(leafnodes.NewMeasureNode(text, body, flag, codeLocation, samples, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call BeforeEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushJustBeforeEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call JustBeforeEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewJustBeforeEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} - -func (suite *Suite) PushAfterEachNode(body interface{}, codeLocation types.CodeLocation, timeout time.Duration) { - if suite.running { - suite.failer.Fail("You may only call AfterEach from within a Describe or Context", codeLocation) - } - suite.currentContainer.PushSetupNode(leafnodes.NewAfterEachNode(body, codeLocation, timeout, suite.failer, suite.containerIndex)) -} diff --git a/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go b/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go deleted file mode 100644 index 090445d084..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/testingtproxy/testing_t_proxy.go +++ /dev/null @@ -1,76 +0,0 @@ -package testingtproxy - -import ( - "fmt" - "io" -) - -type failFunc func(message string, callerSkip ...int) - -func New(writer io.Writer, fail failFunc, offset int) *ginkgoTestingTProxy { - return &ginkgoTestingTProxy{ - fail: fail, - offset: offset, - writer: writer, - } -} - -type ginkgoTestingTProxy struct { - fail failFunc - offset int - writer io.Writer -} - -func (t *ginkgoTestingTProxy) Error(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Errorf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fail() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) FailNow() { - t.fail("failed", t.offset) -} - -func (t *ginkgoTestingTProxy) Fatal(args ...interface{}) { - t.fail(fmt.Sprintln(args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Fatalf(format string, args ...interface{}) { - t.fail(fmt.Sprintf(format, args...), t.offset) -} - -func (t *ginkgoTestingTProxy) Log(args ...interface{}) { - fmt.Fprintln(t.writer, args...) -} - -func (t *ginkgoTestingTProxy) Logf(format string, args ...interface{}) { - t.Log(fmt.Sprintf(format, args...)) -} - -func (t *ginkgoTestingTProxy) Failed() bool { - return false -} - -func (t *ginkgoTestingTProxy) Parallel() { -} - -func (t *ginkgoTestingTProxy) Skip(args ...interface{}) { - fmt.Println(args...) -} - -func (t *ginkgoTestingTProxy) Skipf(format string, args ...interface{}) { - t.Skip(fmt.Sprintf(format, args...)) -} - -func (t *ginkgoTestingTProxy) SkipNow() { -} - -func (t *ginkgoTestingTProxy) Skipped() bool { - return false -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go b/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go deleted file mode 100644 index 6739c3f605..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/fake_writer.go +++ /dev/null @@ -1,36 +0,0 @@ -package writer - -type FakeGinkgoWriter struct { - EventStream []string -} - -func NewFake() *FakeGinkgoWriter { - return &FakeGinkgoWriter{ - EventStream: []string{}, - } -} - -func (writer *FakeGinkgoWriter) AddEvent(event string) { - writer.EventStream = append(writer.EventStream, event) -} - -func (writer *FakeGinkgoWriter) Truncate() { - writer.EventStream = append(writer.EventStream, "TRUNCATE") -} - -func (writer *FakeGinkgoWriter) DumpOut() { - writer.EventStream = append(writer.EventStream, "DUMP") -} - -func (writer *FakeGinkgoWriter) DumpOutWithHeader(header string) { - writer.EventStream = append(writer.EventStream, "DUMP_WITH_HEADER: "+header) -} - -func (writer *FakeGinkgoWriter) Bytes() []byte { - writer.EventStream = append(writer.EventStream, "BYTES") - return nil -} - -func (writer *FakeGinkgoWriter) Write(data []byte) (n int, err error) { - return 0, nil -} diff --git a/vendor/github.com/onsi/ginkgo/internal/writer/writer.go b/vendor/github.com/onsi/ginkgo/internal/writer/writer.go deleted file mode 100644 index 6b23b1a648..0000000000 --- a/vendor/github.com/onsi/ginkgo/internal/writer/writer.go +++ /dev/null @@ -1,81 +0,0 @@ -package writer - -import ( - "bytes" - "io" - "sync" -) - -type WriterInterface interface { - io.Writer - - Truncate() - DumpOut() - DumpOutWithHeader(header string) - Bytes() []byte -} - -type Writer struct { - buffer *bytes.Buffer - outWriter io.Writer - lock *sync.Mutex - stream bool -} - -func New(outWriter io.Writer) *Writer { - return &Writer{ - buffer: &bytes.Buffer{}, - lock: &sync.Mutex{}, - outWriter: outWriter, - stream: true, - } -} - -func (w *Writer) SetStream(stream bool) { - w.lock.Lock() - defer w.lock.Unlock() - w.stream = stream -} - -func (w *Writer) Write(b []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - n, err = w.buffer.Write(b) - if w.stream { - return w.outWriter.Write(b) - } - return n, err -} - -func (w *Writer) Truncate() { - w.lock.Lock() - defer w.lock.Unlock() - w.buffer.Reset() -} - -func (w *Writer) DumpOut() { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream { - w.buffer.WriteTo(w.outWriter) - } -} - -func (w *Writer) Bytes() []byte { - w.lock.Lock() - defer w.lock.Unlock() - b := w.buffer.Bytes() - copied := make([]byte, len(b)) - copy(copied, b) - return copied -} - -func (w *Writer) DumpOutWithHeader(header string) { - w.lock.Lock() - defer w.lock.Unlock() - if !w.stream && w.buffer.Len() > 0 { - w.outWriter.Write([]byte(header)) - w.buffer.WriteTo(w.outWriter) - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go deleted file mode 100644 index fb82f70a6d..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/default_reporter.go +++ /dev/null @@ -1,84 +0,0 @@ -/* -Ginkgo's Default Reporter - -A number of command line flags are available to tweak Ginkgo's default output. - -These are documented [here](http://onsi.github.io/ginkgo/#running_tests) -*/ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/reporters/stenographer" - "github.com/onsi/ginkgo/types" -) - -type DefaultReporter struct { - config config.DefaultReporterConfigType - stenographer stenographer.Stenographer - specSummaries []*types.SpecSummary -} - -func NewDefaultReporter(config config.DefaultReporterConfigType, stenographer stenographer.Stenographer) *DefaultReporter { - return &DefaultReporter{ - config: config, - stenographer: stenographer, - } -} - -func (reporter *DefaultReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.stenographer.AnnounceSuite(summary.SuiteDescription, config.RandomSeed, config.RandomizeAllSpecs, reporter.config.Succinct) - if config.ParallelTotal > 1 { - reporter.stenographer.AnnounceParallelRun(config.ParallelNode, config.ParallelTotal, reporter.config.Succinct) - } else { - reporter.stenographer.AnnounceNumberOfSpecs(summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, reporter.config.Succinct) - } -} - -func (reporter *DefaultReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceBeforeSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - reporter.stenographer.AnnounceAfterSuiteFailure(setupSummary, reporter.config.Succinct, reporter.config.FullTrace) - } -} - -func (reporter *DefaultReporter) SpecWillRun(specSummary *types.SpecSummary) { - if reporter.config.Verbose && !reporter.config.Succinct && specSummary.State != types.SpecStatePending && specSummary.State != types.SpecStateSkipped { - reporter.stenographer.AnnounceSpecWillRun(specSummary) - } -} - -func (reporter *DefaultReporter) SpecDidComplete(specSummary *types.SpecSummary) { - switch specSummary.State { - case types.SpecStatePassed: - if specSummary.IsMeasurement { - reporter.stenographer.AnnounceSuccesfulMeasurement(specSummary, reporter.config.Succinct) - } else if specSummary.RunTime.Seconds() >= reporter.config.SlowSpecThreshold { - reporter.stenographer.AnnounceSuccesfulSlowSpec(specSummary, reporter.config.Succinct) - } else { - reporter.stenographer.AnnounceSuccesfulSpec(specSummary) - } - case types.SpecStatePending: - reporter.stenographer.AnnouncePendingSpec(specSummary, reporter.config.NoisyPendings && !reporter.config.Succinct) - case types.SpecStateSkipped: - reporter.stenographer.AnnounceSkippedSpec(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStateTimedOut: - reporter.stenographer.AnnounceSpecTimedOut(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStatePanicked: - reporter.stenographer.AnnounceSpecPanicked(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - case types.SpecStateFailed: - reporter.stenographer.AnnounceSpecFailed(specSummary, reporter.config.Succinct, reporter.config.FullTrace) - } - - reporter.specSummaries = append(reporter.specSummaries, specSummary) -} - -func (reporter *DefaultReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.stenographer.SummarizeFailures(reporter.specSummaries) - reporter.stenographer.AnnounceSpecRunCompletion(summary, reporter.config.Succinct) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go deleted file mode 100644 index 27db479490..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/fake_reporter.go +++ /dev/null @@ -1,59 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -//FakeReporter is useful for testing purposes -type FakeReporter struct { - Config config.GinkgoConfigType - - BeginSummary *types.SuiteSummary - BeforeSuiteSummary *types.SetupSummary - SpecWillRunSummaries []*types.SpecSummary - SpecSummaries []*types.SpecSummary - AfterSuiteSummary *types.SetupSummary - EndSummary *types.SuiteSummary - - SpecWillRunStub func(specSummary *types.SpecSummary) - SpecDidCompleteStub func(specSummary *types.SpecSummary) -} - -func NewFakeReporter() *FakeReporter { - return &FakeReporter{ - SpecWillRunSummaries: make([]*types.SpecSummary, 0), - SpecSummaries: make([]*types.SpecSummary, 0), - } -} - -func (fakeR *FakeReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - fakeR.Config = config - fakeR.BeginSummary = summary -} - -func (fakeR *FakeReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.BeforeSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecWillRun(specSummary *types.SpecSummary) { - if fakeR.SpecWillRunStub != nil { - fakeR.SpecWillRunStub(specSummary) - } - fakeR.SpecWillRunSummaries = append(fakeR.SpecWillRunSummaries, specSummary) -} - -func (fakeR *FakeReporter) SpecDidComplete(specSummary *types.SpecSummary) { - if fakeR.SpecDidCompleteStub != nil { - fakeR.SpecDidCompleteStub(specSummary) - } - fakeR.SpecSummaries = append(fakeR.SpecSummaries, specSummary) -} - -func (fakeR *FakeReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - fakeR.AfterSuiteSummary = setupSummary -} - -func (fakeR *FakeReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fakeR.EndSummary = summary -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go deleted file mode 100644 index 89b03513fd..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/junit_reporter.go +++ /dev/null @@ -1,147 +0,0 @@ -/* - -JUnit XML Reporter for Ginkgo - -For usage instructions: http://onsi.github.io/ginkgo/#generating_junit_xml_output - -*/ - -package reporters - -import ( - "encoding/xml" - "fmt" - "os" - "strings" - - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -type JUnitTestSuite struct { - XMLName xml.Name `xml:"testsuite"` - TestCases []JUnitTestCase `xml:"testcase"` - Tests int `xml:"tests,attr"` - Failures int `xml:"failures,attr"` - Time float64 `xml:"time,attr"` -} - -type JUnitTestCase struct { - Name string `xml:"name,attr"` - ClassName string `xml:"classname,attr"` - FailureMessage *JUnitFailureMessage `xml:"failure,omitempty"` - Skipped *JUnitSkipped `xml:"skipped,omitempty"` - Time float64 `xml:"time,attr"` - SystemOut string `xml:"system-out,omitempty"` -} - -type JUnitFailureMessage struct { - Type string `xml:"type,attr"` - Message string `xml:",chardata"` -} - -type JUnitSkipped struct { - XMLName xml.Name `xml:"skipped"` -} - -type JUnitReporter struct { - suite JUnitTestSuite - filename string - testSuiteName string -} - -//NewJUnitReporter creates a new JUnit XML reporter. The XML will be stored in the passed in filename. -func NewJUnitReporter(filename string) *JUnitReporter { - return &JUnitReporter{ - filename: filename, - } -} - -func (reporter *JUnitReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.suite = JUnitTestSuite{ - TestCases: []JUnitTestCase{}, - } - reporter.testSuiteName = summary.SuiteDescription -} - -func (reporter *JUnitReporter) SpecWillRun(specSummary *types.SpecSummary) { -} - -func (reporter *JUnitReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *JUnitReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func failureMessage(failure types.SpecFailure) string { - return fmt.Sprintf("%s\n%s\n%s", failure.ComponentCodeLocation.String(), failure.Message, failure.Location.String()) -} - -func (reporter *JUnitReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testCase := JUnitTestCase{ - Name: name, - ClassName: reporter.testSuiteName, - } - - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(setupSummary.State), - Message: failureMessage(setupSummary.Failure), - } - testCase.SystemOut = setupSummary.CapturedOutput - testCase.Time = setupSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) - } -} - -func (reporter *JUnitReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testCase := JUnitTestCase{ - Name: strings.Join(specSummary.ComponentTexts[1:], " "), - ClassName: reporter.testSuiteName, - } - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - testCase.FailureMessage = &JUnitFailureMessage{ - Type: reporter.failureTypeForState(specSummary.State), - Message: failureMessage(specSummary.Failure), - } - testCase.SystemOut = specSummary.CapturedOutput - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - testCase.Skipped = &JUnitSkipped{} - } - testCase.Time = specSummary.RunTime.Seconds() - reporter.suite.TestCases = append(reporter.suite.TestCases, testCase) -} - -func (reporter *JUnitReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - reporter.suite.Tests = summary.NumberOfSpecsThatWillBeRun - reporter.suite.Time = summary.RunTime.Seconds() - reporter.suite.Failures = summary.NumberOfFailedSpecs - file, err := os.Create(reporter.filename) - if err != nil { - fmt.Printf("Failed to create JUnit report file: %s\n\t%s", reporter.filename, err.Error()) - } - defer file.Close() - file.WriteString(xml.Header) - encoder := xml.NewEncoder(file) - encoder.Indent(" ", " ") - err = encoder.Encode(reporter.suite) - if err != nil { - fmt.Printf("Failed to generate JUnit report\n\t%s", err.Error()) - } -} - -func (reporter *JUnitReporter) failureTypeForState(state types.SpecState) string { - switch state { - case types.SpecStateFailed: - return "Failure" - case types.SpecStateTimedOut: - return "Timeout" - case types.SpecStatePanicked: - return "Panic" - default: - return "" - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/reporter.go b/vendor/github.com/onsi/ginkgo/reporters/reporter.go deleted file mode 100644 index 348b9dfce1..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/reporter.go +++ /dev/null @@ -1,15 +0,0 @@ -package reporters - -import ( - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" -) - -type Reporter interface { - SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) - BeforeSuiteDidRun(setupSummary *types.SetupSummary) - SpecWillRun(specSummary *types.SpecSummary) - SpecDidComplete(specSummary *types.SpecSummary) - AfterSuiteDidRun(setupSummary *types.SetupSummary) - SpecSuiteDidEnd(summary *types.SuiteSummary) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go deleted file mode 100644 index 45b8f88690..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/console_logging.go +++ /dev/null @@ -1,64 +0,0 @@ -package stenographer - -import ( - "fmt" - "strings" -) - -func (s *consoleStenographer) colorize(colorCode string, format string, args ...interface{}) string { - var out string - - if len(args) > 0 { - out = fmt.Sprintf(format, args...) - } else { - out = format - } - - if s.color { - return fmt.Sprintf("%s%s%s", colorCode, out, defaultStyle) - } else { - return out - } -} - -func (s *consoleStenographer) printBanner(text string, bannerCharacter string) { - fmt.Fprintln(s.w, text) - fmt.Fprintln(s.w, strings.Repeat(bannerCharacter, len(text))) -} - -func (s *consoleStenographer) printNewLine() { - fmt.Fprintln(s.w, "") -} - -func (s *consoleStenographer) printDelimiter() { - fmt.Fprintln(s.w, s.colorize(grayColor, "%s", strings.Repeat("-", 30))) -} - -func (s *consoleStenographer) print(indentation int, format string, args ...interface{}) { - fmt.Fprint(s.w, s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) println(indentation int, format string, args ...interface{}) { - fmt.Fprintln(s.w, s.indent(indentation, format, args...)) -} - -func (s *consoleStenographer) indent(indentation int, format string, args ...interface{}) string { - var text string - - if len(args) > 0 { - text = fmt.Sprintf(format, args...) - } else { - text = format - } - - stringArray := strings.Split(text, "\n") - padding := "" - if indentation >= 0 { - padding = strings.Repeat(" ", indentation) - } - for i, s := range stringArray { - stringArray[i] = fmt.Sprintf("%s%s", padding, s) - } - - return strings.Join(stringArray, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go deleted file mode 100644 index 98854e7d9a..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/fake_stenographer.go +++ /dev/null @@ -1,142 +0,0 @@ -package stenographer - -import ( - "sync" - - "github.com/onsi/ginkgo/types" -) - -func NewFakeStenographerCall(method string, args ...interface{}) FakeStenographerCall { - return FakeStenographerCall{ - Method: method, - Args: args, - } -} - -type FakeStenographer struct { - calls []FakeStenographerCall - lock *sync.Mutex -} - -type FakeStenographerCall struct { - Method string - Args []interface{} -} - -func NewFakeStenographer() *FakeStenographer { - stenographer := &FakeStenographer{ - lock: &sync.Mutex{}, - } - stenographer.Reset() - return stenographer -} - -func (stenographer *FakeStenographer) Calls() []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - return stenographer.calls -} - -func (stenographer *FakeStenographer) Reset() { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = make([]FakeStenographerCall, 0) -} - -func (stenographer *FakeStenographer) CallsTo(method string) []FakeStenographerCall { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - results := make([]FakeStenographerCall, 0) - for _, call := range stenographer.calls { - if call.Method == method { - results = append(results, call) - } - } - - return results -} - -func (stenographer *FakeStenographer) registerCall(method string, args ...interface{}) { - stenographer.lock.Lock() - defer stenographer.lock.Unlock() - - stenographer.calls = append(stenographer.calls, NewFakeStenographerCall(method, args...)) -} - -func (stenographer *FakeStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - stenographer.registerCall("AnnounceSuite", description, randomSeed, randomizingAll, succinct) -} - -func (stenographer *FakeStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - stenographer.registerCall("AnnounceAggregatedParallelRun", nodes, succinct) -} - -func (stenographer *FakeStenographer) AnnounceParallelRun(node int, nodes int, succinct bool) { - stenographer.registerCall("AnnounceParallelRun", node, nodes, succinct) -} - -func (stenographer *FakeStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - stenographer.registerCall("AnnounceNumberOfSpecs", specsToRun, total, succinct) -} - -func (stenographer *FakeStenographer) AnnounceTotalNumberOfSpecs(total int, succinct bool) { - stenographer.registerCall("AnnounceTotalNumberOfSpecs", total, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - stenographer.registerCall("AnnounceSpecRunCompletion", summary, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSpecWillRun", spec) -} - -func (stenographer *FakeStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceBeforeSuiteFailure", summary, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceAfterSuiteFailure", summary, succinct, fullTrace) -} -func (stenographer *FakeStenographer) AnnounceCapturedOutput(output string) { - stenographer.registerCall("AnnounceCapturedOutput", output) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - stenographer.registerCall("AnnounceSuccesfulSpec", spec) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulSlowSpec", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - stenographer.registerCall("AnnounceSuccesfulMeasurement", spec, succinct) -} - -func (stenographer *FakeStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - stenographer.registerCall("AnnouncePendingSpec", spec, noisy) -} - -func (stenographer *FakeStenographer) AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSkippedSpec", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecTimedOut", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecPanicked", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - stenographer.registerCall("AnnounceSpecFailed", spec, succinct, fullTrace) -} - -func (stenographer *FakeStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - stenographer.registerCall("SummarizeFailures", summaries) -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go deleted file mode 100644 index fefd3e182f..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/stenographer.go +++ /dev/null @@ -1,573 +0,0 @@ -/* -The stenographer is used by Ginkgo's reporters to generate output. - -Move along, nothing to see here. -*/ - -package stenographer - -import ( - "fmt" - "io" - "runtime" - "strings" - - "github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable" - "github.com/onsi/ginkgo/types" -) - -const defaultStyle = "\x1b[0m" -const boldStyle = "\x1b[1m" -const redColor = "\x1b[91m" -const greenColor = "\x1b[32m" -const yellowColor = "\x1b[33m" -const cyanColor = "\x1b[36m" -const grayColor = "\x1b[90m" -const lightGrayColor = "\x1b[37m" - -type cursorStateType int - -const ( - cursorStateTop cursorStateType = iota - cursorStateStreaming - cursorStateMidBlock - cursorStateEndBlock -) - -type Stenographer interface { - AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) - AnnounceAggregatedParallelRun(nodes int, succinct bool) - AnnounceParallelRun(node int, nodes int, succinct bool) - AnnounceTotalNumberOfSpecs(total int, succinct bool) - AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) - AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) - - AnnounceSpecWillRun(spec *types.SpecSummary) - AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) - - AnnounceCapturedOutput(output string) - - AnnounceSuccesfulSpec(spec *types.SpecSummary) - AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) - AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) - - AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) - AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) - - AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) - AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) - - SummarizeFailures(summaries []*types.SpecSummary) -} - -func New(color bool, enableFlakes bool) Stenographer { - denoter := "•" - if runtime.GOOS == "windows" { - denoter = "+" - } - return &consoleStenographer{ - color: color, - denoter: denoter, - cursorState: cursorStateTop, - enableFlakes: enableFlakes, - w: colorable.NewColorableStdout(), - } -} - -type consoleStenographer struct { - color bool - denoter string - cursorState cursorStateType - enableFlakes bool - w io.Writer -} - -var alternatingColors = []string{defaultStyle, grayColor} - -func (s *consoleStenographer) AnnounceSuite(description string, randomSeed int64, randomizingAll bool, succinct bool) { - if succinct { - s.print(0, "[%d] %s ", randomSeed, s.colorize(boldStyle, description)) - return - } - s.printBanner(fmt.Sprintf("Running Suite: %s", description), "=") - s.print(0, "Random Seed: %s", s.colorize(boldStyle, "%d", randomSeed)) - if randomizingAll { - s.print(0, " - Will randomize all specs") - } - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceParallelRun(node int, nodes int, succinct bool) { - if succinct { - s.print(0, "- node #%d ", node) - return - } - s.println(0, - "Parallel test node %s/%s.", - s.colorize(boldStyle, "%d", node), - s.colorize(boldStyle, "%d", nodes), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceAggregatedParallelRun(nodes int, succinct bool) { - if succinct { - s.print(0, "- %d nodes ", nodes) - return - } - s.println(0, - "Running in parallel across %s nodes", - s.colorize(boldStyle, "%d", nodes), - ) - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceNumberOfSpecs(specsToRun int, total int, succinct bool) { - if succinct { - s.print(0, "- %d/%d specs ", specsToRun, total) - s.stream() - return - } - s.println(0, - "Will run %s of %s specs", - s.colorize(boldStyle, "%d", specsToRun), - s.colorize(boldStyle, "%d", total), - ) - - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceTotalNumberOfSpecs(total int, succinct bool) { - if succinct { - s.print(0, "- %d specs ", total) - s.stream() - return - } - s.println(0, - "Will run %s specs", - s.colorize(boldStyle, "%d", total), - ) - - s.printNewLine() -} - -func (s *consoleStenographer) AnnounceSpecRunCompletion(summary *types.SuiteSummary, succinct bool) { - if succinct && summary.SuiteSucceeded { - s.print(0, " %s %s ", s.colorize(greenColor, "SUCCESS!"), summary.RunTime) - return - } - s.printNewLine() - color := greenColor - if !summary.SuiteSucceeded { - color = redColor - } - s.println(0, s.colorize(boldStyle+color, "Ran %d of %d Specs in %.3f seconds", summary.NumberOfSpecsThatWillBeRun, summary.NumberOfTotalSpecs, summary.RunTime.Seconds())) - - status := "" - if summary.SuiteSucceeded { - status = s.colorize(boldStyle+greenColor, "SUCCESS!") - } else { - status = s.colorize(boldStyle+redColor, "FAIL!") - } - - flakes := "" - if s.enableFlakes { - flakes = " | " + s.colorize(yellowColor+boldStyle, "%d Flaked", summary.NumberOfFlakedSpecs) - } - - s.print(0, - "%s -- %s | %s | %s | %s ", - status, - s.colorize(greenColor+boldStyle, "%d Passed", summary.NumberOfPassedSpecs), - s.colorize(redColor+boldStyle, "%d Failed", summary.NumberOfFailedSpecs)+flakes, - s.colorize(yellowColor+boldStyle, "%d Pending", summary.NumberOfPendingSpecs), - s.colorize(cyanColor+boldStyle, "%d Skipped", summary.NumberOfSkippedSpecs), - ) -} - -func (s *consoleStenographer) AnnounceSpecWillRun(spec *types.SpecSummary) { - s.startBlock() - for i, text := range spec.ComponentTexts[1 : len(spec.ComponentTexts)-1] { - s.print(0, s.colorize(alternatingColors[i%2], text)+" ") - } - - indentation := 0 - if len(spec.ComponentTexts) > 2 { - indentation = 1 - s.printNewLine() - } - index := len(spec.ComponentTexts) - 1 - s.print(indentation, s.colorize(boldStyle, spec.ComponentTexts[index])) - s.printNewLine() - s.print(indentation, s.colorize(lightGrayColor, spec.ComponentCodeLocations[index].String())) - s.printNewLine() - s.midBlock() -} - -func (s *consoleStenographer) AnnounceBeforeSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("BeforeSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceAfterSuiteFailure(summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.announceSetupFailure("AfterSuite", summary, succinct, fullTrace) -} - -func (s *consoleStenographer) announceSetupFailure(name string, summary *types.SetupSummary, succinct bool, fullTrace bool) { - s.startBlock() - var message string - switch summary.State { - case types.SpecStateFailed: - message = "Failure" - case types.SpecStatePanicked: - message = "Panic" - case types.SpecStateTimedOut: - message = "Timeout" - } - - s.println(0, s.colorize(redColor+boldStyle, "%s [%.3f seconds]", message, summary.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock([]string{name}, []types.CodeLocation{summary.CodeLocation}, summary.ComponentType, 0, summary.State, true) - - s.printNewLine() - s.printFailure(indentation, summary.State, summary.Failure, fullTrace) - - s.endBlock() -} - -func (s *consoleStenographer) AnnounceCapturedOutput(output string) { - if output == "" { - return - } - - s.startBlock() - s.println(0, output) - s.midBlock() -} - -func (s *consoleStenographer) AnnounceSuccesfulSpec(spec *types.SpecSummary) { - s.print(0, s.colorize(greenColor, s.denoter)) - s.stream() -} - -func (s *consoleStenographer) AnnounceSuccesfulSlowSpec(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "%s [SLOW TEST:%.3f seconds]", s.denoter, spec.RunTime.Seconds()), - "", - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnounceSuccesfulMeasurement(spec *types.SpecSummary, succinct bool) { - s.printBlockWithMessage( - s.colorize(greenColor, "%s [MEASUREMENT]", s.denoter), - s.measurementReport(spec, succinct), - spec, - succinct, - ) -} - -func (s *consoleStenographer) AnnouncePendingSpec(spec *types.SpecSummary, noisy bool) { - if noisy { - s.printBlockWithMessage( - s.colorize(yellowColor, "P [PENDING]"), - "", - spec, - false, - ) - } else { - s.print(0, s.colorize(yellowColor, "P")) - s.stream() - } -} - -func (s *consoleStenographer) AnnounceSkippedSpec(spec *types.SpecSummary, succinct bool, fullTrace bool) { - // Skips at runtime will have a non-empty spec.Failure. All others should be succinct. - if succinct || spec.Failure == (types.SpecFailure{}) { - s.print(0, s.colorize(cyanColor, "S")) - s.stream() - } else { - s.startBlock() - s.println(0, s.colorize(cyanColor+boldStyle, "S [SKIPPING]%s [%.3f seconds]", s.failureContext(spec.Failure.ComponentType), spec.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, spec.Failure.ComponentType, spec.Failure.ComponentIndex, spec.State, succinct) - - s.printNewLine() - s.printSkip(indentation, spec.Failure) - s.endBlock() - } -} - -func (s *consoleStenographer) AnnounceSpecTimedOut(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s... Timeout", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecPanicked(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s! Panic", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) AnnounceSpecFailed(spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.printSpecFailure(fmt.Sprintf("%s Failure", s.denoter), spec, succinct, fullTrace) -} - -func (s *consoleStenographer) SummarizeFailures(summaries []*types.SpecSummary) { - failingSpecs := []*types.SpecSummary{} - - for _, summary := range summaries { - if summary.HasFailureState() { - failingSpecs = append(failingSpecs, summary) - } - } - - if len(failingSpecs) == 0 { - return - } - - s.printNewLine() - s.printNewLine() - plural := "s" - if len(failingSpecs) == 1 { - plural = "" - } - s.println(0, s.colorize(redColor+boldStyle, "Summarizing %d Failure%s:", len(failingSpecs), plural)) - for _, summary := range failingSpecs { - s.printNewLine() - if summary.HasFailureState() { - if summary.TimedOut() { - s.print(0, s.colorize(redColor+boldStyle, "[Timeout...] ")) - } else if summary.Panicked() { - s.print(0, s.colorize(redColor+boldStyle, "[Panic!] ")) - } else if summary.Failed() { - s.print(0, s.colorize(redColor+boldStyle, "[Fail] ")) - } - s.printSpecContext(summary.ComponentTexts, summary.ComponentCodeLocations, summary.Failure.ComponentType, summary.Failure.ComponentIndex, summary.State, true) - s.printNewLine() - s.println(0, s.colorize(lightGrayColor, summary.Failure.Location.String())) - } - } -} - -func (s *consoleStenographer) startBlock() { - if s.cursorState == cursorStateStreaming { - s.printNewLine() - s.printDelimiter() - } else if s.cursorState == cursorStateMidBlock { - s.printNewLine() - } -} - -func (s *consoleStenographer) midBlock() { - s.cursorState = cursorStateMidBlock -} - -func (s *consoleStenographer) endBlock() { - s.printDelimiter() - s.cursorState = cursorStateEndBlock -} - -func (s *consoleStenographer) stream() { - s.cursorState = cursorStateStreaming -} - -func (s *consoleStenographer) printBlockWithMessage(header string, message string, spec *types.SpecSummary, succinct bool) { - s.startBlock() - s.println(0, header) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, types.SpecComponentTypeInvalid, 0, spec.State, succinct) - - if message != "" { - s.printNewLine() - s.println(indentation, message) - } - - s.endBlock() -} - -func (s *consoleStenographer) printSpecFailure(message string, spec *types.SpecSummary, succinct bool, fullTrace bool) { - s.startBlock() - s.println(0, s.colorize(redColor+boldStyle, "%s%s [%.3f seconds]", message, s.failureContext(spec.Failure.ComponentType), spec.RunTime.Seconds())) - - indentation := s.printCodeLocationBlock(spec.ComponentTexts, spec.ComponentCodeLocations, spec.Failure.ComponentType, spec.Failure.ComponentIndex, spec.State, succinct) - - s.printNewLine() - s.printFailure(indentation, spec.State, spec.Failure, fullTrace) - s.endBlock() -} - -func (s *consoleStenographer) failureContext(failedComponentType types.SpecComponentType) string { - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - return " in Suite Setup (BeforeSuite)" - case types.SpecComponentTypeAfterSuite: - return " in Suite Teardown (AfterSuite)" - case types.SpecComponentTypeBeforeEach: - return " in Spec Setup (BeforeEach)" - case types.SpecComponentTypeJustBeforeEach: - return " in Spec Setup (JustBeforeEach)" - case types.SpecComponentTypeAfterEach: - return " in Spec Teardown (AfterEach)" - } - - return "" -} - -func (s *consoleStenographer) printSkip(indentation int, spec types.SpecFailure) { - s.println(indentation, s.colorize(cyanColor, spec.Message)) - s.printNewLine() - s.println(indentation, spec.Location.String()) -} - -func (s *consoleStenographer) printFailure(indentation int, state types.SpecState, failure types.SpecFailure, fullTrace bool) { - if state == types.SpecStatePanicked { - s.println(indentation, s.colorize(redColor+boldStyle, failure.Message)) - s.println(indentation, s.colorize(redColor, failure.ForwardedPanic)) - s.println(indentation, failure.Location.String()) - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } else { - s.println(indentation, s.colorize(redColor, failure.Message)) - s.printNewLine() - s.println(indentation, failure.Location.String()) - if fullTrace { - s.printNewLine() - s.println(indentation, s.colorize(redColor, "Full Stack Trace")) - s.println(indentation, failure.Location.FullStackTrace) - } - } -} - -func (s *consoleStenographer) printSpecContext(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, state types.SpecState, succinct bool) int { - startIndex := 1 - indentation := 0 - - if len(componentTexts) == 1 { - startIndex = 0 - } - - for i := startIndex; i < len(componentTexts); i++ { - if (state.IsFailure() || state == types.SpecStateSkipped) && i == failedComponentIndex { - color := redColor - if state == types.SpecStateSkipped { - color = cyanColor - } - blockType := "" - switch failedComponentType { - case types.SpecComponentTypeBeforeSuite: - blockType = "BeforeSuite" - case types.SpecComponentTypeAfterSuite: - blockType = "AfterSuite" - case types.SpecComponentTypeBeforeEach: - blockType = "BeforeEach" - case types.SpecComponentTypeJustBeforeEach: - blockType = "JustBeforeEach" - case types.SpecComponentTypeAfterEach: - blockType = "AfterEach" - case types.SpecComponentTypeIt: - blockType = "It" - case types.SpecComponentTypeMeasure: - blockType = "Measurement" - } - if succinct { - s.print(0, s.colorize(color+boldStyle, "[%s] %s ", blockType, componentTexts[i])) - } else { - s.println(indentation, s.colorize(color+boldStyle, "%s [%s]", componentTexts[i], blockType)) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } else { - if succinct { - s.print(0, s.colorize(alternatingColors[i%2], "%s ", componentTexts[i])) - } else { - s.println(indentation, componentTexts[i]) - s.println(indentation, s.colorize(grayColor, "%s", componentCodeLocations[i])) - } - } - indentation++ - } - - return indentation -} - -func (s *consoleStenographer) printCodeLocationBlock(componentTexts []string, componentCodeLocations []types.CodeLocation, failedComponentType types.SpecComponentType, failedComponentIndex int, state types.SpecState, succinct bool) int { - indentation := s.printSpecContext(componentTexts, componentCodeLocations, failedComponentType, failedComponentIndex, state, succinct) - - if succinct { - if len(componentTexts) > 0 { - s.printNewLine() - s.print(0, s.colorize(lightGrayColor, "%s", componentCodeLocations[len(componentCodeLocations)-1])) - } - s.printNewLine() - indentation = 1 - } else { - indentation-- - } - - return indentation -} - -func (s *consoleStenographer) orderedMeasurementKeys(measurements map[string]*types.SpecMeasurement) []string { - orderedKeys := make([]string, len(measurements)) - for key, measurement := range measurements { - orderedKeys[measurement.Order] = key - } - return orderedKeys -} - -func (s *consoleStenographer) measurementReport(spec *types.SpecSummary, succinct bool) string { - if len(spec.Measurements) == 0 { - return "Found no measurements" - } - - message := []string{} - orderedKeys := s.orderedMeasurementKeys(spec.Measurements) - - if succinct { - message = append(message, fmt.Sprintf("%s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - message = append(message, fmt.Sprintf(" %s - %s: %s%s, %s: %s%s ± %s%s, %s: %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - measurement.SmallestLabel, - s.colorize(greenColor, measurement.PrecisionFmt(), measurement.Smallest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.Average), - measurement.Units, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.StdDeviation), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, measurement.PrecisionFmt(), measurement.Largest), - measurement.Units, - )) - } - } else { - message = append(message, fmt.Sprintf("Ran %s samples:", s.colorize(boldStyle, "%d", spec.NumberOfSamples))) - for _, key := range orderedKeys { - measurement := spec.Measurements[key] - info := "" - if measurement.Info != nil { - message = append(message, fmt.Sprintf("%v", measurement.Info)) - } - - message = append(message, fmt.Sprintf("%s:\n%s %s: %s%s\n %s: %s%s\n %s: %s%s ± %s%s", - s.colorize(boldStyle, "%s", measurement.Name), - info, - measurement.SmallestLabel, - s.colorize(greenColor, measurement.PrecisionFmt(), measurement.Smallest), - measurement.Units, - measurement.LargestLabel, - s.colorize(redColor, measurement.PrecisionFmt(), measurement.Largest), - measurement.Units, - measurement.AverageLabel, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.Average), - measurement.Units, - s.colorize(cyanColor, measurement.PrecisionFmt(), measurement.StdDeviation), - measurement.Units, - )) - } - } - - return strings.Join(message, "\n") -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE deleted file mode 100644 index 91b5cef30e..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Yasuhiro Matsumoto - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md deleted file mode 100644 index e84226a735..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# go-colorable - -Colorable writer for windows. - -For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) -This package is possible to handle escape sequence for ansi color on windows. - -## Too Bad! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) - - -## So Good! - -![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) - -## Usage - -```go -logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) -logrus.SetOutput(colorable.NewColorableStdout()) - -logrus.Info("succeeded") -logrus.Warn("not correct") -logrus.Error("something error") -logrus.Fatal("panic") -``` - -You can compile above code on non-windows OSs. - -## Installation - -``` -$ go get github.com/mattn/go-colorable -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go deleted file mode 100644 index 52d6653b34..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_others.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build !windows - -package colorable - -import ( - "io" - "os" -) - -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - return file -} - -func NewColorableStdout() io.Writer { - return os.Stdout -} - -func NewColorableStderr() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go deleted file mode 100644 index 1088009230..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/colorable_windows.go +++ /dev/null @@ -1,783 +0,0 @@ -package colorable - -import ( - "bytes" - "fmt" - "io" - "math" - "os" - "strconv" - "strings" - "syscall" - "unsafe" - - "github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty" -) - -const ( - foregroundBlue = 0x1 - foregroundGreen = 0x2 - foregroundRed = 0x4 - foregroundIntensity = 0x8 - foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) - backgroundBlue = 0x10 - backgroundGreen = 0x20 - backgroundRed = 0x40 - backgroundIntensity = 0x80 - backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) -) - -type wchar uint16 -type short int16 -type dword uint32 -type word uint16 - -type coord struct { - x short - y short -} - -type smallRect struct { - left short - top short - right short - bottom short -} - -type consoleScreenBufferInfo struct { - size coord - cursorPosition coord - attributes word - window smallRect - maximumWindowSize coord -} - -var ( - kernel32 = syscall.NewLazyDLL("kernel32.dll") - procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") - procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") - procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") - procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") - procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") -) - -type Writer struct { - out io.Writer - handle syscall.Handle - lastbuf bytes.Buffer - oldattr word -} - -func NewColorable(file *os.File) io.Writer { - if file == nil { - panic("nil passed instead of *os.File to NewColorable()") - } - - if isatty.IsTerminal(file.Fd()) { - var csbi consoleScreenBufferInfo - handle := syscall.Handle(file.Fd()) - procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) - return &Writer{out: file, handle: handle, oldattr: csbi.attributes} - } else { - return file - } -} - -func NewColorableStdout() io.Writer { - return NewColorable(os.Stdout) -} - -func NewColorableStderr() io.Writer { - return NewColorable(os.Stderr) -} - -var color256 = map[int]int{ - 0: 0x000000, - 1: 0x800000, - 2: 0x008000, - 3: 0x808000, - 4: 0x000080, - 5: 0x800080, - 6: 0x008080, - 7: 0xc0c0c0, - 8: 0x808080, - 9: 0xff0000, - 10: 0x00ff00, - 11: 0xffff00, - 12: 0x0000ff, - 13: 0xff00ff, - 14: 0x00ffff, - 15: 0xffffff, - 16: 0x000000, - 17: 0x00005f, - 18: 0x000087, - 19: 0x0000af, - 20: 0x0000d7, - 21: 0x0000ff, - 22: 0x005f00, - 23: 0x005f5f, - 24: 0x005f87, - 25: 0x005faf, - 26: 0x005fd7, - 27: 0x005fff, - 28: 0x008700, - 29: 0x00875f, - 30: 0x008787, - 31: 0x0087af, - 32: 0x0087d7, - 33: 0x0087ff, - 34: 0x00af00, - 35: 0x00af5f, - 36: 0x00af87, - 37: 0x00afaf, - 38: 0x00afd7, - 39: 0x00afff, - 40: 0x00d700, - 41: 0x00d75f, - 42: 0x00d787, - 43: 0x00d7af, - 44: 0x00d7d7, - 45: 0x00d7ff, - 46: 0x00ff00, - 47: 0x00ff5f, - 48: 0x00ff87, - 49: 0x00ffaf, - 50: 0x00ffd7, - 51: 0x00ffff, - 52: 0x5f0000, - 53: 0x5f005f, - 54: 0x5f0087, - 55: 0x5f00af, - 56: 0x5f00d7, - 57: 0x5f00ff, - 58: 0x5f5f00, - 59: 0x5f5f5f, - 60: 0x5f5f87, - 61: 0x5f5faf, - 62: 0x5f5fd7, - 63: 0x5f5fff, - 64: 0x5f8700, - 65: 0x5f875f, - 66: 0x5f8787, - 67: 0x5f87af, - 68: 0x5f87d7, - 69: 0x5f87ff, - 70: 0x5faf00, - 71: 0x5faf5f, - 72: 0x5faf87, - 73: 0x5fafaf, - 74: 0x5fafd7, - 75: 0x5fafff, - 76: 0x5fd700, - 77: 0x5fd75f, - 78: 0x5fd787, - 79: 0x5fd7af, - 80: 0x5fd7d7, - 81: 0x5fd7ff, - 82: 0x5fff00, - 83: 0x5fff5f, - 84: 0x5fff87, - 85: 0x5fffaf, - 86: 0x5fffd7, - 87: 0x5fffff, - 88: 0x870000, - 89: 0x87005f, - 90: 0x870087, - 91: 0x8700af, - 92: 0x8700d7, - 93: 0x8700ff, - 94: 0x875f00, - 95: 0x875f5f, - 96: 0x875f87, - 97: 0x875faf, - 98: 0x875fd7, - 99: 0x875fff, - 100: 0x878700, - 101: 0x87875f, - 102: 0x878787, - 103: 0x8787af, - 104: 0x8787d7, - 105: 0x8787ff, - 106: 0x87af00, - 107: 0x87af5f, - 108: 0x87af87, - 109: 0x87afaf, - 110: 0x87afd7, - 111: 0x87afff, - 112: 0x87d700, - 113: 0x87d75f, - 114: 0x87d787, - 115: 0x87d7af, - 116: 0x87d7d7, - 117: 0x87d7ff, - 118: 0x87ff00, - 119: 0x87ff5f, - 120: 0x87ff87, - 121: 0x87ffaf, - 122: 0x87ffd7, - 123: 0x87ffff, - 124: 0xaf0000, - 125: 0xaf005f, - 126: 0xaf0087, - 127: 0xaf00af, - 128: 0xaf00d7, - 129: 0xaf00ff, - 130: 0xaf5f00, - 131: 0xaf5f5f, - 132: 0xaf5f87, - 133: 0xaf5faf, - 134: 0xaf5fd7, - 135: 0xaf5fff, - 136: 0xaf8700, - 137: 0xaf875f, - 138: 0xaf8787, - 139: 0xaf87af, - 140: 0xaf87d7, - 141: 0xaf87ff, - 142: 0xafaf00, - 143: 0xafaf5f, - 144: 0xafaf87, - 145: 0xafafaf, - 146: 0xafafd7, - 147: 0xafafff, - 148: 0xafd700, - 149: 0xafd75f, - 150: 0xafd787, - 151: 0xafd7af, - 152: 0xafd7d7, - 153: 0xafd7ff, - 154: 0xafff00, - 155: 0xafff5f, - 156: 0xafff87, - 157: 0xafffaf, - 158: 0xafffd7, - 159: 0xafffff, - 160: 0xd70000, - 161: 0xd7005f, - 162: 0xd70087, - 163: 0xd700af, - 164: 0xd700d7, - 165: 0xd700ff, - 166: 0xd75f00, - 167: 0xd75f5f, - 168: 0xd75f87, - 169: 0xd75faf, - 170: 0xd75fd7, - 171: 0xd75fff, - 172: 0xd78700, - 173: 0xd7875f, - 174: 0xd78787, - 175: 0xd787af, - 176: 0xd787d7, - 177: 0xd787ff, - 178: 0xd7af00, - 179: 0xd7af5f, - 180: 0xd7af87, - 181: 0xd7afaf, - 182: 0xd7afd7, - 183: 0xd7afff, - 184: 0xd7d700, - 185: 0xd7d75f, - 186: 0xd7d787, - 187: 0xd7d7af, - 188: 0xd7d7d7, - 189: 0xd7d7ff, - 190: 0xd7ff00, - 191: 0xd7ff5f, - 192: 0xd7ff87, - 193: 0xd7ffaf, - 194: 0xd7ffd7, - 195: 0xd7ffff, - 196: 0xff0000, - 197: 0xff005f, - 198: 0xff0087, - 199: 0xff00af, - 200: 0xff00d7, - 201: 0xff00ff, - 202: 0xff5f00, - 203: 0xff5f5f, - 204: 0xff5f87, - 205: 0xff5faf, - 206: 0xff5fd7, - 207: 0xff5fff, - 208: 0xff8700, - 209: 0xff875f, - 210: 0xff8787, - 211: 0xff87af, - 212: 0xff87d7, - 213: 0xff87ff, - 214: 0xffaf00, - 215: 0xffaf5f, - 216: 0xffaf87, - 217: 0xffafaf, - 218: 0xffafd7, - 219: 0xffafff, - 220: 0xffd700, - 221: 0xffd75f, - 222: 0xffd787, - 223: 0xffd7af, - 224: 0xffd7d7, - 225: 0xffd7ff, - 226: 0xffff00, - 227: 0xffff5f, - 228: 0xffff87, - 229: 0xffffaf, - 230: 0xffffd7, - 231: 0xffffff, - 232: 0x080808, - 233: 0x121212, - 234: 0x1c1c1c, - 235: 0x262626, - 236: 0x303030, - 237: 0x3a3a3a, - 238: 0x444444, - 239: 0x4e4e4e, - 240: 0x585858, - 241: 0x626262, - 242: 0x6c6c6c, - 243: 0x767676, - 244: 0x808080, - 245: 0x8a8a8a, - 246: 0x949494, - 247: 0x9e9e9e, - 248: 0xa8a8a8, - 249: 0xb2b2b2, - 250: 0xbcbcbc, - 251: 0xc6c6c6, - 252: 0xd0d0d0, - 253: 0xdadada, - 254: 0xe4e4e4, - 255: 0xeeeeee, -} - -func (w *Writer) Write(data []byte) (n int, err error) { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - - er := bytes.NewBuffer(data) -loop: - for { - r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - if r1 == 0 { - break loop - } - - c1, _, err := er.ReadRune() - if err != nil { - break loop - } - if c1 != 0x1b { - fmt.Fprint(w.out, string(c1)) - continue - } - c2, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - break loop - } - if c2 != 0x5b { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - continue - } - - var buf bytes.Buffer - var m rune - for { - c, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - w.lastbuf.Write(buf.Bytes()) - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - m = c - break - } - buf.Write([]byte(string(c))) - } - - var csbi consoleScreenBufferInfo - switch m { - case 'A': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'B': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'C': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'D': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - if n, err = strconv.Atoi(buf.String()); err == nil { - var csbi consoleScreenBufferInfo - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - } - case 'E': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y += short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'F': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = 0 - csbi.cursorPosition.y -= short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'G': - n, err = strconv.Atoi(buf.String()) - if err != nil { - continue - } - procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) - csbi.cursorPosition.x = short(n) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'H': - token := strings.Split(buf.String(), ";") - if len(token) != 2 { - continue - } - n1, err := strconv.Atoi(token[0]) - if err != nil { - continue - } - n2, err := strconv.Atoi(token[1]) - if err != nil { - continue - } - csbi.cursorPosition.x = short(n2) - csbi.cursorPosition.x = short(n1) - procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) - case 'J': - n, err := strconv.Atoi(buf.String()) - if err != nil { - continue - } - var cursor coord - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top} - } - var count, written dword - count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'K': - n, err := strconv.Atoi(buf.String()) - if err != nil { - continue - } - var cursor coord - switch n { - case 0: - cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} - case 1: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - case 2: - cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} - } - var count, written dword - count = dword(csbi.size.x - csbi.cursorPosition.x) - procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) - case 'm': - attr := csbi.attributes - cs := buf.String() - if cs == "" { - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) - continue - } - token := strings.Split(cs, ";") - for i := 0; i < len(token); i += 1 { - ns := token[i] - if n, err = strconv.Atoi(ns); err == nil { - switch { - case n == 0 || n == 100: - attr = w.oldattr - case 1 <= n && n <= 5: - attr |= foregroundIntensity - case n == 7: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 22 == n || n == 25 || n == 25: - attr |= foregroundIntensity - case n == 27: - attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) - case 30 <= n && n <= 37: - attr = (attr & backgroundMask) - if (n-30)&1 != 0 { - attr |= foregroundRed - } - if (n-30)&2 != 0 { - attr |= foregroundGreen - } - if (n-30)&4 != 0 { - attr |= foregroundBlue - } - case n == 38: // set foreground color. - if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256foreAttr == nil { - n256setup() - } - attr &= backgroundMask - attr |= n256foreAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & backgroundMask) - } - case n == 39: // reset foreground color. - attr &= backgroundMask - attr |= w.oldattr & foregroundMask - case 40 <= n && n <= 47: - attr = (attr & foregroundMask) - if (n-40)&1 != 0 { - attr |= backgroundRed - } - if (n-40)&2 != 0 { - attr |= backgroundGreen - } - if (n-40)&4 != 0 { - attr |= backgroundBlue - } - case n == 48: // set background color. - if i < len(token)-2 && token[i+1] == "5" { - if n256, err := strconv.Atoi(token[i+2]); err == nil { - if n256backAttr == nil { - n256setup() - } - attr &= foregroundMask - attr |= n256backAttr[n256] - i += 2 - } - } else { - attr = attr & (w.oldattr & foregroundMask) - } - case n == 49: // reset foreground color. - attr &= foregroundMask - attr |= w.oldattr & backgroundMask - case 90 <= n && n <= 97: - attr = (attr & backgroundMask) - attr |= foregroundIntensity - if (n-90)&1 != 0 { - attr |= foregroundRed - } - if (n-90)&2 != 0 { - attr |= foregroundGreen - } - if (n-90)&4 != 0 { - attr |= foregroundBlue - } - case 100 <= n && n <= 107: - attr = (attr & foregroundMask) - attr |= backgroundIntensity - if (n-100)&1 != 0 { - attr |= backgroundRed - } - if (n-100)&2 != 0 { - attr |= backgroundGreen - } - if (n-100)&4 != 0 { - attr |= backgroundBlue - } - } - procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) - } - } - } - } - return len(data) - w.lastbuf.Len(), nil -} - -type consoleColor struct { - rgb int - red bool - green bool - blue bool - intensity bool -} - -func (c consoleColor) foregroundAttr() (attr word) { - if c.red { - attr |= foregroundRed - } - if c.green { - attr |= foregroundGreen - } - if c.blue { - attr |= foregroundBlue - } - if c.intensity { - attr |= foregroundIntensity - } - return -} - -func (c consoleColor) backgroundAttr() (attr word) { - if c.red { - attr |= backgroundRed - } - if c.green { - attr |= backgroundGreen - } - if c.blue { - attr |= backgroundBlue - } - if c.intensity { - attr |= backgroundIntensity - } - return -} - -var color16 = []consoleColor{ - consoleColor{0x000000, false, false, false, false}, - consoleColor{0x000080, false, false, true, false}, - consoleColor{0x008000, false, true, false, false}, - consoleColor{0x008080, false, true, true, false}, - consoleColor{0x800000, true, false, false, false}, - consoleColor{0x800080, true, false, true, false}, - consoleColor{0x808000, true, true, false, false}, - consoleColor{0xc0c0c0, true, true, true, false}, - consoleColor{0x808080, false, false, false, true}, - consoleColor{0x0000ff, false, false, true, true}, - consoleColor{0x00ff00, false, true, false, true}, - consoleColor{0x00ffff, false, true, true, true}, - consoleColor{0xff0000, true, false, false, true}, - consoleColor{0xff00ff, true, false, true, true}, - consoleColor{0xffff00, true, true, false, true}, - consoleColor{0xffffff, true, true, true, true}, -} - -type hsv struct { - h, s, v float32 -} - -func (a hsv) dist(b hsv) float32 { - dh := a.h - b.h - switch { - case dh > 0.5: - dh = 1 - dh - case dh < -0.5: - dh = -1 - dh - } - ds := a.s - b.s - dv := a.v - b.v - return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) -} - -func toHSV(rgb int) hsv { - r, g, b := float32((rgb&0xFF0000)>>16)/256.0, - float32((rgb&0x00FF00)>>8)/256.0, - float32(rgb&0x0000FF)/256.0 - min, max := minmax3f(r, g, b) - h := max - min - if h > 0 { - if max == r { - h = (g - b) / h - if h < 0 { - h += 6 - } - } else if max == g { - h = 2 + (b-r)/h - } else { - h = 4 + (r-g)/h - } - } - h /= 6.0 - s := max - min - if max != 0 { - s /= max - } - v := max - return hsv{h: h, s: s, v: v} -} - -type hsvTable []hsv - -func toHSVTable(rgbTable []consoleColor) hsvTable { - t := make(hsvTable, len(rgbTable)) - for i, c := range rgbTable { - t[i] = toHSV(c.rgb) - } - return t -} - -func (t hsvTable) find(rgb int) consoleColor { - hsv := toHSV(rgb) - n := 7 - l := float32(5.0) - for i, p := range t { - d := hsv.dist(p) - if d < l { - l, n = d, i - } - } - return color16[n] -} - -func minmax3f(a, b, c float32) (min, max float32) { - if a < b { - if b < c { - return a, c - } else if a < c { - return a, b - } else { - return c, b - } - } else { - if a < c { - return b, c - } else if b < c { - return b, a - } else { - return c, a - } - } -} - -var n256foreAttr []word -var n256backAttr []word - -func n256setup() { - n256foreAttr = make([]word, 256) - n256backAttr = make([]word, 256) - t := toHSVTable(color16) - for i, rgb := range color256 { - c := t.find(rgb) - n256foreAttr[i] = c.foregroundAttr() - n256backAttr[i] = c.backgroundAttr() - } -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go deleted file mode 100644 index fb976dbd8b..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable/noncolorable.go +++ /dev/null @@ -1,57 +0,0 @@ -package colorable - -import ( - "bytes" - "fmt" - "io" -) - -type NonColorable struct { - out io.Writer - lastbuf bytes.Buffer -} - -func NewNonColorable(w io.Writer) io.Writer { - return &NonColorable{out: w} -} - -func (w *NonColorable) Write(data []byte) (n int, err error) { - er := bytes.NewBuffer(data) -loop: - for { - c1, _, err := er.ReadRune() - if err != nil { - break loop - } - if c1 != 0x1b { - fmt.Fprint(w.out, string(c1)) - continue - } - c2, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - break loop - } - if c2 != 0x5b { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - continue - } - - var buf bytes.Buffer - for { - c, _, err := er.ReadRune() - if err != nil { - w.lastbuf.WriteRune(c1) - w.lastbuf.WriteRune(c2) - w.lastbuf.Write(buf.Bytes()) - break loop - } - if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { - break - } - buf.Write([]byte(string(c))) - } - } - return len(data) - w.lastbuf.Len(), nil -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE deleted file mode 100644 index 65dc692b6b..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -Copyright (c) Yasuhiro MATSUMOTO - -MIT License (Expat) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md deleted file mode 100644 index 74845de4a2..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# go-isatty - -isatty for golang - -## Usage - -```go -package main - -import ( - "fmt" - "github.com/mattn/go-isatty" - "os" -) - -func main() { - if isatty.IsTerminal(os.Stdout.Fd()) { - fmt.Println("Is Terminal") - } else { - fmt.Println("Is Not Terminal") - } -} -``` - -## Installation - -``` -$ go get github.com/mattn/go-isatty -``` - -# License - -MIT - -# Author - -Yasuhiro Matsumoto (a.k.a mattn) diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go deleted file mode 100644 index 17d4f90ebc..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package isatty implements interface to isatty -package isatty diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go deleted file mode 100644 index 83c588773c..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_appengine.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build appengine - -package isatty - -// IsTerminal returns true if the file descriptor is terminal which -// is always false on on appengine classic which is a sandboxed PaaS. -func IsTerminal(fd uintptr) bool { - return false -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go deleted file mode 100644 index 98ffe86a4b..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_bsd.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build darwin freebsd openbsd netbsd -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TIOCGETA - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go deleted file mode 100644 index 9d24bac1db..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_linux.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build linux -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -const ioctlReadTermios = syscall.TCGETS - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var termios syscall.Termios - _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) - return err == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go deleted file mode 100644 index 1f0c6bf53d..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_solaris.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build solaris -// +build !appengine - -package isatty - -import ( - "golang.org/x/sys/unix" -) - -// IsTerminal returns true if the given file descriptor is a terminal. -// see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c -func IsTerminal(fd uintptr) bool { - var termio unix.Termio - err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) - return err == nil -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go b/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go deleted file mode 100644 index 83c398b16d..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/stenographer/support/go-isatty/isatty_windows.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build windows -// +build !appengine - -package isatty - -import ( - "syscall" - "unsafe" -) - -var kernel32 = syscall.NewLazyDLL("kernel32.dll") -var procGetConsoleMode = kernel32.NewProc("GetConsoleMode") - -// IsTerminal return true if the file descriptor is terminal. -func IsTerminal(fd uintptr) bool { - var st uint32 - r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) - return r != 0 && e == 0 -} diff --git a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go b/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go deleted file mode 100644 index 657dfe726e..0000000000 --- a/vendor/github.com/onsi/ginkgo/reporters/teamcity_reporter.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - -TeamCity Reporter for Ginkgo - -Makes use of TeamCity's support for Service Messages -http://confluence.jetbrains.com/display/TCD7/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-ReportingTests -*/ - -package reporters - -import ( - "fmt" - "github.com/onsi/ginkgo/config" - "github.com/onsi/ginkgo/types" - "io" - "strings" -) - -const ( - messageId = "##teamcity" -) - -type TeamCityReporter struct { - writer io.Writer - testSuiteName string -} - -func NewTeamCityReporter(writer io.Writer) *TeamCityReporter { - return &TeamCityReporter{ - writer: writer, - } -} - -func (reporter *TeamCityReporter) SpecSuiteWillBegin(config config.GinkgoConfigType, summary *types.SuiteSummary) { - reporter.testSuiteName = escape(summary.SuiteDescription) - fmt.Fprintf(reporter.writer, "%s[testSuiteStarted name='%s']", messageId, reporter.testSuiteName) -} - -func (reporter *TeamCityReporter) BeforeSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("BeforeSuite", setupSummary) -} - -func (reporter *TeamCityReporter) AfterSuiteDidRun(setupSummary *types.SetupSummary) { - reporter.handleSetupSummary("AfterSuite", setupSummary) -} - -func (reporter *TeamCityReporter) handleSetupSummary(name string, setupSummary *types.SetupSummary) { - if setupSummary.State != types.SpecStatePassed { - testName := escape(name) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) - message := escape(setupSummary.Failure.ComponentCodeLocation.String()) - details := escape(setupSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - durationInMilliseconds := setupSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) - } -} - -func (reporter *TeamCityReporter) SpecWillRun(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - fmt.Fprintf(reporter.writer, "%s[testStarted name='%s']", messageId, testName) -} - -func (reporter *TeamCityReporter) SpecDidComplete(specSummary *types.SpecSummary) { - testName := escape(strings.Join(specSummary.ComponentTexts[1:], " ")) - - if specSummary.State == types.SpecStateFailed || specSummary.State == types.SpecStateTimedOut || specSummary.State == types.SpecStatePanicked { - message := escape(specSummary.Failure.ComponentCodeLocation.String()) - details := escape(specSummary.Failure.Message) - fmt.Fprintf(reporter.writer, "%s[testFailed name='%s' message='%s' details='%s']", messageId, testName, message, details) - } - if specSummary.State == types.SpecStateSkipped || specSummary.State == types.SpecStatePending { - fmt.Fprintf(reporter.writer, "%s[testIgnored name='%s']", messageId, testName) - } - - durationInMilliseconds := specSummary.RunTime.Seconds() * 1000 - fmt.Fprintf(reporter.writer, "%s[testFinished name='%s' duration='%v']", messageId, testName, durationInMilliseconds) -} - -func (reporter *TeamCityReporter) SpecSuiteDidEnd(summary *types.SuiteSummary) { - fmt.Fprintf(reporter.writer, "%s[testSuiteFinished name='%s']", messageId, reporter.testSuiteName) -} - -func escape(output string) string { - output = strings.Replace(output, "|", "||", -1) - output = strings.Replace(output, "'", "|'", -1) - output = strings.Replace(output, "\n", "|n", -1) - output = strings.Replace(output, "\r", "|r", -1) - output = strings.Replace(output, "[", "|[", -1) - output = strings.Replace(output, "]", "|]", -1) - return output -} diff --git a/vendor/github.com/onsi/ginkgo/types/code_location.go b/vendor/github.com/onsi/ginkgo/types/code_location.go deleted file mode 100644 index 935a89e136..0000000000 --- a/vendor/github.com/onsi/ginkgo/types/code_location.go +++ /dev/null @@ -1,15 +0,0 @@ -package types - -import ( - "fmt" -) - -type CodeLocation struct { - FileName string - LineNumber int - FullStackTrace string -} - -func (codeLocation CodeLocation) String() string { - return fmt.Sprintf("%s:%d", codeLocation.FileName, codeLocation.LineNumber) -} diff --git a/vendor/github.com/onsi/ginkgo/types/synchronization.go b/vendor/github.com/onsi/ginkgo/types/synchronization.go deleted file mode 100644 index fdd6ed5bdf..0000000000 --- a/vendor/github.com/onsi/ginkgo/types/synchronization.go +++ /dev/null @@ -1,30 +0,0 @@ -package types - -import ( - "encoding/json" -) - -type RemoteBeforeSuiteState int - -const ( - RemoteBeforeSuiteStateInvalid RemoteBeforeSuiteState = iota - - RemoteBeforeSuiteStatePending - RemoteBeforeSuiteStatePassed - RemoteBeforeSuiteStateFailed - RemoteBeforeSuiteStateDisappeared -) - -type RemoteBeforeSuiteData struct { - Data []byte - State RemoteBeforeSuiteState -} - -func (r RemoteBeforeSuiteData) ToJSON() []byte { - data, _ := json.Marshal(r) - return data -} - -type RemoteAfterSuiteData struct { - CanRun bool -} diff --git a/vendor/github.com/onsi/ginkgo/types/types.go b/vendor/github.com/onsi/ginkgo/types/types.go deleted file mode 100644 index baf1bd1c47..0000000000 --- a/vendor/github.com/onsi/ginkgo/types/types.go +++ /dev/null @@ -1,173 +0,0 @@ -package types - -import ( - "strconv" - "time" -) - -const GINKGO_FOCUS_EXIT_CODE = 197 - -/* -SuiteSummary represents the a summary of the test suite and is passed to both -Reporter.SpecSuiteWillBegin -Reporter.SpecSuiteDidEnd - -this is unfortunate as these two methods should receive different objects. When running in parallel -each node does not deterministically know how many specs it will end up running. - -Unfortunately making such a change would break backward compatibility. - -Until Ginkgo 2.0 comes out we will continue to reuse this struct but populate unkown fields -with -1. -*/ -type SuiteSummary struct { - SuiteDescription string - SuiteSucceeded bool - SuiteID string - - NumberOfSpecsBeforeParallelization int - NumberOfTotalSpecs int - NumberOfSpecsThatWillBeRun int - NumberOfPendingSpecs int - NumberOfSkippedSpecs int - NumberOfPassedSpecs int - NumberOfFailedSpecs int - // Flaked specs are those that failed initially, but then passed on a - // subsequent try. - NumberOfFlakedSpecs int - RunTime time.Duration -} - -type SpecSummary struct { - ComponentTexts []string - ComponentCodeLocations []CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - IsMeasurement bool - NumberOfSamples int - Measurements map[string]*SpecMeasurement - - CapturedOutput string - SuiteID string -} - -func (s SpecSummary) HasFailureState() bool { - return s.State.IsFailure() -} - -func (s SpecSummary) TimedOut() bool { - return s.State == SpecStateTimedOut -} - -func (s SpecSummary) Panicked() bool { - return s.State == SpecStatePanicked -} - -func (s SpecSummary) Failed() bool { - return s.State == SpecStateFailed -} - -func (s SpecSummary) Passed() bool { - return s.State == SpecStatePassed -} - -func (s SpecSummary) Skipped() bool { - return s.State == SpecStateSkipped -} - -func (s SpecSummary) Pending() bool { - return s.State == SpecStatePending -} - -type SetupSummary struct { - ComponentType SpecComponentType - CodeLocation CodeLocation - - State SpecState - RunTime time.Duration - Failure SpecFailure - - CapturedOutput string - SuiteID string -} - -type SpecFailure struct { - Message string - Location CodeLocation - ForwardedPanic string - - ComponentIndex int - ComponentType SpecComponentType - ComponentCodeLocation CodeLocation -} - -type SpecMeasurement struct { - Name string - Info interface{} - Order int - - Results []float64 - - Smallest float64 - Largest float64 - Average float64 - StdDeviation float64 - - SmallestLabel string - LargestLabel string - AverageLabel string - Units string - Precision int -} - -func (s SpecMeasurement) PrecisionFmt() string { - if s.Precision == 0 { - return "%f" - } - - str := strconv.Itoa(s.Precision) - - return "%." + str + "f" -} - -type SpecState uint - -const ( - SpecStateInvalid SpecState = iota - - SpecStatePending - SpecStateSkipped - SpecStatePassed - SpecStateFailed - SpecStatePanicked - SpecStateTimedOut -) - -func (state SpecState) IsFailure() bool { - return state == SpecStateTimedOut || state == SpecStatePanicked || state == SpecStateFailed -} - -type SpecComponentType uint - -const ( - SpecComponentTypeInvalid SpecComponentType = iota - - SpecComponentTypeContainer - SpecComponentTypeBeforeSuite - SpecComponentTypeAfterSuite - SpecComponentTypeBeforeEach - SpecComponentTypeJustBeforeEach - SpecComponentTypeAfterEach - SpecComponentTypeIt - SpecComponentTypeMeasure -) - -type FlagType uint - -const ( - FlagTypeNone FlagType = iota - FlagTypeFocused - FlagTypePending -) diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md deleted file mode 100644 index a3e8ee4447..0000000000 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ /dev/null @@ -1,74 +0,0 @@ -## HEAD - -## 1.2.0 - -Improvements: - -- Added `BeSent` which attempts to send a value down a channel and fails if the attempt blocks. Can be paired with `Eventually` to safely send a value down a channel with a timeout. -- `Ω`, `Expect`, `Eventually`, and `Consistently` now immediately `panic` if there is no registered fail handler. This is always a mistake that can hide failing tests. -- `Receive()` no longer errors when passed a closed channel, it's perfectly fine to attempt to read from a closed channel so Ω(c).Should(Receive()) always fails and Ω(c).ShoudlNot(Receive()) always passes with a closed channel. -- Added `HavePrefix` and `HaveSuffix` matchers. -- `ghttp` can now handle concurrent requests. -- Added `Succeed` which allows one to write `Ω(MyFunction()).Should(Succeed())`. -- Improved `ghttp`'s behavior around failing assertions and panics: - - If a registered handler makes a failing assertion `ghttp` will return `500`. - - If a registered handler panics, `ghttp` will return `500` *and* fail the test. This is new behavior that may cause existing code to break. This code is almost certainly incorrect and creating a false positive. -- `ghttp` servers can take an `io.Writer`. `ghttp` will write a line to the writer when each request arrives. -- Added `WithTransform` matcher to allow munging input data before feeding into the relevant matcher -- Added boolean `And`, `Or`, and `Not` matchers to allow creating composite matchers -- Added `gbytes.TimeoutCloser`, `gbytes.TimeoutReader`, and `gbytes.TimeoutWriter` - these are convenience wrappers that timeout if the underlying Closer/Reader/Writer does not return within the alloted time. -- Added `gbytes.BufferReader` - this constructs a `gbytes.Buffer` that asynchronously reads the passed-in `io.Reader` into its buffer. - -Bug Fixes: -- gexec: `session.Wait` now uses `EventuallyWithOffset` to get the right line number in the failure. -- `ContainElement` no longer bails if a passed-in matcher errors. - -## 1.0 (8/2/2014) - -No changes. Dropping "beta" from the version number. - -## 1.0.0-beta (7/8/2014) -Breaking Changes: - -- Changed OmegaMatcher interface. Instead of having `Match` return failure messages, two new methods `FailureMessage` and `NegatedFailureMessage` are called instead. -- Moved and renamed OmegaFailHandler to types.GomegaFailHandler and OmegaMatcher to types.GomegaMatcher. Any references to OmegaMatcher in any custom matchers will need to be changed to point to types.GomegaMatcher - -New Test-Support Features: - -- `ghttp`: supports testing http clients - - Provides a flexible fake http server - - Provides a collection of chainable http handlers that perform assertions. -- `gbytes`: supports making ordered assertions against streams of data - - Provides a `gbytes.Buffer` - - Provides a `Say` matcher to perform ordered assertions against output data -- `gexec`: supports testing external processes - - Provides support for building Go binaries - - Wraps and starts `exec.Cmd` commands - - Makes it easy to assert against stdout and stderr - - Makes it easy to send signals and wait for processes to exit - - Provides an `Exit` matcher to assert against exit code. - -DSL Changes: - -- `Eventually` and `Consistently` can accept `time.Duration` interval and polling inputs. -- The default timeouts for `Eventually` and `Consistently` are now configurable. - -New Matchers: - -- `ConsistOf`: order-independent assertion against the elements of an array/slice or keys of a map. -- `BeTemporally`: like `BeNumerically` but for `time.Time` -- `HaveKeyWithValue`: asserts a map has a given key with the given value. - -Updated Matchers: - -- `Receive` matcher can take a matcher as an argument and passes only if the channel under test receives an objet that satisfies the passed-in matcher. -- Matchers that implement `MatchMayChangeInTheFuture(actual interface{}) bool` can inform `Eventually` and/or `Consistently` when a match has no chance of changing status in the future. For example, `Receive` returns `false` when a channel is closed. - -Misc: - -- Start using semantic versioning -- Start maintaining changelog - -Major refactor: - -- Pull out Gomega's internal to `internal` diff --git a/vendor/github.com/onsi/gomega/CONTRIBUTING.md b/vendor/github.com/onsi/gomega/CONTRIBUTING.md deleted file mode 100644 index 73d4020e6b..0000000000 --- a/vendor/github.com/onsi/gomega/CONTRIBUTING.md +++ /dev/null @@ -1,11 +0,0 @@ -# Contributing to Gomega - -Your contributions to Gomega are essential for its long-term maintenance and improvement. To make a contribution: - -- Please **open an issue first** - describe what problem you are trying to solve and give the community a forum for input and feedback ahead of investing time in writing code! -- Ensure adequate test coverage: - - Make sure to add appropriate unit tests - - Please run all tests locally (`ginkgo -r -p`) and make sure they go green before submitting the PR -- Update the documentation. In addition to standard `godoc` comments Gomega has extensive documentation on the `gh-pages` branch. If relevant, please submit a docs PR to that branch alongside your code PR. - -Thanks for supporting Gomega! \ No newline at end of file diff --git a/vendor/github.com/onsi/gomega/LICENSE b/vendor/github.com/onsi/gomega/LICENSE deleted file mode 100644 index 9415ee72c1..0000000000 --- a/vendor/github.com/onsi/gomega/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013-2014 Onsi Fakhouri - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/onsi/gomega/README.md b/vendor/github.com/onsi/gomega/README.md deleted file mode 100644 index 159be35907..0000000000 --- a/vendor/github.com/onsi/gomega/README.md +++ /dev/null @@ -1,21 +0,0 @@ -![Gomega: Ginkgo's Preferred Matcher Library](http://onsi.github.io/gomega/images/gomega.png) - -[![Build Status](https://travis-ci.org/onsi/gomega.svg)](https://travis-ci.org/onsi/gomega) - -Jump straight to the [docs](http://onsi.github.io/gomega/) to learn about Gomega, including a list of [all available matchers](http://onsi.github.io/gomega/#provided-matchers). - -If you have a question, comment, bug report, feature request, etc. please open a GitHub issue. - -## [Ginkgo](http://github.com/onsi/ginkgo): a BDD Testing Framework for Golang - -Learn more about Ginkgo [here](http://onsi.github.io/ginkgo/) - -## Community Matchers - -A collection of community matchers is available on the [wiki](https://github.com/onsi/gomega/wiki). - -## License - -Gomega is MIT-Licensed - -The `ConsistOf` matcher uses [goraph](https://github.com/amitkgupta/goraph) which is embedded in the source to simplify distribution. goraph has an MIT license. diff --git a/vendor/github.com/onsi/gomega/format/format.go b/vendor/github.com/onsi/gomega/format/format.go deleted file mode 100644 index e206ee59a4..0000000000 --- a/vendor/github.com/onsi/gomega/format/format.go +++ /dev/null @@ -1,379 +0,0 @@ -/* -Gomega's format package pretty-prints objects. It explores input objects recursively and generates formatted, indented output with type information. -*/ -package format - -import ( - "fmt" - "reflect" - "strconv" - "strings" - "time" -) - -// Use MaxDepth to set the maximum recursion depth when printing deeply nested objects -var MaxDepth = uint(10) - -/* -By default, all objects (even those that implement fmt.Stringer and fmt.GoStringer) are recursively inspected to generate output. - -Set UseStringerRepresentation = true to use GoString (for fmt.GoStringers) or String (for fmt.Stringer) instead. - -Note that GoString and String don't always have all the information you need to understand why a test failed! -*/ -var UseStringerRepresentation = false - -/* -Print the content of context objects. By default it will be suppressed. - -Set PrintContextObjects = true to enable printing of the context internals. -*/ -var PrintContextObjects = false - -// Ctx interface defined here to keep backwards compatability with go < 1.7 -// It matches the context.Context interface -type Ctx interface { - Deadline() (deadline time.Time, ok bool) - Done() <-chan struct{} - Err() error - Value(key interface{}) interface{} -} - -var contextType = reflect.TypeOf((*Ctx)(nil)).Elem() -var timeType = reflect.TypeOf(time.Time{}) - -//The default indentation string emitted by the format package -var Indent = " " - -var longFormThreshold = 20 - -/* -Generates a formatted matcher success/failure message of the form: - - Expected - - - - -If expected is omited, then the message looks like: - - Expected - - -*/ -func Message(actual interface{}, message string, expected ...interface{}) string { - if len(expected) == 0 { - return fmt.Sprintf("Expected\n%s\n%s", Object(actual, 1), message) - } - return fmt.Sprintf("Expected\n%s\n%s\n%s", Object(actual, 1), message, Object(expected[0], 1)) -} - -/* - -Generates a nicely formatted matcher success / failure message - -Much like Message(...), but it attempts to pretty print diffs in strings - -Expected - : "...aaaaabaaaaa..." -to equal | - : "...aaaaazaaaaa..." - -*/ - -func MessageWithDiff(actual, message, expected string) string { - if len(actual) >= truncateThreshold && len(expected) >= truncateThreshold { - diffPoint := findFirstMismatch(actual, expected) - formattedActual := truncateAndFormat(actual, diffPoint) - formattedExpected := truncateAndFormat(expected, diffPoint) - - spacesBeforeFormattedMismatch := findFirstMismatch(formattedActual, formattedExpected) - - tabLength := 4 - spaceFromMessageToActual := tabLength + len(": ") - len(message) - padding := strings.Repeat(" ", spaceFromMessageToActual+spacesBeforeFormattedMismatch) + "|" - return Message(formattedActual, message+padding, formattedExpected) - } - return Message(actual, message, expected) -} - -func truncateAndFormat(str string, index int) string { - leftPadding := `...` - rightPadding := `...` - - start := index - charactersAroundMismatchToInclude - if start < 0 { - start = 0 - leftPadding = "" - } - - // slice index must include the mis-matched character - lengthOfMismatchedCharacter := 1 - end := index + charactersAroundMismatchToInclude + lengthOfMismatchedCharacter - if end > len(str) { - end = len(str) - rightPadding = "" - - } - return fmt.Sprintf("\"%s\"", leftPadding+str[start:end]+rightPadding) -} - -func findFirstMismatch(a, b string) int { - aSlice := strings.Split(a, "") - bSlice := strings.Split(b, "") - - for index, str := range aSlice { - if index > len(b) - 1 { - return index - } - if str != bSlice[index] { - return index - } - } - - if len(b) > len(a) { - return len(a) + 1 - } - - return 0 -} - -const ( - truncateThreshold = 50 - charactersAroundMismatchToInclude = 5 -) - -/* -Pretty prints the passed in object at the passed in indentation level. - -Object recurses into deeply nested objects emitting pretty-printed representations of their components. - -Modify format.MaxDepth to control how deep the recursion is allowed to go -Set format.UseStringerRepresentation to true to return object.GoString() or object.String() when available instead of -recursing into the object. - -Set PrintContextObjects to true to print the content of objects implementing context.Context -*/ -func Object(object interface{}, indentation uint) string { - indent := strings.Repeat(Indent, int(indentation)) - value := reflect.ValueOf(object) - return fmt.Sprintf("%s<%s>: %s", indent, formatType(object), formatValue(value, indentation)) -} - -/* -IndentString takes a string and indents each line by the specified amount. -*/ -func IndentString(s string, indentation uint) string { - components := strings.Split(s, "\n") - result := "" - indent := strings.Repeat(Indent, int(indentation)) - for i, component := range components { - result += indent + component - if i < len(components)-1 { - result += "\n" - } - } - - return result -} - -func formatType(object interface{}) string { - t := reflect.TypeOf(object) - if t == nil { - return "nil" - } - switch t.Kind() { - case reflect.Chan: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Ptr: - return fmt.Sprintf("%T | %p", object, object) - case reflect.Slice: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d, cap:%d", object, v.Len(), v.Cap()) - case reflect.Map: - v := reflect.ValueOf(object) - return fmt.Sprintf("%T | len:%d", object, v.Len()) - default: - return fmt.Sprintf("%T", object) - } -} - -func formatValue(value reflect.Value, indentation uint) string { - if indentation > MaxDepth { - return "..." - } - - if isNilValue(value) { - return "nil" - } - - if UseStringerRepresentation { - if value.CanInterface() { - obj := value.Interface() - switch x := obj.(type) { - case fmt.GoStringer: - return x.GoString() - case fmt.Stringer: - return x.String() - } - } - } - - if !PrintContextObjects { - if value.Type().Implements(contextType) && indentation > 1 { - return "" - } - } - - switch value.Kind() { - case reflect.Bool: - return fmt.Sprintf("%v", value.Bool()) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return fmt.Sprintf("%v", value.Int()) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return fmt.Sprintf("%v", value.Uint()) - case reflect.Uintptr: - return fmt.Sprintf("0x%x", value.Uint()) - case reflect.Float32, reflect.Float64: - return fmt.Sprintf("%v", value.Float()) - case reflect.Complex64, reflect.Complex128: - return fmt.Sprintf("%v", value.Complex()) - case reflect.Chan: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Func: - return fmt.Sprintf("0x%x", value.Pointer()) - case reflect.Ptr: - return formatValue(value.Elem(), indentation) - case reflect.Slice: - return formatSlice(value, indentation) - case reflect.String: - return formatString(value.String(), indentation) - case reflect.Array: - return formatSlice(value, indentation) - case reflect.Map: - return formatMap(value, indentation) - case reflect.Struct: - if value.Type() == timeType && value.CanInterface() { - t, _ := value.Interface().(time.Time) - return t.Format(time.RFC3339Nano) - } - return formatStruct(value, indentation) - case reflect.Interface: - return formatValue(value.Elem(), indentation) - default: - if value.CanInterface() { - return fmt.Sprintf("%#v", value.Interface()) - } - return fmt.Sprintf("%#v", value) - } -} - -func formatString(object interface{}, indentation uint) string { - if indentation == 1 { - s := fmt.Sprintf("%s", object) - components := strings.Split(s, "\n") - result := "" - for i, component := range components { - if i == 0 { - result += component - } else { - result += Indent + component - } - if i < len(components)-1 { - result += "\n" - } - } - - return fmt.Sprintf("%s", result) - } else { - return fmt.Sprintf("%q", object) - } -} - -func formatSlice(v reflect.Value, indentation uint) string { - if v.Kind() == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && isPrintableString(string(v.Bytes())) { - return formatString(v.Bytes(), indentation) - } - - l := v.Len() - result := make([]string, l) - longest := 0 - for i := 0; i < l; i++ { - result[i] = formatValue(v.Index(i), indentation+1) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("[\n%s%s,\n%s]", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("[%s]", strings.Join(result, ", ")) -} - -func formatMap(v reflect.Value, indentation uint) string { - l := v.Len() - result := make([]string, l) - - longest := 0 - for i, key := range v.MapKeys() { - value := v.MapIndex(key) - result[i] = fmt.Sprintf("%s: %s", formatValue(key, indentation+1), formatValue(value, indentation+1)) - if len(result[i]) > longest { - longest = len(result[i]) - } - } - - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) -} - -func formatStruct(v reflect.Value, indentation uint) string { - t := v.Type() - - l := v.NumField() - result := []string{} - longest := 0 - for i := 0; i < l; i++ { - structField := t.Field(i) - fieldEntry := v.Field(i) - representation := fmt.Sprintf("%s: %s", structField.Name, formatValue(fieldEntry, indentation+1)) - result = append(result, representation) - if len(representation) > longest { - longest = len(representation) - } - } - if longest > longFormThreshold { - indenter := strings.Repeat(Indent, int(indentation)) - return fmt.Sprintf("{\n%s%s,\n%s}", indenter+Indent, strings.Join(result, ",\n"+indenter+Indent), indenter) - } - return fmt.Sprintf("{%s}", strings.Join(result, ", ")) -} - -func isNilValue(a reflect.Value) bool { - switch a.Kind() { - case reflect.Invalid: - return true - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return a.IsNil() - } - - return false -} - -/* -Returns true when the string is entirely made of printable runes, false otherwise. -*/ -func isPrintableString(str string) bool { - for _, runeValue := range str { - if !strconv.IsPrint(runeValue) { - return false - } - } - return true -} diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go deleted file mode 100644 index 0d0f563a14..0000000000 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ /dev/null @@ -1,335 +0,0 @@ -/* -Gomega is the Ginkgo BDD-style testing framework's preferred matcher library. - -The godoc documentation describes Gomega's API. More comprehensive documentation (with examples!) is available at http://onsi.github.io/gomega/ - -Gomega on Github: http://github.com/onsi/gomega - -Learn more about Ginkgo online: http://onsi.github.io/ginkgo - -Ginkgo on Github: http://github.com/onsi/ginkgo - -Gomega is MIT-Licensed -*/ -package gomega - -import ( - "fmt" - "reflect" - "time" - - "github.com/onsi/gomega/internal/assertion" - "github.com/onsi/gomega/internal/asyncassertion" - "github.com/onsi/gomega/internal/testingtsupport" - "github.com/onsi/gomega/types" -) - -const GOMEGA_VERSION = "1.2.0" - -const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil. -If you're using Ginkgo then you probably forgot to put your assertion in an It(). -Alternatively, you may have forgotten to register a fail handler with RegisterFailHandler() or RegisterTestingT(). -` - -var globalFailHandler types.GomegaFailHandler - -var defaultEventuallyTimeout = time.Second -var defaultEventuallyPollingInterval = 10 * time.Millisecond -var defaultConsistentlyDuration = 100 * time.Millisecond -var defaultConsistentlyPollingInterval = 10 * time.Millisecond - -//RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails -//the fail handler passed into RegisterFailHandler is called. -func RegisterFailHandler(handler types.GomegaFailHandler) { - globalFailHandler = handler -} - -//RegisterTestingT connects Gomega to Golang's XUnit style -//Testing.T tests. You'll need to call this at the top of each XUnit style test: -// -// func TestFarmHasCow(t *testing.T) { -// RegisterTestingT(t) -// -// f := farm.New([]string{"Cow", "Horse"}) -// Expect(f.HasCow()).To(BeTrue(), "Farm should have cow") -// } -// -// Note that this *testing.T is registered *globally* by Gomega (this is why you don't have to -// pass `t` down to the matcher itself). This means that you cannot run the XUnit style tests -// in parallel as the global fail handler cannot point to more than one testing.T at a time. -// -// (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*). -func RegisterTestingT(t types.GomegaTestingT) { - RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailHandler(t)) -} - -//InterceptGomegaHandlers runs a given callback and returns an array of -//failure messages generated by any Gomega assertions within the callback. -// -//This is accomplished by temporarily replacing the *global* fail handler -//with a fail handler that simply annotates failures. The original fail handler -//is reset when InterceptGomegaFailures returns. -// -//This is most useful when testing custom matchers, but can also be used to check -//on a value using a Gomega assertion without causing a test failure. -func InterceptGomegaFailures(f func()) []string { - originalHandler := globalFailHandler - failures := []string{} - RegisterFailHandler(func(message string, callerSkip ...int) { - failures = append(failures, message) - }) - f() - RegisterFailHandler(originalHandler) - return failures -} - -//Ω wraps an actual value allowing assertions to be made on it: -// Ω("foo").Should(Equal("foo")) -// -//If Ω is passed more than one argument it will pass the *first* argument to the matcher. -//All subsequent arguments will be required to be nil/zero. -// -//This is convenient if you want to make an assertion on a method/function that returns -//a value and an error - a common patter in Go. -// -//For example, given a function with signature: -// func MyAmazingThing() (int, error) -// -//Then: -// Ω(MyAmazingThing()).Should(Equal(3)) -//Will succeed only if `MyAmazingThing()` returns `(3, nil)` -// -//Ω and Expect are identical -func Ω(actual interface{}, extra ...interface{}) GomegaAssertion { - return ExpectWithOffset(0, actual, extra...) -} - -//Expect wraps an actual value allowing assertions to be made on it: -// Expect("foo").To(Equal("foo")) -// -//If Expect is passed more than one argument it will pass the *first* argument to the matcher. -//All subsequent arguments will be required to be nil/zero. -// -//This is convenient if you want to make an assertion on a method/function that returns -//a value and an error - a common patter in Go. -// -//For example, given a function with signature: -// func MyAmazingThing() (int, error) -// -//Then: -// Expect(MyAmazingThing()).Should(Equal(3)) -//Will succeed only if `MyAmazingThing()` returns `(3, nil)` -// -//Expect and Ω are identical -func Expect(actual interface{}, extra ...interface{}) GomegaAssertion { - return ExpectWithOffset(0, actual, extra...) -} - -//ExpectWithOffset wraps an actual value allowing assertions to be made on it: -// ExpectWithOffset(1, "foo").To(Equal("foo")) -// -//Unlike `Expect` and `Ω`, `ExpectWithOffset` takes an additional integer argument -//this is used to modify the call-stack offset when computing line numbers. -// -//This is most useful in helper functions that make assertions. If you want Gomega's -//error message to refer to the calling line in the test (as opposed to the line in the helper function) -//set the first argument of `ExpectWithOffset` appropriately. -func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) GomegaAssertion { - if globalFailHandler == nil { - panic(nilFailHandlerPanic) - } - return assertion.New(actual, globalFailHandler, offset, extra...) -} - -//Eventually wraps an actual value allowing assertions to be made on it. -//The assertion is tried periodically until it passes or a timeout occurs. -// -//Both the timeout and polling interval are configurable as optional arguments: -//The first optional argument is the timeout -//The second optional argument is the polling interval -// -//Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the -//last case they are interpreted as seconds. -// -//If Eventually is passed an actual that is a function taking no arguments and returning at least one value, -//then Eventually will call the function periodically and try the matcher against the function's first return value. -// -//Example: -// -// Eventually(func() int { -// return thingImPolling.Count() -// }).Should(BeNumerically(">=", 17)) -// -//Note that this example could be rewritten: -// -// Eventually(thingImPolling.Count).Should(BeNumerically(">=", 17)) -// -//If the function returns more than one value, then Eventually will pass the first value to the matcher and -//assert that all other values are nil/zero. -//This allows you to pass Eventually a function that returns a value and an error - a common pattern in Go. -// -//For example, consider a method that returns a value and an error: -// func FetchFromDB() (string, error) -// -//Then -// Eventually(FetchFromDB).Should(Equal("hasselhoff")) -// -//Will pass only if the the returned error is nil and the returned string passes the matcher. -// -//Eventually's default timeout is 1 second, and its default polling interval is 10ms -func Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - return EventuallyWithOffset(0, actual, intervals...) -} - -//EventuallyWithOffset operates like Eventually but takes an additional -//initial argument to indicate an offset in the call stack. This is useful when building helper -//functions that contain matchers. To learn more, read about `ExpectWithOffset`. -func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailHandler == nil { - panic(nilFailHandlerPanic) - } - timeoutInterval := defaultEventuallyTimeout - pollingInterval := defaultEventuallyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailHandler, timeoutInterval, pollingInterval, offset) -} - -//Consistently wraps an actual value allowing assertions to be made on it. -//The assertion is tried periodically and is required to pass for a period of time. -// -//Both the total time and polling interval are configurable as optional arguments: -//The first optional argument is the duration that Consistently will run for -//The second optional argument is the polling interval -// -//Both intervals can either be specified as time.Duration, parsable duration strings or as floats/integers. In the -//last case they are interpreted as seconds. -// -//If Consistently is passed an actual that is a function taking no arguments and returning at least one value, -//then Consistently will call the function periodically and try the matcher against the function's first return value. -// -//If the function returns more than one value, then Consistently will pass the first value to the matcher and -//assert that all other values are nil/zero. -//This allows you to pass Consistently a function that returns a value and an error - a common pattern in Go. -// -//Consistently is useful in cases where you want to assert that something *does not happen* over a period of tiem. -//For example, you want to assert that a goroutine does *not* send data down a channel. In this case, you could: -// -// Consistently(channel).ShouldNot(Receive()) -// -//Consistently's default duration is 100ms, and its default polling interval is 10ms -func Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - return ConsistentlyWithOffset(0, actual, intervals...) -} - -//ConsistentlyWithOffset operates like Consistnetly but takes an additional -//initial argument to indicate an offset in the call stack. This is useful when building helper -//functions that contain matchers. To learn more, read about `ExpectWithOffset`. -func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailHandler == nil { - panic(nilFailHandlerPanic) - } - timeoutInterval := defaultConsistentlyDuration - pollingInterval := defaultConsistentlyPollingInterval - if len(intervals) > 0 { - timeoutInterval = toDuration(intervals[0]) - } - if len(intervals) > 1 { - pollingInterval = toDuration(intervals[1]) - } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailHandler, timeoutInterval, pollingInterval, offset) -} - -//Set the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses. -func SetDefaultEventuallyTimeout(t time.Duration) { - defaultEventuallyTimeout = t -} - -//Set the default polling interval for Eventually. -func SetDefaultEventuallyPollingInterval(t time.Duration) { - defaultEventuallyPollingInterval = t -} - -//Set the default duration for Consistently. Consistently will verify that your condition is satsified for this long. -func SetDefaultConsistentlyDuration(t time.Duration) { - defaultConsistentlyDuration = t -} - -//Set the default polling interval for Consistently. -func SetDefaultConsistentlyPollingInterval(t time.Duration) { - defaultConsistentlyPollingInterval = t -} - -//GomegaAsyncAssertion is returned by Eventually and Consistently and polls the actual value passed into Eventually against -//the matcher passed to the Should and ShouldNot methods. -// -//Both Should and ShouldNot take a variadic optionalDescription argument. This is passed on to -//fmt.Sprintf() and is used to annotate failure messages. This allows you to make your failure messages more -//descriptive -// -//Both Should and ShouldNot return a boolean that is true if the assertion passed and false if it failed. -// -//Example: -// -// Eventually(myChannel).Should(Receive(), "Something should have come down the pipe.") -// Consistently(myChannel).ShouldNot(Receive(), "Nothing should have come down the pipe.") -type GomegaAsyncAssertion interface { - Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool -} - -//GomegaAssertion is returned by Ω and Expect and compares the actual value to the matcher -//passed to the Should/ShouldNot and To/ToNot/NotTo methods. -// -//Typically Should/ShouldNot are used with Ω and To/ToNot/NotTo are used with Expect -//though this is not enforced. -// -//All methods take a variadic optionalDescription argument. This is passed on to fmt.Sprintf() -//and is used to annotate failure messages. -// -//All methods return a bool that is true if hte assertion passed and false if it failed. -// -//Example: -// -// Ω(farm.HasCow()).Should(BeTrue(), "Farm %v should have a cow", farm) -type GomegaAssertion interface { - Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - - To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool - NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool -} - -//OmegaMatcher is deprecated in favor of the better-named and better-organized types.GomegaMatcher but sticks around to support existing code that uses it -type OmegaMatcher types.GomegaMatcher - -func toDuration(input interface{}) time.Duration { - duration, ok := input.(time.Duration) - if ok { - return duration - } - - value := reflect.ValueOf(input) - kind := reflect.TypeOf(input).Kind() - - if reflect.Int <= kind && kind <= reflect.Int64 { - return time.Duration(value.Int()) * time.Second - } else if reflect.Uint <= kind && kind <= reflect.Uint64 { - return time.Duration(value.Uint()) * time.Second - } else if reflect.Float32 <= kind && kind <= reflect.Float64 { - return time.Duration(value.Float() * float64(time.Second)) - } else if reflect.String == kind { - duration, err := time.ParseDuration(value.String()) - if err != nil { - panic(fmt.Sprintf("%#v is not a valid parsable duration string.", input)) - } - return duration - } - - panic(fmt.Sprintf("%v is not a valid interval. Must be time.Duration, parsable duration string or a number.", input)) -} diff --git a/vendor/github.com/onsi/gomega/gstruct/elements.go b/vendor/github.com/onsi/gomega/gstruct/elements.go deleted file mode 100644 index a315fa139f..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/elements.go +++ /dev/null @@ -1,145 +0,0 @@ -package gstruct - -import ( - "errors" - "fmt" - "reflect" - "runtime/debug" - - "github.com/onsi/gomega/format" - errorsutil "github.com/onsi/gomega/gstruct/errors" - "github.com/onsi/gomega/types" -) - -//MatchAllElements succeeds if every element of a slice matches the element matcher it maps to -//through the id function, and every element matcher is matched. -// Expect([]string{"a", "b"}).To(MatchAllElements(idFn, matchers.Elements{ -// "a": BeEqual("a"), -// "b": BeEqual("b"), -// }) -func MatchAllElements(identifier Identifier, elements Elements) types.GomegaMatcher { - return &ElementsMatcher{ - Identifier: identifier, - Elements: elements, - } -} - -//MatchElements succeeds if each element of a slice matches the element matcher it maps to -//through the id function. It can ignore extra elements and/or missing elements. -// Expect([]string{"a", "c"}).To(MatchElements(idFn, IgnoreMissing|IgnoreExtra, matchers.Elements{ -// "a": BeEqual("a") -// "b": BeEqual("b"), -// }) -func MatchElements(identifier Identifier, options Options, elements Elements) types.GomegaMatcher { - return &ElementsMatcher{ - Identifier: identifier, - Elements: elements, - IgnoreExtras: options&IgnoreExtras != 0, - IgnoreMissing: options&IgnoreMissing != 0, - AllowDuplicates: options&AllowDuplicates != 0, - } -} - -// ElementsMatcher is a NestingMatcher that applies custom matchers to each element of a slice mapped -// by the Identifier function. -// TODO: Extend this to work with arrays & maps (map the key) as well. -type ElementsMatcher struct { - // Matchers for each element. - Elements Elements - // Function mapping an element to the string key identifying its matcher. - Identifier Identifier - - // Whether to ignore extra elements or consider it an error. - IgnoreExtras bool - // Whether to ignore missing elements or consider it an error. - IgnoreMissing bool - // Whether to key duplicates when matching IDs. - AllowDuplicates bool - - // State. - failures []error -} - -// Element ID to matcher. -type Elements map[string]types.GomegaMatcher - -// Function for identifying (mapping) elements. -type Identifier func(element interface{}) string - -func (m *ElementsMatcher) Match(actual interface{}) (success bool, err error) { - if reflect.TypeOf(actual).Kind() != reflect.Slice { - return false, fmt.Errorf("%v is type %T, expected slice", actual, actual) - } - - m.failures = m.matchElements(actual) - if len(m.failures) > 0 { - return false, nil - } - return true, nil -} - -func (m *ElementsMatcher) matchElements(actual interface{}) (errs []error) { - // Provide more useful error messages in the case of a panic. - defer func() { - if err := recover(); err != nil { - errs = append(errs, fmt.Errorf("panic checking %+v: %v\n%s", actual, err, debug.Stack())) - } - }() - - val := reflect.ValueOf(actual) - elements := map[string]bool{} - for i := 0; i < val.Len(); i++ { - element := val.Index(i).Interface() - id := m.Identifier(element) - if elements[id] { - if !m.AllowDuplicates { - errs = append(errs, fmt.Errorf("found duplicate element ID %s", id)) - continue - } - } - elements[id] = true - - matcher, expected := m.Elements[id] - if !expected { - if !m.IgnoreExtras { - errs = append(errs, fmt.Errorf("unexpected element %s", id)) - } - continue - } - - match, err := matcher.Match(element) - if match { - continue - } - - if err == nil { - if nesting, ok := matcher.(errorsutil.NestingMatcher); ok { - err = errorsutil.AggregateError(nesting.Failures()) - } else { - err = errors.New(matcher.FailureMessage(element)) - } - } - errs = append(errs, errorsutil.Nest(fmt.Sprintf("[%s]", id), err)) - } - - for id := range m.Elements { - if !elements[id] && !m.IgnoreMissing { - errs = append(errs, fmt.Errorf("missing expected element %s", id)) - } - } - - return errs -} - -func (m *ElementsMatcher) FailureMessage(actual interface{}) (message string) { - failure := errorsutil.AggregateError(m.failures) - return format.Message(actual, fmt.Sprintf("to match elements: %v", failure)) -} - -func (m *ElementsMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match elements") -} - -func (m *ElementsMatcher) Failures() []error { - return m.failures -} diff --git a/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go b/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go deleted file mode 100644 index 188492b212..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/errors/nested_types.go +++ /dev/null @@ -1,72 +0,0 @@ -package errors - -import ( - "fmt" - "strings" - - "github.com/onsi/gomega/types" -) - -// A stateful matcher that nests other matchers within it and preserves the error types of the -// nested matcher failures. -type NestingMatcher interface { - types.GomegaMatcher - - // Returns the failures of nested matchers. - Failures() []error -} - -// An error type for labeling errors on deeply nested matchers. -type NestedError struct { - Path string - Err error -} - -func (e *NestedError) Error() string { - // Indent Errors. - indented := strings.Replace(e.Err.Error(), "\n", "\n\t", -1) - return fmt.Sprintf("%s:\n\t%v", e.Path, indented) -} - -// Create a NestedError with the given path. -// If err is a NestedError, prepend the path to it. -// If err is an AggregateError, recursively Nest each error. -func Nest(path string, err error) error { - if ag, ok := err.(AggregateError); ok { - var errs AggregateError - for _, e := range ag { - errs = append(errs, Nest(path, e)) - } - return errs - } - if ne, ok := err.(*NestedError); ok { - return &NestedError{ - Path: path + ne.Path, - Err: ne.Err, - } - } - return &NestedError{ - Path: path, - Err: err, - } -} - -// An error type for treating multiple errors as a single error. -type AggregateError []error - -// Error is part of the error interface. -func (err AggregateError) Error() string { - if len(err) == 0 { - // This should never happen, really. - return "" - } - if len(err) == 1 { - return err[0].Error() - } - result := fmt.Sprintf("[%s", err[0].Error()) - for i := 1; i < len(err); i++ { - result += fmt.Sprintf(", %s", err[i].Error()) - } - result += "]" - return result -} diff --git a/vendor/github.com/onsi/gomega/gstruct/fields.go b/vendor/github.com/onsi/gomega/gstruct/fields.go deleted file mode 100644 index 0020b873d3..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/fields.go +++ /dev/null @@ -1,141 +0,0 @@ -package gstruct - -import ( - "errors" - "fmt" - "reflect" - "runtime/debug" - "strings" - - "github.com/onsi/gomega/format" - errorsutil "github.com/onsi/gomega/gstruct/errors" - "github.com/onsi/gomega/types" -) - -//MatchAllFields succeeds if every field of a struct matches the field matcher associated with -//it, and every element matcher is matched. -// Expect([]string{"a", "b"}).To(MatchAllFields(gstruct.Fields{ -// "a": BeEqual("a"), -// "b": BeEqual("b"), -// }) -func MatchAllFields(fields Fields) types.GomegaMatcher { - return &FieldsMatcher{ - Fields: fields, - } -} - -//MatchFields succeeds if each element of a struct matches the field matcher associated with -//it. It can ignore extra fields and/or missing fields. -// Expect([]string{"a", "c"}).To(MatchFields(IgnoreMissing|IgnoreExtra, gstruct.Fields{ -// "a": BeEqual("a") -// "b": BeEqual("b"), -// }) -func MatchFields(options Options, fields Fields) types.GomegaMatcher { - return &FieldsMatcher{ - Fields: fields, - IgnoreExtras: options&IgnoreExtras != 0, - IgnoreMissing: options&IgnoreMissing != 0, - } -} - -type FieldsMatcher struct { - // Matchers for each field. - Fields Fields - - // Whether to ignore extra elements or consider it an error. - IgnoreExtras bool - // Whether to ignore missing elements or consider it an error. - IgnoreMissing bool - - // State. - failures []error -} - -// Field name to matcher. -type Fields map[string]types.GomegaMatcher - -func (m *FieldsMatcher) Match(actual interface{}) (success bool, err error) { - if reflect.TypeOf(actual).Kind() != reflect.Struct { - return false, fmt.Errorf("%v is type %T, expected struct", actual, actual) - } - - m.failures = m.matchFields(actual) - if len(m.failures) > 0 { - return false, nil - } - return true, nil -} - -func (m *FieldsMatcher) matchFields(actual interface{}) (errs []error) { - val := reflect.ValueOf(actual) - typ := val.Type() - fields := map[string]bool{} - for i := 0; i < val.NumField(); i++ { - fieldName := typ.Field(i).Name - fields[fieldName] = true - - err := func() (err error) { - // This test relies heavily on reflect, which tends to panic. - // Recover here to provide more useful error messages in that case. - defer func() { - if r := recover(); r != nil { - err = fmt.Errorf("panic checking %+v: %v\n%s", actual, r, debug.Stack()) - } - }() - - matcher, expected := m.Fields[fieldName] - if !expected { - if !m.IgnoreExtras { - return fmt.Errorf("unexpected field %s: %+v", fieldName, actual) - } - return nil - } - - var field interface{} - if val.Field(i).IsValid() { - field = val.Field(i).Interface() - } else { - field = reflect.Zero(typ.Field(i).Type) - } - - match, err := matcher.Match(field) - if err != nil { - return err - } else if !match { - if nesting, ok := matcher.(errorsutil.NestingMatcher); ok { - return errorsutil.AggregateError(nesting.Failures()) - } - return errors.New(matcher.FailureMessage(field)) - } - return nil - }() - if err != nil { - errs = append(errs, errorsutil.Nest("."+fieldName, err)) - } - } - - for field := range m.Fields { - if !fields[field] && !m.IgnoreMissing { - errs = append(errs, fmt.Errorf("missing expected field %s", field)) - } - } - - return errs -} - -func (m *FieldsMatcher) FailureMessage(actual interface{}) (message string) { - failures := make([]string, len(m.failures)) - for i := range m.failures { - failures[i] = m.failures[i].Error() - } - return format.Message(reflect.TypeOf(actual).Name(), - fmt.Sprintf("to match fields: {\n%v\n}\n", strings.Join(failures, "\n"))) -} - -func (m *FieldsMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match fields") -} - -func (m *FieldsMatcher) Failures() []error { - return m.failures -} diff --git a/vendor/github.com/onsi/gomega/gstruct/ignore.go b/vendor/github.com/onsi/gomega/gstruct/ignore.go deleted file mode 100644 index 0365f32ad1..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/ignore.go +++ /dev/null @@ -1,37 +0,0 @@ -package gstruct - -import ( - "github.com/onsi/gomega/types" -) - -//Ignore ignores the actual value and always succeeds. -// Expect(nil).To(Ignore()) -// Expect(true).To(Ignore()) -func Ignore() types.GomegaMatcher { - return &IgnoreMatcher{true} -} - -//Reject ignores the actual value and always fails. It can be used in conjunction with IgnoreMissing -//to catch problematic elements, or to verify tests are running. -// Expect(nil).NotTo(Reject()) -// Expect(true).NotTo(Reject()) -func Reject() types.GomegaMatcher { - return &IgnoreMatcher{false} -} - -// A matcher that either always succeeds or always fails. -type IgnoreMatcher struct { - Succeed bool -} - -func (m *IgnoreMatcher) Match(actual interface{}) (bool, error) { - return m.Succeed, nil -} - -func (m *IgnoreMatcher) FailureMessage(_ interface{}) (message string) { - return "Unconditional failure" -} - -func (m *IgnoreMatcher) NegatedFailureMessage(_ interface{}) (message string) { - return "Unconditional success" -} diff --git a/vendor/github.com/onsi/gomega/gstruct/pointer.go b/vendor/github.com/onsi/gomega/gstruct/pointer.go deleted file mode 100644 index 0a2f35de31..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/pointer.go +++ /dev/null @@ -1,56 +0,0 @@ -package gstruct - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/types" -) - -//PointTo applies the given matcher to the value pointed to by actual. It fails if the pointer is -//nil. -// actual := 5 -// Expect(&actual).To(PointTo(Equal(5))) -func PointTo(matcher types.GomegaMatcher) types.GomegaMatcher { - return &PointerMatcher{ - Matcher: matcher, - } -} - -type PointerMatcher struct { - Matcher types.GomegaMatcher - - // Failure message. - failure string -} - -func (m *PointerMatcher) Match(actual interface{}) (bool, error) { - val := reflect.ValueOf(actual) - - // return error if actual type is not a pointer - if val.Kind() != reflect.Ptr { - return false, fmt.Errorf("PointerMatcher expects a pointer but we have '%s'", val.Kind()) - } - - if !val.IsValid() || val.IsNil() { - m.failure = format.Message(actual, "not to be ") - return false, nil - } - - // Forward the value. - elem := val.Elem().Interface() - match, err := m.Matcher.Match(elem) - if !match { - m.failure = m.Matcher.FailureMessage(elem) - } - return match, err -} - -func (m *PointerMatcher) FailureMessage(_ interface{}) (message string) { - return m.failure -} - -func (m *PointerMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return m.Matcher.NegatedFailureMessage(actual) -} diff --git a/vendor/github.com/onsi/gomega/gstruct/types.go b/vendor/github.com/onsi/gomega/gstruct/types.go deleted file mode 100644 index 48cbbe8f66..0000000000 --- a/vendor/github.com/onsi/gomega/gstruct/types.go +++ /dev/null @@ -1,15 +0,0 @@ -package gstruct - -//Options is the type for options passed to some matchers. -type Options int - -const ( - //IgnoreExtras tells the matcher to ignore extra elements or fields, rather than triggering a failure. - IgnoreExtras Options = 1 << iota - //IgnoreMissing tells the matcher to ignore missing elements or fields, rather than triggering a failure. - IgnoreMissing - //AllowDuplicates tells the matcher to permit multiple members of the slice to produce the same ID when - //considered by the indentifier function. All members that map to a given key must still match successfully - //with the matcher that is provided for that key. - AllowDuplicates -) diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion.go deleted file mode 100644 index b73673f21e..0000000000 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go +++ /dev/null @@ -1,98 +0,0 @@ -package assertion - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/types" -) - -type Assertion struct { - actualInput interface{} - fail types.GomegaFailHandler - offset int - extra []interface{} -} - -func New(actualInput interface{}, fail types.GomegaFailHandler, offset int, extra ...interface{}) *Assertion { - return &Assertion{ - actualInput: actualInput, - fail: fail, - offset: offset, - extra: extra, - } -} - -func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) string { - switch len(optionalDescription) { - case 0: - return "" - default: - return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" - } -} - -func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { - matches, err := matcher.Match(assertion.actualInput) - description := assertion.buildDescription(optionalDescription...) - if err != nil { - assertion.fail(description+err.Error(), 2+assertion.offset) - return false - } - if matches != desiredMatch { - var message string - if desiredMatch { - message = matcher.FailureMessage(assertion.actualInput) - } else { - message = matcher.NegatedFailureMessage(assertion.actualInput) - } - assertion.fail(description+message, 2+assertion.offset) - return false - } - - return true -} - -func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool { - success, message := vetExtras(assertion.extra) - if success { - return true - } - - description := assertion.buildDescription(optionalDescription...) - assertion.fail(description+message, 2+assertion.offset) - return false -} - -func vetExtras(extras []interface{}) (bool, string) { - for i, extra := range extras { - if extra != nil { - zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface() - if !reflect.DeepEqual(zeroValue, extra) { - message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra) - return false, message - } - } - } - return true, "" -} diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go deleted file mode 100644 index bce0853006..0000000000 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go +++ /dev/null @@ -1,189 +0,0 @@ -package asyncassertion - -import ( - "errors" - "fmt" - "reflect" - "time" - - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type AsyncAssertionType uint - -const ( - AsyncAssertionTypeEventually AsyncAssertionType = iota - AsyncAssertionTypeConsistently -) - -type AsyncAssertion struct { - asyncType AsyncAssertionType - actualInput interface{} - timeoutInterval time.Duration - pollingInterval time.Duration - fail types.GomegaFailHandler - offset int -} - -func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.GomegaFailHandler, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion { - actualType := reflect.TypeOf(actualInput) - if actualType.Kind() == reflect.Func { - if actualType.NumIn() != 0 || actualType.NumOut() == 0 { - panic("Expected a function with no arguments and one or more return values.") - } - } - - return &AsyncAssertion{ - asyncType: asyncType, - actualInput: actualInput, - fail: fail, - timeoutInterval: timeoutInterval, - pollingInterval: pollingInterval, - offset: offset, - } -} - -func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.match(matcher, true, optionalDescription...) -} - -func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { - return assertion.match(matcher, false, optionalDescription...) -} - -func (assertion *AsyncAssertion) buildDescription(optionalDescription ...interface{}) string { - switch len(optionalDescription) { - case 0: - return "" - default: - return fmt.Sprintf(optionalDescription[0].(string), optionalDescription[1:]...) + "\n" - } -} - -func (assertion *AsyncAssertion) actualInputIsAFunction() bool { - actualType := reflect.TypeOf(assertion.actualInput) - return actualType.Kind() == reflect.Func && actualType.NumIn() == 0 && actualType.NumOut() > 0 -} - -func (assertion *AsyncAssertion) pollActual() (interface{}, error) { - if assertion.actualInputIsAFunction() { - values := reflect.ValueOf(assertion.actualInput).Call([]reflect.Value{}) - - extras := []interface{}{} - for _, value := range values[1:] { - extras = append(extras, value.Interface()) - } - - success, message := vetExtras(extras) - - if !success { - return nil, errors.New(message) - } - - return values[0].Interface(), nil - } - - return assertion.actualInput, nil -} - -func (assertion *AsyncAssertion) matcherMayChange(matcher types.GomegaMatcher, value interface{}) bool { - if assertion.actualInputIsAFunction() { - return true - } - - return oraclematcher.MatchMayChangeInTheFuture(matcher, value) -} - -func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { - timer := time.Now() - timeout := time.After(assertion.timeoutInterval) - - description := assertion.buildDescription(optionalDescription...) - - var matches bool - var err error - mayChange := true - value, err := assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - - fail := func(preamble string) { - errMsg := "" - message := "" - if err != nil { - errMsg = "Error: " + err.Error() - } else { - if desiredMatch { - message = matcher.FailureMessage(value) - } else { - message = matcher.NegatedFailureMessage(value) - } - } - assertion.fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset) - } - - if assertion.asyncType == AsyncAssertionTypeEventually { - for { - if err == nil && matches == desiredMatch { - return true - } - - if !mayChange { - fail("No future change is possible. Bailing out early") - return false - } - - select { - case <-time.After(assertion.pollingInterval): - value, err = assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - case <-timeout: - fail("Timed out") - return false - } - } - } else if assertion.asyncType == AsyncAssertionTypeConsistently { - for { - if !(err == nil && matches == desiredMatch) { - fail("Failed") - return false - } - - if !mayChange { - return true - } - - select { - case <-time.After(assertion.pollingInterval): - value, err = assertion.pollActual() - if err == nil { - mayChange = assertion.matcherMayChange(matcher, value) - matches, err = matcher.Match(value) - } - case <-timeout: - return true - } - } - } - - return false -} - -func vetExtras(extras []interface{}) (bool, string) { - for i, extra := range extras { - if extra != nil { - zeroValue := reflect.Zero(reflect.TypeOf(extra)).Interface() - if !reflect.DeepEqual(zeroValue, extra) { - message := fmt.Sprintf("Unexpected non-nil/non-zero extra argument at index %d:\n\t<%T>: %#v", i+1, extra, extra) - return false, message - } - } - } - return true, "" -} diff --git a/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go b/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go deleted file mode 100644 index 66cad88a1f..0000000000 --- a/vendor/github.com/onsi/gomega/internal/oraclematcher/oracle_matcher.go +++ /dev/null @@ -1,25 +0,0 @@ -package oraclematcher - -import "github.com/onsi/gomega/types" - -/* -GomegaMatchers that also match the OracleMatcher interface can convey information about -whether or not their result will change upon future attempts. - -This allows `Eventually` and `Consistently` to short circuit if success becomes impossible. - -For example, a process' exit code can never change. So, gexec's Exit matcher returns `true` -for `MatchMayChangeInTheFuture` until the process exits, at which point it returns `false` forevermore. -*/ -type OracleMatcher interface { - MatchMayChangeInTheFuture(actual interface{}) bool -} - -func MatchMayChangeInTheFuture(matcher types.GomegaMatcher, value interface{}) bool { - oracleMatcher, ok := matcher.(OracleMatcher) - if !ok { - return true - } - - return oracleMatcher.MatchMayChangeInTheFuture(value) -} diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go deleted file mode 100644 index ac8912525a..0000000000 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go +++ /dev/null @@ -1,40 +0,0 @@ -package testingtsupport - -import ( - "regexp" - "runtime/debug" - "strings" - - "github.com/onsi/gomega/types" -) - -type gomegaTestingT interface { - Fatalf(format string, args ...interface{}) -} - -func BuildTestingTGomegaFailHandler(t gomegaTestingT) types.GomegaFailHandler { - return func(message string, callerSkip ...int) { - skip := 1 - if len(callerSkip) > 0 { - skip = callerSkip[0] - } - stackTrace := pruneStack(string(debug.Stack()), skip) - t.Fatalf("\n%s\n%s", stackTrace, message) - } -} - -func pruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n") - if len(stack) > 2*(skip+1) { - stack = stack[2*(skip+1):] - } - prunedStack := []string{} - re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) - for i := 0; i < len(stack)/2; i++ { - if !re.Match([]byte(stack[i*2])) { - prunedStack = append(prunedStack, stack[i*2]) - prunedStack = append(prunedStack, stack[i*2+1]) - } - } - return strings.Join(prunedStack, "\n") -} diff --git a/vendor/github.com/onsi/gomega/matchers.go b/vendor/github.com/onsi/gomega/matchers.go deleted file mode 100644 index e6e85d070d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers.go +++ /dev/null @@ -1,427 +0,0 @@ -package gomega - -import ( - "time" - - "github.com/onsi/gomega/matchers" - "github.com/onsi/gomega/types" -) - -//Equal uses reflect.DeepEqual to compare actual with expected. Equal is strict about -//types when performing comparisons. -//It is an error for both actual and expected to be nil. Use BeNil() instead. -func Equal(expected interface{}) types.GomegaMatcher { - return &matchers.EqualMatcher{ - Expected: expected, - } -} - -//BeEquivalentTo is more lax than Equal, allowing equality between different types. -//This is done by converting actual to have the type of expected before -//attempting equality with reflect.DeepEqual. -//It is an error for actual and expected to be nil. Use BeNil() instead. -func BeEquivalentTo(expected interface{}) types.GomegaMatcher { - return &matchers.BeEquivalentToMatcher{ - Expected: expected, - } -} - -//BeIdenticalTo uses the == operator to compare actual with expected. -//BeIdenticalTo is strict about types when performing comparisons. -//It is an error for both actual and expected to be nil. Use BeNil() instead. -func BeIdenticalTo(expected interface{}) types.GomegaMatcher { - return &matchers.BeIdenticalToMatcher{ - Expected: expected, - } -} - -//BeNil succeeds if actual is nil -func BeNil() types.GomegaMatcher { - return &matchers.BeNilMatcher{} -} - -//BeTrue succeeds if actual is true -func BeTrue() types.GomegaMatcher { - return &matchers.BeTrueMatcher{} -} - -//BeFalse succeeds if actual is false -func BeFalse() types.GomegaMatcher { - return &matchers.BeFalseMatcher{} -} - -//HaveOccurred succeeds if actual is a non-nil error -//The typical Go error checking pattern looks like: -// err := SomethingThatMightFail() -// Ω(err).ShouldNot(HaveOccurred()) -func HaveOccurred() types.GomegaMatcher { - return &matchers.HaveOccurredMatcher{} -} - -//Succeed passes if actual is a nil error -//Succeed is intended to be used with functions that return a single error value. Instead of -// err := SomethingThatMightFail() -// Ω(err).ShouldNot(HaveOccurred()) -// -//You can write: -// Ω(SomethingThatMightFail()).Should(Succeed()) -// -//It is a mistake to use Succeed with a function that has multiple return values. Gomega's Ω and Expect -//functions automatically trigger failure if any return values after the first return value are non-zero/non-nil. -//This means that Ω(MultiReturnFunc()).ShouldNot(Succeed()) can never pass. -func Succeed() types.GomegaMatcher { - return &matchers.SucceedMatcher{} -} - -//MatchError succeeds if actual is a non-nil error that matches the passed in string/error. -// -//These are valid use-cases: -// Ω(err).Should(MatchError("an error")) //asserts that err.Error() == "an error" -// Ω(err).Should(MatchError(SomeError)) //asserts that err == SomeError (via reflect.DeepEqual) -// -//It is an error for err to be nil or an object that does not implement the Error interface -func MatchError(expected interface{}) types.GomegaMatcher { - return &matchers.MatchErrorMatcher{ - Expected: expected, - } -} - -//BeClosed succeeds if actual is a closed channel. -//It is an error to pass a non-channel to BeClosed, it is also an error to pass nil -// -//In order to check whether or not the channel is closed, Gomega must try to read from the channel -//(even in the `ShouldNot(BeClosed())` case). You should keep this in mind if you wish to make subsequent assertions about -//values coming down the channel. -// -//Also, if you are testing that a *buffered* channel is closed you must first read all values out of the channel before -//asserting that it is closed (it is not possible to detect that a buffered-channel has been closed until all its buffered values are read). -// -//Finally, as a corollary: it is an error to check whether or not a send-only channel is closed. -func BeClosed() types.GomegaMatcher { - return &matchers.BeClosedMatcher{} -} - -//Receive succeeds if there is a value to be received on actual. -//Actual must be a channel (and cannot be a send-only channel) -- anything else is an error. -// -//Receive returns immediately and never blocks: -// -//- If there is nothing on the channel `c` then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. -// -//- If the channel `c` is closed then Ω(c).Should(Receive()) will fail and Ω(c).ShouldNot(Receive()) will pass. -// -//- If there is something on the channel `c` ready to be read, then Ω(c).Should(Receive()) will pass and Ω(c).ShouldNot(Receive()) will fail. -// -//If you have a go-routine running in the background that will write to channel `c` you can: -// Eventually(c).Should(Receive()) -// -//This will timeout if nothing gets sent to `c` (you can modify the timeout interval as you normally do with `Eventually`) -// -//A similar use-case is to assert that no go-routine writes to a channel (for a period of time). You can do this with `Consistently`: -// Consistently(c).ShouldNot(Receive()) -// -//You can pass `Receive` a matcher. If you do so, it will match the received object against the matcher. For example: -// Ω(c).Should(Receive(Equal("foo"))) -// -//When given a matcher, `Receive` will always fail if there is nothing to be received on the channel. -// -//Passing Receive a matcher is especially useful when paired with Eventually: -// -// Eventually(c).Should(Receive(ContainSubstring("bar"))) -// -//will repeatedly attempt to pull values out of `c` until a value matching "bar" is received. -// -//Finally, if you want to have a reference to the value *sent* to the channel you can pass the `Receive` matcher a pointer to a variable of the appropriate type: -// var myThing thing -// Eventually(thingChan).Should(Receive(&myThing)) -// Ω(myThing.Sprocket).Should(Equal("foo")) -// Ω(myThing.IsValid()).Should(BeTrue()) -func Receive(args ...interface{}) types.GomegaMatcher { - var arg interface{} - if len(args) > 0 { - arg = args[0] - } - - return &matchers.ReceiveMatcher{ - Arg: arg, - } -} - -//BeSent succeeds if a value can be sent to actual. -//Actual must be a channel (and cannot be a receive-only channel) that can sent the type of the value passed into BeSent -- anything else is an error. -//In addition, actual must not be closed. -// -//BeSent never blocks: -// -//- If the channel `c` is not ready to receive then Ω(c).Should(BeSent("foo")) will fail immediately -//- If the channel `c` is eventually ready to receive then Eventually(c).Should(BeSent("foo")) will succeed.. presuming the channel becomes ready to receive before Eventually's timeout -//- If the channel `c` is closed then Ω(c).Should(BeSent("foo")) and Ω(c).ShouldNot(BeSent("foo")) will both fail immediately -// -//Of course, the value is actually sent to the channel. The point of `BeSent` is less to make an assertion about the availability of the channel (which is typically an implementation detail that your test should not be concerned with). -//Rather, the point of `BeSent` is to make it possible to easily and expressively write tests that can timeout on blocked channel sends. -func BeSent(arg interface{}) types.GomegaMatcher { - return &matchers.BeSentMatcher{ - Arg: arg, - } -} - -//MatchRegexp succeeds if actual is a string or stringer that matches the -//passed-in regexp. Optional arguments can be provided to construct a regexp -//via fmt.Sprintf(). -func MatchRegexp(regexp string, args ...interface{}) types.GomegaMatcher { - return &matchers.MatchRegexpMatcher{ - Regexp: regexp, - Args: args, - } -} - -//ContainSubstring succeeds if actual is a string or stringer that contains the -//passed-in substring. Optional arguments can be provided to construct the substring -//via fmt.Sprintf(). -func ContainSubstring(substr string, args ...interface{}) types.GomegaMatcher { - return &matchers.ContainSubstringMatcher{ - Substr: substr, - Args: args, - } -} - -//HavePrefix succeeds if actual is a string or stringer that contains the -//passed-in string as a prefix. Optional arguments can be provided to construct -//via fmt.Sprintf(). -func HavePrefix(prefix string, args ...interface{}) types.GomegaMatcher { - return &matchers.HavePrefixMatcher{ - Prefix: prefix, - Args: args, - } -} - -//HaveSuffix succeeds if actual is a string or stringer that contains the -//passed-in string as a suffix. Optional arguments can be provided to construct -//via fmt.Sprintf(). -func HaveSuffix(suffix string, args ...interface{}) types.GomegaMatcher { - return &matchers.HaveSuffixMatcher{ - Suffix: suffix, - Args: args, - } -} - -//MatchJSON succeeds if actual is a string or stringer of JSON that matches -//the expected JSON. The JSONs are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchJSON(json interface{}) types.GomegaMatcher { - return &matchers.MatchJSONMatcher{ - JSONToMatch: json, - } -} - -//MatchXML succeeds if actual is a string or stringer of XML that matches -//the expected XML. The XMLs are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like whitespaces shouldn't matter. -func MatchXML(xml interface{}) types.GomegaMatcher { - return &matchers.MatchXMLMatcher{ - XMLToMatch: xml, - } -} - -//MatchYAML succeeds if actual is a string or stringer of YAML that matches -//the expected YAML. The YAML's are decoded and the resulting objects are compared via -//reflect.DeepEqual so things like key-ordering and whitespace shouldn't matter. -func MatchYAML(yaml interface{}) types.GomegaMatcher { - return &matchers.MatchYAMLMatcher{ - YAMLToMatch: yaml, - } -} - -//BeEmpty succeeds if actual is empty. Actual must be of type string, array, map, chan, or slice. -func BeEmpty() types.GomegaMatcher { - return &matchers.BeEmptyMatcher{} -} - -//HaveLen succeeds if actual has the passed-in length. Actual must be of type string, array, map, chan, or slice. -func HaveLen(count int) types.GomegaMatcher { - return &matchers.HaveLenMatcher{ - Count: count, - } -} - -//HaveCap succeeds if actual has the passed-in capacity. Actual must be of type array, chan, or slice. -func HaveCap(count int) types.GomegaMatcher { - return &matchers.HaveCapMatcher{ - Count: count, - } -} - -//BeZero succeeds if actual is the zero value for its type or if actual is nil. -func BeZero() types.GomegaMatcher { - return &matchers.BeZeroMatcher{} -} - -//ContainElement succeeds if actual contains the passed in element. -//By default ContainElement() uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Ω([]string{"Foo", "FooBar"}).Should(ContainElement(ContainSubstring("Bar"))) -// -//Actual must be an array, slice or map. -//For maps, ContainElement searches through the map's values. -func ContainElement(element interface{}) types.GomegaMatcher { - return &matchers.ContainElementMatcher{ - Element: element, - } -} - -//ConsistOf succeeds if actual contains preciely the elements passed into the matcher. The ordering of the elements does not matter. -//By default ConsistOf() uses Equal() to match the elements, however custom matchers can be passed in instead. Here are some examples: -// -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf("FooBar", "Foo")) -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Bar"), "Foo")) -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf(ContainSubstring("Foo"), ContainSubstring("Foo"))) -// -//Actual must be an array, slice or map. For maps, ConsistOf matches against the map's values. -// -//You typically pass variadic arguments to ConsistOf (as in the examples above). However, if you need to pass in a slice you can provided that it -//is the only element passed in to ConsistOf: -// -// Ω([]string{"Foo", "FooBar"}).Should(ConsistOf([]string{"FooBar", "Foo"})) -// -//Note that Go's type system does not allow you to write this as ConsistOf([]string{"FooBar", "Foo"}...) as []string and []interface{} are different types - hence the need for this special rule. -func ConsistOf(elements ...interface{}) types.GomegaMatcher { - return &matchers.ConsistOfMatcher{ - Elements: elements, - } -} - -//HaveKey succeeds if actual is a map with the passed in key. -//By default HaveKey uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKey(MatchRegexp(`.+Foo$`))) -func HaveKey(key interface{}) types.GomegaMatcher { - return &matchers.HaveKeyMatcher{ - Key: key, - } -} - -//HaveKeyWithValue succeeds if actual is a map with the passed in key and value. -//By default HaveKeyWithValue uses Equal() to perform the match, however a -//matcher can be passed in instead: -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue("Foo", "Bar")) -// Ω(map[string]string{"Foo": "Bar", "BazFoo": "Duck"}).Should(HaveKeyWithValue(MatchRegexp(`.+Foo$`), "Bar")) -func HaveKeyWithValue(key interface{}, value interface{}) types.GomegaMatcher { - return &matchers.HaveKeyWithValueMatcher{ - Key: key, - Value: value, - } -} - -//BeNumerically performs numerical assertions in a type-agnostic way. -//Actual and expected should be numbers, though the specific type of -//number is irrelevant (floa32, float64, uint8, etc...). -// -//There are six, self-explanatory, supported comparators: -// Ω(1.0).Should(BeNumerically("==", 1)) -// Ω(1.0).Should(BeNumerically("~", 0.999, 0.01)) -// Ω(1.0).Should(BeNumerically(">", 0.9)) -// Ω(1.0).Should(BeNumerically(">=", 1.0)) -// Ω(1.0).Should(BeNumerically("<", 3)) -// Ω(1.0).Should(BeNumerically("<=", 1.0)) -func BeNumerically(comparator string, compareTo ...interface{}) types.GomegaMatcher { - return &matchers.BeNumericallyMatcher{ - Comparator: comparator, - CompareTo: compareTo, - } -} - -//BeTemporally compares time.Time's like BeNumerically -//Actual and expected must be time.Time. The comparators are the same as for BeNumerically -// Ω(time.Now()).Should(BeTemporally(">", time.Time{})) -// Ω(time.Now()).Should(BeTemporally("~", time.Now(), time.Second)) -func BeTemporally(comparator string, compareTo time.Time, threshold ...time.Duration) types.GomegaMatcher { - return &matchers.BeTemporallyMatcher{ - Comparator: comparator, - CompareTo: compareTo, - Threshold: threshold, - } -} - -//BeAssignableToTypeOf succeeds if actual is assignable to the type of expected. -//It will return an error when one of the values is nil. -// Ω(0).Should(BeAssignableToTypeOf(0)) // Same values -// Ω(5).Should(BeAssignableToTypeOf(-1)) // different values same type -// Ω("foo").Should(BeAssignableToTypeOf("bar")) // different values same type -// Ω(struct{ Foo string }{}).Should(BeAssignableToTypeOf(struct{ Foo string }{})) -func BeAssignableToTypeOf(expected interface{}) types.GomegaMatcher { - return &matchers.AssignableToTypeOfMatcher{ - Expected: expected, - } -} - -//Panic succeeds if actual is a function that, when invoked, panics. -//Actual must be a function that takes no arguments and returns no results. -func Panic() types.GomegaMatcher { - return &matchers.PanicMatcher{} -} - -//BeAnExistingFile succeeds if a file exists. -//Actual must be a string representing the abs path to the file being checked. -func BeAnExistingFile() types.GomegaMatcher { - return &matchers.BeAnExistingFileMatcher{} -} - -//BeARegularFile succeeds iff a file exists and is a regular file. -//Actual must be a string representing the abs path to the file being checked. -func BeARegularFile() types.GomegaMatcher { - return &matchers.BeARegularFileMatcher{} -} - -//BeADirectory succeeds iff a file exists and is a directory. -//Actual must be a string representing the abs path to the file being checked. -func BeADirectory() types.GomegaMatcher { - return &matchers.BeADirectoryMatcher{} -} - -//And succeeds only if all of the given matchers succeed. -//The matchers are tried in order, and will fail-fast if one doesn't succeed. -// Expect("hi").To(And(HaveLen(2), Equal("hi")) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func And(ms ...types.GomegaMatcher) types.GomegaMatcher { - return &matchers.AndMatcher{Matchers: ms} -} - -//SatisfyAll is an alias for And(). -// Ω("hi").Should(SatisfyAll(HaveLen(2), Equal("hi"))) -func SatisfyAll(matchers ...types.GomegaMatcher) types.GomegaMatcher { - return And(matchers...) -} - -//Or succeeds if any of the given matchers succeed. -//The matchers are tried in order and will return immediately upon the first successful match. -// Expect("hi").To(Or(HaveLen(3), HaveLen(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func Or(ms ...types.GomegaMatcher) types.GomegaMatcher { - return &matchers.OrMatcher{Matchers: ms} -} - -//SatisfyAny is an alias for Or(). -// Expect("hi").SatisfyAny(Or(HaveLen(3), HaveLen(2)) -func SatisfyAny(matchers ...types.GomegaMatcher) types.GomegaMatcher { - return Or(matchers...) -} - -//Not negates the given matcher; it succeeds if the given matcher fails. -// Expect(1).To(Not(Equal(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func Not(matcher types.GomegaMatcher) types.GomegaMatcher { - return &matchers.NotMatcher{Matcher: matcher} -} - -//WithTransform applies the `transform` to the actual value and matches it against `matcher`. -//The given transform must be a function of one parameter that returns one value. -// var plus1 = func(i int) int { return i + 1 } -// Expect(1).To(WithTransform(plus1, Equal(2)) -// -//And(), Or(), Not() and WithTransform() allow matchers to be composed into complex expressions. -func WithTransform(transform interface{}, matcher types.GomegaMatcher) types.GomegaMatcher { - return matchers.NewWithTransformMatcher(transform, matcher) -} diff --git a/vendor/github.com/onsi/gomega/matchers/and.go b/vendor/github.com/onsi/gomega/matchers/and.go deleted file mode 100644 index d83a29164c..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/and.go +++ /dev/null @@ -1,63 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type AndMatcher struct { - Matchers []types.GomegaMatcher - - // state - firstFailedMatcher types.GomegaMatcher -} - -func (m *AndMatcher) Match(actual interface{}) (success bool, err error) { - m.firstFailedMatcher = nil - for _, matcher := range m.Matchers { - success, err := matcher.Match(actual) - if !success || err != nil { - m.firstFailedMatcher = matcher - return false, err - } - } - return true, nil -} - -func (m *AndMatcher) FailureMessage(actual interface{}) (message string) { - return m.firstFailedMatcher.FailureMessage(actual) -} - -func (m *AndMatcher) NegatedFailureMessage(actual interface{}) (message string) { - // not the most beautiful list of matchers, but not bad either... - return format.Message(actual, fmt.Sprintf("To not satisfy all of these matchers: %s", m.Matchers)) -} - -func (m *AndMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - /* - Example with 3 matchers: A, B, C - - Match evaluates them: T, F, => F - So match is currently F, what should MatchMayChangeInTheFuture() return? - Seems like it only depends on B, since currently B MUST change to allow the result to become T - - Match eval: T, T, T => T - So match is currently T, what should MatchMayChangeInTheFuture() return? - Seems to depend on ANY of them being able to change to F. - */ - - if m.firstFailedMatcher == nil { - // so all matchers succeeded.. Any one of them changing would change the result. - for _, matcher := range m.Matchers { - if oraclematcher.MatchMayChangeInTheFuture(matcher, actual) { - return true - } - } - return false // none of were going to change - } - // one of the matchers failed.. it must be able to change in order to affect the result - return oraclematcher.MatchMayChangeInTheFuture(m.firstFailedMatcher, actual) -} diff --git a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go b/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go deleted file mode 100644 index 89a1fc2116..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/assignable_to_type_of_matcher.go +++ /dev/null @@ -1,31 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type AssignableToTypeOfMatcher struct { - Expected interface{} -} - -func (matcher *AssignableToTypeOfMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil || matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } - - actualType := reflect.TypeOf(actual) - expectedType := reflect.TypeOf(matcher.Expected) - - return actualType.AssignableTo(expectedType), nil -} - -func (matcher *AssignableToTypeOfMatcher) FailureMessage(actual interface{}) string { - return format.Message(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)) -} - -func (matcher *AssignableToTypeOfMatcher) NegatedFailureMessage(actual interface{}) string { - return format.Message(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go b/vendor/github.com/onsi/gomega/matchers/be_a_directory.go deleted file mode 100644 index 7b6975e41e..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_directory.go +++ /dev/null @@ -1,54 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type notADirectoryError struct { - os.FileInfo -} - -func (t notADirectoryError) Error() string { - fileInfo := os.FileInfo(t) - switch { - case fileInfo.Mode().IsRegular(): - return "file is a regular file" - default: - return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) - } -} - -type BeADirectoryMatcher struct { - expected interface{} - err error -} - -func (matcher *BeADirectoryMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeADirectoryMatcher matcher expects a file path") - } - - fileInfo, err := os.Stat(actualFilename) - if err != nil { - matcher.err = err - return false, nil - } - - if !fileInfo.Mode().IsDir() { - matcher.err = notADirectoryError{fileInfo} - return false, nil - } - return true, nil -} - -func (matcher *BeADirectoryMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be a directory: %s", matcher.err)) -} - -func (matcher *BeADirectoryMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not be a directory")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go b/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go deleted file mode 100644 index e239131fb6..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_a_regular_file.go +++ /dev/null @@ -1,54 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type notARegularFileError struct { - os.FileInfo -} - -func (t notARegularFileError) Error() string { - fileInfo := os.FileInfo(t) - switch { - case fileInfo.IsDir(): - return "file is a directory" - default: - return fmt.Sprintf("file mode is: %s", fileInfo.Mode().String()) - } -} - -type BeARegularFileMatcher struct { - expected interface{} - err error -} - -func (matcher *BeARegularFileMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeARegularFileMatcher matcher expects a file path") - } - - fileInfo, err := os.Stat(actualFilename) - if err != nil { - matcher.err = err - return false, nil - } - - if !fileInfo.Mode().IsRegular() { - matcher.err = notARegularFileError{fileInfo} - return false, nil - } - return true, nil -} - -func (matcher *BeARegularFileMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be a regular file: %s", matcher.err)) -} - -func (matcher *BeARegularFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not be a regular file")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go b/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go deleted file mode 100644 index d42eba2234..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_an_existing_file.go +++ /dev/null @@ -1,38 +0,0 @@ -package matchers - -import ( - "fmt" - "os" - - "github.com/onsi/gomega/format" -) - -type BeAnExistingFileMatcher struct { - expected interface{} -} - -func (matcher *BeAnExistingFileMatcher) Match(actual interface{}) (success bool, err error) { - actualFilename, ok := actual.(string) - if !ok { - return false, fmt.Errorf("BeAnExistingFileMatcher matcher expects a file path") - } - - if _, err = os.Stat(actualFilename); err != nil { - switch { - case os.IsNotExist(err): - return false, nil - default: - return false, err - } - } - - return true, nil -} - -func (matcher *BeAnExistingFileMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to exist")) -} - -func (matcher *BeAnExistingFileMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to exist")) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go deleted file mode 100644 index c1b499597d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_closed_matcher.go +++ /dev/null @@ -1,45 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "reflect" -) - -type BeClosedMatcher struct { -} - -func (matcher *BeClosedMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("BeClosed matcher expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.SendDir { - return false, fmt.Errorf("BeClosed matcher cannot determine if a send-only channel is closed or open. Got:\n%s", format.Object(actual, 1)) - } - - winnerIndex, _, open := reflect.Select([]reflect.SelectCase{ - reflect.SelectCase{Dir: reflect.SelectRecv, Chan: channelValue}, - reflect.SelectCase{Dir: reflect.SelectDefault}, - }) - - var closed bool - if winnerIndex == 0 { - closed = !open - } else if winnerIndex == 1 { - closed = false - } - - return closed, nil -} - -func (matcher *BeClosedMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be closed") -} - -func (matcher *BeClosedMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be open") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go deleted file mode 100644 index 55bdd7d15d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_empty_matcher.go +++ /dev/null @@ -1,26 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type BeEmptyMatcher struct { -} - -func (matcher *BeEmptyMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := lengthOf(actual) - if !ok { - return false, fmt.Errorf("BeEmpty matcher expects a string/array/map/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == 0, nil -} - -func (matcher *BeEmptyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be empty") -} - -func (matcher *BeEmptyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be empty") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go deleted file mode 100644 index 32a0c3108a..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_equivalent_to_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "reflect" -) - -type BeEquivalentToMatcher struct { - Expected interface{} -} - -func (matcher *BeEquivalentToMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Both actual and expected must not be nil.") - } - - convertedActual := actual - - if actual != nil && matcher.Expected != nil && reflect.TypeOf(actual).ConvertibleTo(reflect.TypeOf(matcher.Expected)) { - convertedActual = reflect.ValueOf(actual).Convert(reflect.TypeOf(matcher.Expected)).Interface() - } - - return reflect.DeepEqual(convertedActual, matcher.Expected), nil -} - -func (matcher *BeEquivalentToMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be equivalent to", matcher.Expected) -} - -func (matcher *BeEquivalentToMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be equivalent to", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go deleted file mode 100644 index 0b224cbbc6..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_false_matcher.go +++ /dev/null @@ -1,25 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type BeFalseMatcher struct { -} - -func (matcher *BeFalseMatcher) Match(actual interface{}) (success bool, err error) { - if !isBool(actual) { - return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) - } - - return actual == false, nil -} - -func (matcher *BeFalseMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be false") -} - -func (matcher *BeFalseMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be false") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go b/vendor/github.com/onsi/gomega/matchers/be_identical_to.go deleted file mode 100644 index fdcda4d1fb..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_identical_to.go +++ /dev/null @@ -1,37 +0,0 @@ -package matchers - -import ( - "fmt" - "runtime" - - "github.com/onsi/gomega/format" -) - -type BeIdenticalToMatcher struct { - Expected interface{} -} - -func (matcher *BeIdenticalToMatcher) Match(actual interface{}) (success bool, matchErr error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } - - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - success = false - matchErr = nil - } - } - }() - - return actual == matcher.Expected, nil -} - -func (matcher *BeIdenticalToMatcher) FailureMessage(actual interface{}) string { - return format.Message(actual, "to be identical to", matcher.Expected) -} - -func (matcher *BeIdenticalToMatcher) NegatedFailureMessage(actual interface{}) string { - return format.Message(actual, "not to be identical to", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go deleted file mode 100644 index 7ee84fe1bc..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_nil_matcher.go +++ /dev/null @@ -1,18 +0,0 @@ -package matchers - -import "github.com/onsi/gomega/format" - -type BeNilMatcher struct { -} - -func (matcher *BeNilMatcher) Match(actual interface{}) (success bool, err error) { - return isNil(actual), nil -} - -func (matcher *BeNilMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be nil") -} - -func (matcher *BeNilMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be nil") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go deleted file mode 100644 index 0c157f61b9..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go +++ /dev/null @@ -1,120 +0,0 @@ -package matchers - -import ( - "fmt" - "math" - - "github.com/onsi/gomega/format" -) - -type BeNumericallyMatcher struct { - Comparator string - CompareTo []interface{} -} - -func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo[0]) -} - -func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo[0]) -} - -func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) { - if len(matcher.CompareTo) == 0 || len(matcher.CompareTo) > 2 { - return false, fmt.Errorf("BeNumerically requires 1 or 2 CompareTo arguments. Got:\n%s", format.Object(matcher.CompareTo, 1)) - } - if !isNumber(actual) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(actual, 1)) - } - if !isNumber(matcher.CompareTo[0]) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) - } - if len(matcher.CompareTo) == 2 && !isNumber(matcher.CompareTo[1]) { - return false, fmt.Errorf("Expected a number. Got:\n%s", format.Object(matcher.CompareTo[0], 1)) - } - - switch matcher.Comparator { - case "==", "~", ">", ">=", "<", "<=": - default: - return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) - } - - if isFloat(actual) || isFloat(matcher.CompareTo[0]) { - var secondOperand float64 = 1e-8 - if len(matcher.CompareTo) == 2 { - secondOperand = toFloat(matcher.CompareTo[1]) - } - success = matcher.matchFloats(toFloat(actual), toFloat(matcher.CompareTo[0]), secondOperand) - } else if isInteger(actual) { - var secondOperand int64 = 0 - if len(matcher.CompareTo) == 2 { - secondOperand = toInteger(matcher.CompareTo[1]) - } - success = matcher.matchIntegers(toInteger(actual), toInteger(matcher.CompareTo[0]), secondOperand) - } else if isUnsignedInteger(actual) { - var secondOperand uint64 = 0 - if len(matcher.CompareTo) == 2 { - secondOperand = toUnsignedInteger(matcher.CompareTo[1]) - } - success = matcher.matchUnsignedIntegers(toUnsignedInteger(actual), toUnsignedInteger(matcher.CompareTo[0]), secondOperand) - } else { - return false, fmt.Errorf("Failed to compare:\n%s\n%s:\n%s", format.Object(actual, 1), matcher.Comparator, format.Object(matcher.CompareTo[0], 1)) - } - - return success, nil -} - -func (matcher *BeNumericallyMatcher) matchIntegers(actual, compareTo, threshold int64) (success bool) { - switch matcher.Comparator { - case "==", "~": - diff := actual - compareTo - return -threshold <= diff && diff <= threshold - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} - -func (matcher *BeNumericallyMatcher) matchUnsignedIntegers(actual, compareTo, threshold uint64) (success bool) { - switch matcher.Comparator { - case "==", "~": - if actual < compareTo { - actual, compareTo = compareTo, actual - } - return actual-compareTo <= threshold - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} - -func (matcher *BeNumericallyMatcher) matchFloats(actual, compareTo, threshold float64) (success bool) { - switch matcher.Comparator { - case "~": - return math.Abs(actual-compareTo) <= threshold - case "==": - return (actual == compareTo) - case ">": - return (actual > compareTo) - case ">=": - return (actual >= compareTo) - case "<": - return (actual < compareTo) - case "<=": - return (actual <= compareTo) - } - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go deleted file mode 100644 index d7c32233ec..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_sent_matcher.go +++ /dev/null @@ -1,71 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type BeSentMatcher struct { - Arg interface{} - channelClosed bool -} - -func (matcher *BeSentMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("BeSent expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.RecvDir { - return false, fmt.Errorf("BeSent matcher cannot be passed a receive-only channel. Got:\n%s", format.Object(actual, 1)) - } - - argType := reflect.TypeOf(matcher.Arg) - assignable := argType.AssignableTo(channelType.Elem()) - - if !assignable { - return false, fmt.Errorf("Cannot pass:\n%s to the channel:\n%s\nThe types don't match.", format.Object(matcher.Arg, 1), format.Object(actual, 1)) - } - - argValue := reflect.ValueOf(matcher.Arg) - - defer func() { - if e := recover(); e != nil { - success = false - err = fmt.Errorf("Cannot send to a closed channel") - matcher.channelClosed = true - } - }() - - winnerIndex, _, _ := reflect.Select([]reflect.SelectCase{ - reflect.SelectCase{Dir: reflect.SelectSend, Chan: channelValue, Send: argValue}, - reflect.SelectCase{Dir: reflect.SelectDefault}, - }) - - var didSend bool - if winnerIndex == 0 { - didSend = true - } - - return didSend, nil -} - -func (matcher *BeSentMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to send:", matcher.Arg) -} - -func (matcher *BeSentMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to send:", matcher.Arg) -} - -func (matcher *BeSentMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - if !isChan(actual) { - return false - } - - return !matcher.channelClosed -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go deleted file mode 100644 index abda4eb1e7..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_temporally_matcher.go +++ /dev/null @@ -1,65 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "time" -) - -type BeTemporallyMatcher struct { - Comparator string - CompareTo time.Time - Threshold []time.Duration -} - -func (matcher *BeTemporallyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo) -} - -func (matcher *BeTemporallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo) -} - -func (matcher *BeTemporallyMatcher) Match(actual interface{}) (bool, error) { - // predicate to test for time.Time type - isTime := func(t interface{}) bool { - _, ok := t.(time.Time) - return ok - } - - if !isTime(actual) { - return false, fmt.Errorf("Expected a time.Time. Got:\n%s", format.Object(actual, 1)) - } - - switch matcher.Comparator { - case "==", "~", ">", ">=", "<", "<=": - default: - return false, fmt.Errorf("Unknown comparator: %s", matcher.Comparator) - } - - var threshold = time.Millisecond - if len(matcher.Threshold) == 1 { - threshold = matcher.Threshold[0] - } - - return matcher.matchTimes(actual.(time.Time), matcher.CompareTo, threshold), nil -} - -func (matcher *BeTemporallyMatcher) matchTimes(actual, compareTo time.Time, threshold time.Duration) (success bool) { - switch matcher.Comparator { - case "==": - return actual.Equal(compareTo) - case "~": - diff := actual.Sub(compareTo) - return -threshold <= diff && diff <= threshold - case ">": - return actual.After(compareTo) - case ">=": - return !actual.Before(compareTo) - case "<": - return actual.Before(compareTo) - case "<=": - return !actual.After(compareTo) - } - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go deleted file mode 100644 index 1275e5fc9d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_true_matcher.go +++ /dev/null @@ -1,25 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type BeTrueMatcher struct { -} - -func (matcher *BeTrueMatcher) Match(actual interface{}) (success bool, err error) { - if !isBool(actual) { - return false, fmt.Errorf("Expected a boolean. Got:\n%s", format.Object(actual, 1)) - } - - return actual.(bool), nil -} - -func (matcher *BeTrueMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be true") -} - -func (matcher *BeTrueMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be true") -} diff --git a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go deleted file mode 100644 index b39c9144be..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/be_zero_matcher.go +++ /dev/null @@ -1,27 +0,0 @@ -package matchers - -import ( - "github.com/onsi/gomega/format" - "reflect" -) - -type BeZeroMatcher struct { -} - -func (matcher *BeZeroMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil { - return true, nil - } - zeroValue := reflect.Zero(reflect.TypeOf(actual)).Interface() - - return reflect.DeepEqual(zeroValue, actual), nil - -} - -func (matcher *BeZeroMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to be zero-valued") -} - -func (matcher *BeZeroMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to be zero-valued") -} diff --git a/vendor/github.com/onsi/gomega/matchers/consist_of.go b/vendor/github.com/onsi/gomega/matchers/consist_of.go deleted file mode 100644 index 7b0e088684..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/consist_of.go +++ /dev/null @@ -1,80 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/matchers/support/goraph/bipartitegraph" -) - -type ConsistOfMatcher struct { - Elements []interface{} -} - -func (matcher *ConsistOfMatcher) Match(actual interface{}) (success bool, err error) { - if !isArrayOrSlice(actual) && !isMap(actual) { - return false, fmt.Errorf("ConsistOf matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1)) - } - - elements := matcher.Elements - if len(matcher.Elements) == 1 && isArrayOrSlice(matcher.Elements[0]) { - elements = []interface{}{} - value := reflect.ValueOf(matcher.Elements[0]) - for i := 0; i < value.Len(); i++ { - elements = append(elements, value.Index(i).Interface()) - } - } - - matchers := []interface{}{} - for _, element := range elements { - matcher, isMatcher := element.(omegaMatcher) - if !isMatcher { - matcher = &EqualMatcher{Expected: element} - } - matchers = append(matchers, matcher) - } - - values := matcher.valuesOf(actual) - - if len(values) != len(matchers) { - return false, nil - } - - neighbours := func(v, m interface{}) (bool, error) { - match, err := m.(omegaMatcher).Match(v) - return match && err == nil, nil - } - - bipartiteGraph, err := bipartitegraph.NewBipartiteGraph(values, matchers, neighbours) - if err != nil { - return false, err - } - - return len(bipartiteGraph.LargestMatching()) == len(values), nil -} - -func (matcher *ConsistOfMatcher) valuesOf(actual interface{}) []interface{} { - value := reflect.ValueOf(actual) - values := []interface{}{} - if isMap(actual) { - keys := value.MapKeys() - for i := 0; i < value.Len(); i++ { - values = append(values, value.MapIndex(keys[i]).Interface()) - } - } else { - for i := 0; i < value.Len(); i++ { - values = append(values, value.Index(i).Interface()) - } - } - - return values -} - -func (matcher *ConsistOfMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to consist of", matcher.Elements) -} - -func (matcher *ConsistOfMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to consist of", matcher.Elements) -} diff --git a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go deleted file mode 100644 index 4159335d0d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_element_matcher.go +++ /dev/null @@ -1,56 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type ContainElementMatcher struct { - Element interface{} -} - -func (matcher *ContainElementMatcher) Match(actual interface{}) (success bool, err error) { - if !isArrayOrSlice(actual) && !isMap(actual) { - return false, fmt.Errorf("ContainElement matcher expects an array/slice/map. Got:\n%s", format.Object(actual, 1)) - } - - elemMatcher, elementIsMatcher := matcher.Element.(omegaMatcher) - if !elementIsMatcher { - elemMatcher = &EqualMatcher{Expected: matcher.Element} - } - - value := reflect.ValueOf(actual) - var keys []reflect.Value - if isMap(actual) { - keys = value.MapKeys() - } - var lastError error - for i := 0; i < value.Len(); i++ { - var success bool - var err error - if isMap(actual) { - success, err = elemMatcher.Match(value.MapIndex(keys[i]).Interface()) - } else { - success, err = elemMatcher.Match(value.Index(i).Interface()) - } - if err != nil { - lastError = err - continue - } - if success { - return true, nil - } - } - - return false, lastError -} - -func (matcher *ContainElementMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to contain element matching", matcher.Element) -} - -func (matcher *ContainElementMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to contain element matching", matcher.Element) -} diff --git a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go b/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go deleted file mode 100644 index 2e7608921a..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/contain_substring_matcher.go +++ /dev/null @@ -1,37 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "strings" -) - -type ContainSubstringMatcher struct { - Substr string - Args []interface{} -} - -func (matcher *ContainSubstringMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("ContainSubstring matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - - return strings.Contains(actualString, matcher.stringToMatch()), nil -} - -func (matcher *ContainSubstringMatcher) stringToMatch() string { - stringToMatch := matcher.Substr - if len(matcher.Args) > 0 { - stringToMatch = fmt.Sprintf(matcher.Substr, matcher.Args...) - } - return stringToMatch -} - -func (matcher *ContainSubstringMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to contain substring", matcher.stringToMatch()) -} - -func (matcher *ContainSubstringMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to contain substring", matcher.stringToMatch()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go b/vendor/github.com/onsi/gomega/matchers/equal_matcher.go deleted file mode 100644 index 874e6a6229..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/equal_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type EqualMatcher struct { - Expected interface{} -} - -func (matcher *EqualMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil && matcher.Expected == nil { - return false, fmt.Errorf("Refusing to compare to .\nBe explicit and use BeNil() instead. This is to avoid mistakes where both sides of an assertion are erroneously uninitialized.") - } - return reflect.DeepEqual(actual, matcher.Expected), nil -} - -func (matcher *EqualMatcher) FailureMessage(actual interface{}) (message string) { - actualString, actualOK := actual.(string) - expectedString, expectedOK := matcher.Expected.(string) - if actualOK && expectedOK { - return format.MessageWithDiff(actualString, "to equal", expectedString) - } - - return format.Message(actual, "to equal", matcher.Expected) -} - -func (matcher *EqualMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to equal", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go deleted file mode 100644 index 7ace93dc36..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_cap_matcher.go +++ /dev/null @@ -1,28 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveCapMatcher struct { - Count int -} - -func (matcher *HaveCapMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := capOf(actual) - if !ok { - return false, fmt.Errorf("HaveCap matcher expects a array/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == matcher.Count, nil -} - -func (matcher *HaveCapMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nto have capacity %d", format.Object(actual, 1), matcher.Count) -} - -func (matcher *HaveCapMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nnot to have capacity %d", format.Object(actual, 1), matcher.Count) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go deleted file mode 100644 index 5701ba6e24..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_matcher.go +++ /dev/null @@ -1,53 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "reflect" -) - -type HaveKeyMatcher struct { - Key interface{} -} - -func (matcher *HaveKeyMatcher) Match(actual interface{}) (success bool, err error) { - if !isMap(actual) { - return false, fmt.Errorf("HaveKey matcher expects a map. Got:%s", format.Object(actual, 1)) - } - - keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) - if !keyIsMatcher { - keyMatcher = &EqualMatcher{Expected: matcher.Key} - } - - keys := reflect.ValueOf(actual).MapKeys() - for i := 0; i < len(keys); i++ { - success, err := keyMatcher.Match(keys[i].Interface()) - if err != nil { - return false, fmt.Errorf("HaveKey's key matcher failed with:\n%s%s", format.Indent, err.Error()) - } - if success { - return true, nil - } - } - - return false, nil -} - -func (matcher *HaveKeyMatcher) FailureMessage(actual interface{}) (message string) { - switch matcher.Key.(type) { - case omegaMatcher: - return format.Message(actual, "to have key matching", matcher.Key) - default: - return format.Message(actual, "to have key", matcher.Key) - } -} - -func (matcher *HaveKeyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - switch matcher.Key.(type) { - case omegaMatcher: - return format.Message(actual, "not to have key matching", matcher.Key) - default: - return format.Message(actual, "not to have key", matcher.Key) - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go deleted file mode 100644 index 464ac187e9..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_key_with_value_matcher.go +++ /dev/null @@ -1,73 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "reflect" -) - -type HaveKeyWithValueMatcher struct { - Key interface{} - Value interface{} -} - -func (matcher *HaveKeyWithValueMatcher) Match(actual interface{}) (success bool, err error) { - if !isMap(actual) { - return false, fmt.Errorf("HaveKeyWithValue matcher expects a map. Got:%s", format.Object(actual, 1)) - } - - keyMatcher, keyIsMatcher := matcher.Key.(omegaMatcher) - if !keyIsMatcher { - keyMatcher = &EqualMatcher{Expected: matcher.Key} - } - - valueMatcher, valueIsMatcher := matcher.Value.(omegaMatcher) - if !valueIsMatcher { - valueMatcher = &EqualMatcher{Expected: matcher.Value} - } - - keys := reflect.ValueOf(actual).MapKeys() - for i := 0; i < len(keys); i++ { - success, err := keyMatcher.Match(keys[i].Interface()) - if err != nil { - return false, fmt.Errorf("HaveKeyWithValue's key matcher failed with:\n%s%s", format.Indent, err.Error()) - } - if success { - actualValue := reflect.ValueOf(actual).MapIndex(keys[i]) - success, err := valueMatcher.Match(actualValue.Interface()) - if err != nil { - return false, fmt.Errorf("HaveKeyWithValue's value matcher failed with:\n%s%s", format.Indent, err.Error()) - } - return success, nil - } - } - - return false, nil -} - -func (matcher *HaveKeyWithValueMatcher) FailureMessage(actual interface{}) (message string) { - str := "to have {key: value}" - if _, ok := matcher.Key.(omegaMatcher); ok { - str += " matching" - } else if _, ok := matcher.Value.(omegaMatcher); ok { - str += " matching" - } - - expect := make(map[interface{}]interface{}, 1) - expect[matcher.Key] = matcher.Value - return format.Message(actual, str, expect) -} - -func (matcher *HaveKeyWithValueMatcher) NegatedFailureMessage(actual interface{}) (message string) { - kStr := "not to have key" - if _, ok := matcher.Key.(omegaMatcher); ok { - kStr = "not to have key matching" - } - - vStr := "or that key's value not be" - if _, ok := matcher.Value.(omegaMatcher); ok { - vStr = "or to have that key's value not matching" - } - - return format.Message(actual, kStr, matcher.Key, vStr, matcher.Value) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go deleted file mode 100644 index a183775570..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_len_matcher.go +++ /dev/null @@ -1,27 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type HaveLenMatcher struct { - Count int -} - -func (matcher *HaveLenMatcher) Match(actual interface{}) (success bool, err error) { - length, ok := lengthOf(actual) - if !ok { - return false, fmt.Errorf("HaveLen matcher expects a string/array/map/channel/slice. Got:\n%s", format.Object(actual, 1)) - } - - return length == matcher.Count, nil -} - -func (matcher *HaveLenMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nto have length %d", format.Object(actual, 1), matcher.Count) -} - -func (matcher *HaveLenMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected\n%s\nnot to have length %d", format.Object(actual, 1), matcher.Count) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go deleted file mode 100644 index ebdd71786d..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_occurred_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type HaveOccurredMatcher struct { -} - -func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) { - // is purely nil? - if actual == nil { - return false, nil - } - - // must be an 'error' type - if !isError(actual) { - return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) - } - - // must be non-nil (or a pointer to a non-nil) - return !isNil(actual), nil -} - -func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected an error to have occurred. Got:\n%s", format.Object(actual, 1)) -} - -func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "not to have occurred") -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go deleted file mode 100644 index 8b63a89997..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_prefix_matcher.go +++ /dev/null @@ -1,35 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type HavePrefixMatcher struct { - Prefix string - Args []interface{} -} - -func (matcher *HavePrefixMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("HavePrefix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - prefix := matcher.prefix() - return len(actualString) >= len(prefix) && actualString[0:len(prefix)] == prefix, nil -} - -func (matcher *HavePrefixMatcher) prefix() string { - if len(matcher.Args) > 0 { - return fmt.Sprintf(matcher.Prefix, matcher.Args...) - } - return matcher.Prefix -} - -func (matcher *HavePrefixMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to have prefix", matcher.prefix()) -} - -func (matcher *HavePrefixMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to have prefix", matcher.prefix()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go b/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go deleted file mode 100644 index afc78fc901..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/have_suffix_matcher.go +++ /dev/null @@ -1,35 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" -) - -type HaveSuffixMatcher struct { - Suffix string - Args []interface{} -} - -func (matcher *HaveSuffixMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("HaveSuffix matcher requires a string or stringer. Got:\n%s", format.Object(actual, 1)) - } - suffix := matcher.suffix() - return len(actualString) >= len(suffix) && actualString[len(actualString)-len(suffix):] == suffix, nil -} - -func (matcher *HaveSuffixMatcher) suffix() string { - if len(matcher.Args) > 0 { - return fmt.Sprintf(matcher.Suffix, matcher.Args...) - } - return matcher.Suffix -} - -func (matcher *HaveSuffixMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to have suffix", matcher.suffix()) -} - -func (matcher *HaveSuffixMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to have suffix", matcher.suffix()) -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go deleted file mode 100644 index 03cdf04588..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_error_matcher.go +++ /dev/null @@ -1,50 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "reflect" -) - -type MatchErrorMatcher struct { - Expected interface{} -} - -func (matcher *MatchErrorMatcher) Match(actual interface{}) (success bool, err error) { - if isNil(actual) { - return false, fmt.Errorf("Expected an error, got nil") - } - - if !isError(actual) { - return false, fmt.Errorf("Expected an error. Got:\n%s", format.Object(actual, 1)) - } - - actualErr := actual.(error) - - if isString(matcher.Expected) { - return reflect.DeepEqual(actualErr.Error(), matcher.Expected), nil - } - - if isError(matcher.Expected) { - return reflect.DeepEqual(actualErr, matcher.Expected), nil - } - - var subMatcher omegaMatcher - var hasSubMatcher bool - if matcher.Expected != nil { - subMatcher, hasSubMatcher = (matcher.Expected).(omegaMatcher) - if hasSubMatcher { - return subMatcher.Match(actualErr.Error()) - } - } - - return false, fmt.Errorf("MatchError must be passed an error, string, or Matcher that can match on strings. Got:\n%s", format.Object(matcher.Expected, 1)) -} - -func (matcher *MatchErrorMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to match error", matcher.Expected) -} - -func (matcher *MatchErrorMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match error", matcher.Expected) -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go deleted file mode 100644 index 499bb58301..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go +++ /dev/null @@ -1,135 +0,0 @@ -package matchers - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strings" - - "github.com/onsi/gomega/format" -) - -type MatchJSONMatcher struct { - JSONToMatch interface{} - firstFailurePath []interface{} -} - -func (matcher *MatchJSONMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.prettyPrint(actual) - if err != nil { - return false, err - } - - var aval interface{} - var eval interface{} - - // this is guarded by prettyPrint - json.Unmarshal([]byte(actualString), &aval) - json.Unmarshal([]byte(expectedString), &eval) - var equal bool - equal, matcher.firstFailurePath = deepEqual(aval, eval) - return equal, nil -} - -func (matcher *MatchJSONMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.prettyPrint(actual) - return formattedMessage(format.Message(actualString, "to match JSON of", expectedString), matcher.firstFailurePath) -} - -func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.prettyPrint(actual) - return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) -} - -func formattedMessage(comparisonMessage string, failurePath []interface{}) string { - var diffMessage string - if len(failurePath) == 0 { - diffMessage = "" - } else { - diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath)) - } - return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) -} - -func formattedFailurePath(failurePath []interface{}) string { - formattedPaths := []string{} - for i := len(failurePath) - 1; i >= 0; i-- { - switch p := failurePath[i].(type) { - case int: - formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p)) - default: - if i != len(failurePath)-1 { - formattedPaths = append(formattedPaths, ".") - } - formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p)) - } - } - return strings.Join(formattedPaths, "") -} - -func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, ok := toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok := toString(matcher.JSONToMatch) - if !ok { - return "", "", fmt.Errorf("MatchJSONMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.JSONToMatch, 1)) - } - - abuf := new(bytes.Buffer) - ebuf := new(bytes.Buffer) - - if err := json.Indent(abuf, []byte(actualString), "", " "); err != nil { - return "", "", fmt.Errorf("Actual '%s' should be valid JSON, but it is not.\nUnderlying error:%s", actualString, err) - } - - if err := json.Indent(ebuf, []byte(expectedString), "", " "); err != nil { - return "", "", fmt.Errorf("Expected '%s' should be valid JSON, but it is not.\nUnderlying error:%s", expectedString, err) - } - - return abuf.String(), ebuf.String(), nil -} - -func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { - var errorPath []interface{} - if reflect.TypeOf(a) != reflect.TypeOf(b) { - return false, errorPath - } - - switch a.(type) { - case []interface{}: - if len(a.([]interface{})) != len(b.([]interface{})) { - return false, errorPath - } - - for i, v := range a.([]interface{}) { - elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) - if !elementEqual { - return false, append(keyPath, i) - } - } - return true, errorPath - - case map[string]interface{}: - if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { - return false, errorPath - } - - for k, v1 := range a.(map[string]interface{}) { - v2, ok := b.(map[string]interface{})[k] - if !ok { - return false, errorPath - } - elementEqual, keyPath := deepEqual(v1, v2) - if !elementEqual { - return false, append(keyPath, k) - } - } - return true, errorPath - - default: - return a == b, errorPath - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go deleted file mode 100644 index 7ca79a15be..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_regexp_matcher.go +++ /dev/null @@ -1,42 +0,0 @@ -package matchers - -import ( - "fmt" - "github.com/onsi/gomega/format" - "regexp" -) - -type MatchRegexpMatcher struct { - Regexp string - Args []interface{} -} - -func (matcher *MatchRegexpMatcher) Match(actual interface{}) (success bool, err error) { - actualString, ok := toString(actual) - if !ok { - return false, fmt.Errorf("RegExp matcher requires a string or stringer.\nGot:%s", format.Object(actual, 1)) - } - - match, err := regexp.Match(matcher.regexp(), []byte(actualString)) - if err != nil { - return false, fmt.Errorf("RegExp match failed to compile with error:\n\t%s", err.Error()) - } - - return match, nil -} - -func (matcher *MatchRegexpMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to match regular expression", matcher.regexp()) -} - -func (matcher *MatchRegexpMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, "not to match regular expression", matcher.regexp()) -} - -func (matcher *MatchRegexpMatcher) regexp() string { - re := matcher.Regexp - if len(matcher.Args) > 0 { - re = fmt.Sprintf(matcher.Regexp, matcher.Args...) - } - return re -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go deleted file mode 100644 index da26562902..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_xml_matcher.go +++ /dev/null @@ -1,131 +0,0 @@ -package matchers - -import ( - "bytes" - "encoding/xml" - "errors" - "fmt" - "io" - "reflect" - "strings" - - "github.com/onsi/gomega/format" - "golang.org/x/net/html/charset" -) - -type MatchXMLMatcher struct { - XMLToMatch interface{} -} - -func (matcher *MatchXMLMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.formattedPrint(actual) - if err != nil { - return false, err - } - - aval, err := parseXmlContent(actualString) - if err != nil { - return false, fmt.Errorf("Actual '%s' should be valid XML, but it is not.\nUnderlying error:%s", actualString, err) - } - - eval, err := parseXmlContent(expectedString) - if err != nil { - return false, fmt.Errorf("Expected '%s' should be valid XML, but it is not.\nUnderlying error:%s", expectedString, err) - } - - return reflect.DeepEqual(aval, eval), nil -} - -func (matcher *MatchXMLMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.formattedPrint(actual) - return fmt.Sprintf("Expected\n%s\nto match XML of\n%s", actualString, expectedString) -} - -func (matcher *MatchXMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.formattedPrint(actual) - return fmt.Sprintf("Expected\n%s\nnot to match XML of\n%s", actualString, expectedString) -} - -func (matcher *MatchXMLMatcher) formattedPrint(actual interface{}) (actualString, expectedString string, err error) { - var ok bool - actualString, ok = toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok = toString(matcher.XMLToMatch) - if !ok { - return "", "", fmt.Errorf("MatchXMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.XMLToMatch, 1)) - } - return actualString, expectedString, nil -} - -func parseXmlContent(content string) (*xmlNode, error) { - allNodes := []*xmlNode{} - - dec := newXmlDecoder(strings.NewReader(content)) - for { - tok, err := dec.Token() - if err != nil { - if err == io.EOF { - break - } - return nil, fmt.Errorf("failed to decode next token: %v", err) - } - - lastNodeIndex := len(allNodes) - 1 - var lastNode *xmlNode - if len(allNodes) > 0 { - lastNode = allNodes[lastNodeIndex] - } else { - lastNode = &xmlNode{} - } - - switch tok := tok.(type) { - case xml.StartElement: - allNodes = append(allNodes, &xmlNode{XMLName: tok.Name, XMLAttr: tok.Attr}) - case xml.EndElement: - if len(allNodes) > 1 { - allNodes[lastNodeIndex-1].Nodes = append(allNodes[lastNodeIndex-1].Nodes, lastNode) - allNodes = allNodes[:lastNodeIndex] - } - case xml.CharData: - lastNode.Content = append(lastNode.Content, tok.Copy()...) - case xml.Comment: - lastNode.Comments = append(lastNode.Comments, tok.Copy()) - case xml.ProcInst: - lastNode.ProcInsts = append(lastNode.ProcInsts, tok.Copy()) - } - } - - if len(allNodes) == 0 { - return nil, errors.New("found no nodes") - } - firstNode := allNodes[0] - trimParentNodesContentSpaces(firstNode) - - return firstNode, nil -} - -func newXmlDecoder(reader io.Reader) *xml.Decoder { - dec := xml.NewDecoder(reader) - dec.CharsetReader = charset.NewReaderLabel - return dec -} - -func trimParentNodesContentSpaces(node *xmlNode) { - if len(node.Nodes) > 0 { - node.Content = bytes.TrimSpace(node.Content) - for _, childNode := range node.Nodes { - trimParentNodesContentSpaces(childNode) - } - } -} - -type xmlNode struct { - XMLName xml.Name - Comments []xml.Comment - ProcInsts []xml.ProcInst - XMLAttr []xml.Attr - Content []byte - Nodes []*xmlNode -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go deleted file mode 100644 index 69fb51a859..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go +++ /dev/null @@ -1,74 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - "strings" - - "github.com/onsi/gomega/format" - "gopkg.in/yaml.v2" -) - -type MatchYAMLMatcher struct { - YAMLToMatch interface{} -} - -func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { - actualString, expectedString, err := matcher.toStrings(actual) - if err != nil { - return false, err - } - - var aval interface{} - var eval interface{} - - if err := yaml.Unmarshal([]byte(actualString), &aval); err != nil { - return false, fmt.Errorf("Actual '%s' should be valid YAML, but it is not.\nUnderlying error:%s", actualString, err) - } - if err := yaml.Unmarshal([]byte(expectedString), &eval); err != nil { - return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err) - } - - return reflect.DeepEqual(aval, eval), nil -} - -func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return format.Message(actualString, "to match YAML of", expectedString) -} - -func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { - actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return format.Message(actualString, "not to match YAML of", expectedString) -} - -func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, expectedString, err := matcher.toStrings(actual) - return normalise(actualString), normalise(expectedString), err -} - -func normalise(input string) string { - var val interface{} - err := yaml.Unmarshal([]byte(input), &val) - if err != nil { - panic(err) // guarded by Match - } - output, err := yaml.Marshal(val) - if err != nil { - panic(err) // guarded by Unmarshal - } - return strings.TrimSpace(string(output)) -} - -func (matcher *MatchYAMLMatcher) toStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { - actualString, ok := toString(actual) - if !ok { - return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got actual:\n%s", format.Object(actual, 1)) - } - expectedString, ok := toString(matcher.YAMLToMatch) - if !ok { - return "", "", fmt.Errorf("MatchYAMLMatcher matcher requires a string, stringer, or []byte. Got expected:\n%s", format.Object(matcher.YAMLToMatch, 1)) - } - - return actualString, expectedString, nil -} diff --git a/vendor/github.com/onsi/gomega/matchers/not.go b/vendor/github.com/onsi/gomega/matchers/not.go deleted file mode 100644 index 2c91670bd9..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/not.go +++ /dev/null @@ -1,30 +0,0 @@ -package matchers - -import ( - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type NotMatcher struct { - Matcher types.GomegaMatcher -} - -func (m *NotMatcher) Match(actual interface{}) (bool, error) { - success, err := m.Matcher.Match(actual) - if err != nil { - return false, err - } - return !success, nil -} - -func (m *NotMatcher) FailureMessage(actual interface{}) (message string) { - return m.Matcher.NegatedFailureMessage(actual) // works beautifully -} - -func (m *NotMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return m.Matcher.FailureMessage(actual) // works beautifully -} - -func (m *NotMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - return oraclematcher.MatchMayChangeInTheFuture(m.Matcher, actual) // just return m.Matcher's value -} diff --git a/vendor/github.com/onsi/gomega/matchers/or.go b/vendor/github.com/onsi/gomega/matchers/or.go deleted file mode 100644 index 3bf7998001..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/or.go +++ /dev/null @@ -1,67 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type OrMatcher struct { - Matchers []types.GomegaMatcher - - // state - firstSuccessfulMatcher types.GomegaMatcher -} - -func (m *OrMatcher) Match(actual interface{}) (success bool, err error) { - m.firstSuccessfulMatcher = nil - for _, matcher := range m.Matchers { - success, err := matcher.Match(actual) - if err != nil { - return false, err - } - if success { - m.firstSuccessfulMatcher = matcher - return true, nil - } - } - return false, nil -} - -func (m *OrMatcher) FailureMessage(actual interface{}) (message string) { - // not the most beautiful list of matchers, but not bad either... - return format.Message(actual, fmt.Sprintf("To satisfy at least one of these matchers: %s", m.Matchers)) -} - -func (m *OrMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return m.firstSuccessfulMatcher.NegatedFailureMessage(actual) -} - -func (m *OrMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - /* - Example with 3 matchers: A, B, C - - Match evaluates them: F, T, => T - So match is currently T, what should MatchMayChangeInTheFuture() return? - Seems like it only depends on B, since currently B MUST change to allow the result to become F - - Match eval: F, F, F => F - So match is currently F, what should MatchMayChangeInTheFuture() return? - Seems to depend on ANY of them being able to change to T. - */ - - if m.firstSuccessfulMatcher != nil { - // one of the matchers succeeded.. it must be able to change in order to affect the result - return oraclematcher.MatchMayChangeInTheFuture(m.firstSuccessfulMatcher, actual) - } else { - // so all matchers failed.. Any one of them changing would change the result. - for _, matcher := range m.Matchers { - if oraclematcher.MatchMayChangeInTheFuture(matcher, actual) { - return true - } - } - return false // none of were going to change - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go b/vendor/github.com/onsi/gomega/matchers/panic_matcher.go deleted file mode 100644 index 640f4db1a3..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/panic_matcher.go +++ /dev/null @@ -1,46 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type PanicMatcher struct { - object interface{} -} - -func (matcher *PanicMatcher) Match(actual interface{}) (success bool, err error) { - if actual == nil { - return false, fmt.Errorf("PanicMatcher expects a non-nil actual.") - } - - actualType := reflect.TypeOf(actual) - if actualType.Kind() != reflect.Func { - return false, fmt.Errorf("PanicMatcher expects a function. Got:\n%s", format.Object(actual, 1)) - } - if !(actualType.NumIn() == 0 && actualType.NumOut() == 0) { - return false, fmt.Errorf("PanicMatcher expects a function with no arguments and no return value. Got:\n%s", format.Object(actual, 1)) - } - - success = false - defer func() { - if e := recover(); e != nil { - matcher.object = e - success = true - } - }() - - reflect.ValueOf(actual).Call([]reflect.Value{}) - - return -} - -func (matcher *PanicMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, "to panic") -} - -func (matcher *PanicMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to panic, but panicked with\n%s", format.Object(matcher.object, 1))) -} diff --git a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go b/vendor/github.com/onsi/gomega/matchers/receive_matcher.go deleted file mode 100644 index 74e9e7ebe1..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/receive_matcher.go +++ /dev/null @@ -1,122 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/format" -) - -type ReceiveMatcher struct { - Arg interface{} - receivedValue reflect.Value - channelClosed bool -} - -func (matcher *ReceiveMatcher) Match(actual interface{}) (success bool, err error) { - if !isChan(actual) { - return false, fmt.Errorf("ReceiveMatcher expects a channel. Got:\n%s", format.Object(actual, 1)) - } - - channelType := reflect.TypeOf(actual) - channelValue := reflect.ValueOf(actual) - - if channelType.ChanDir() == reflect.SendDir { - return false, fmt.Errorf("ReceiveMatcher matcher cannot be passed a send-only channel. Got:\n%s", format.Object(actual, 1)) - } - - var subMatcher omegaMatcher - var hasSubMatcher bool - - if matcher.Arg != nil { - subMatcher, hasSubMatcher = (matcher.Arg).(omegaMatcher) - if !hasSubMatcher { - argType := reflect.TypeOf(matcher.Arg) - if argType.Kind() != reflect.Ptr { - return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s\nYou need to pass a pointer!", format.Object(actual, 1), format.Object(matcher.Arg, 1)) - } - - assignable := channelType.Elem().AssignableTo(argType.Elem()) - if !assignable { - return false, fmt.Errorf("Cannot assign a value from the channel:\n%s\nTo:\n%s", format.Object(actual, 1), format.Object(matcher.Arg, 1)) - } - } - } - - winnerIndex, value, open := reflect.Select([]reflect.SelectCase{ - reflect.SelectCase{Dir: reflect.SelectRecv, Chan: channelValue}, - reflect.SelectCase{Dir: reflect.SelectDefault}, - }) - - var closed bool - var didReceive bool - if winnerIndex == 0 { - closed = !open - didReceive = open - } - matcher.channelClosed = closed - - if closed { - return false, nil - } - - if hasSubMatcher { - if didReceive { - matcher.receivedValue = value - return subMatcher.Match(matcher.receivedValue.Interface()) - } - return false, nil - } - - if didReceive { - if matcher.Arg != nil { - outValue := reflect.ValueOf(matcher.Arg) - reflect.Indirect(outValue).Set(value) - } - - return true, nil - } - return false, nil -} - -func (matcher *ReceiveMatcher) FailureMessage(actual interface{}) (message string) { - subMatcher, hasSubMatcher := (matcher.Arg).(omegaMatcher) - - closedAddendum := "" - if matcher.channelClosed { - closedAddendum = " The channel is closed." - } - - if hasSubMatcher { - if matcher.receivedValue.IsValid() { - return subMatcher.FailureMessage(matcher.receivedValue.Interface()) - } - return "When passed a matcher, ReceiveMatcher's channel *must* receive something." - } - return format.Message(actual, "to receive something."+closedAddendum) -} - -func (matcher *ReceiveMatcher) NegatedFailureMessage(actual interface{}) (message string) { - subMatcher, hasSubMatcher := (matcher.Arg).(omegaMatcher) - - closedAddendum := "" - if matcher.channelClosed { - closedAddendum = " The channel is closed." - } - - if hasSubMatcher { - if matcher.receivedValue.IsValid() { - return subMatcher.NegatedFailureMessage(matcher.receivedValue.Interface()) - } - return "When passed a matcher, ReceiveMatcher's channel *must* receive something." - } - return format.Message(actual, "not to receive anything."+closedAddendum) -} - -func (matcher *ReceiveMatcher) MatchMayChangeInTheFuture(actual interface{}) bool { - if !isChan(actual) { - return false - } - - return !matcher.channelClosed -} diff --git a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go b/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go deleted file mode 100644 index 721ed5529b..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/succeed_matcher.go +++ /dev/null @@ -1,33 +0,0 @@ -package matchers - -import ( - "fmt" - - "github.com/onsi/gomega/format" -) - -type SucceedMatcher struct { -} - -func (matcher *SucceedMatcher) Match(actual interface{}) (success bool, err error) { - // is purely nil? - if actual == nil { - return true, nil - } - - // must be an 'error' type - if !isError(actual) { - return false, fmt.Errorf("Expected an error-type. Got:\n%s", format.Object(actual, 1)) - } - - // must be nil (or a pointer to a nil) - return isNil(actual), nil -} - -func (matcher *SucceedMatcher) FailureMessage(actual interface{}) (message string) { - return fmt.Sprintf("Expected success, but got an error:\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1)) -} - -func (matcher *SucceedMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return "Expected failure, but got no error." -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go deleted file mode 100644 index 119d21ef31..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraph.go +++ /dev/null @@ -1,41 +0,0 @@ -package bipartitegraph - -import "errors" -import "fmt" - -import . "github.com/onsi/gomega/matchers/support/goraph/node" -import . "github.com/onsi/gomega/matchers/support/goraph/edge" - -type BipartiteGraph struct { - Left NodeOrderedSet - Right NodeOrderedSet - Edges EdgeSet -} - -func NewBipartiteGraph(leftValues, rightValues []interface{}, neighbours func(interface{}, interface{}) (bool, error)) (*BipartiteGraph, error) { - left := NodeOrderedSet{} - for i, _ := range leftValues { - left = append(left, Node{i}) - } - - right := NodeOrderedSet{} - for j, _ := range rightValues { - right = append(right, Node{j + len(left)}) - } - - edges := EdgeSet{} - for i, leftValue := range leftValues { - for j, rightValue := range rightValues { - neighbours, err := neighbours(leftValue, rightValue) - if err != nil { - return nil, errors.New(fmt.Sprintf("error determining adjacency for %v and %v: %s", leftValue, rightValue, err.Error())) - } - - if neighbours { - edges = append(edges, Edge{left[i], right[j]}) - } - } - } - - return &BipartiteGraph{left, right, edges}, nil -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go deleted file mode 100644 index 8181f43a40..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/bipartitegraph/bipartitegraphmatching.go +++ /dev/null @@ -1,159 +0,0 @@ -package bipartitegraph - -import . "github.com/onsi/gomega/matchers/support/goraph/node" -import . "github.com/onsi/gomega/matchers/support/goraph/edge" -import "github.com/onsi/gomega/matchers/support/goraph/util" - -func (bg *BipartiteGraph) LargestMatching() (matching EdgeSet) { - paths := bg.maximalDisjointSLAPCollection(matching) - - for len(paths) > 0 { - for _, path := range paths { - matching = matching.SymmetricDifference(path) - } - paths = bg.maximalDisjointSLAPCollection(matching) - } - - return -} - -func (bg *BipartiteGraph) maximalDisjointSLAPCollection(matching EdgeSet) (result []EdgeSet) { - guideLayers := bg.createSLAPGuideLayers(matching) - if len(guideLayers) == 0 { - return - } - - used := make(map[Node]bool) - - for _, u := range guideLayers[len(guideLayers)-1] { - slap, found := bg.findDisjointSLAP(u, matching, guideLayers, used) - if found { - for _, edge := range slap { - used[edge.Node1] = true - used[edge.Node2] = true - } - result = append(result, slap) - } - } - - return -} - -func (bg *BipartiteGraph) findDisjointSLAP( - start Node, - matching EdgeSet, - guideLayers []NodeOrderedSet, - used map[Node]bool, -) ([]Edge, bool) { - return bg.findDisjointSLAPHelper(start, EdgeSet{}, len(guideLayers)-1, matching, guideLayers, used) -} - -func (bg *BipartiteGraph) findDisjointSLAPHelper( - currentNode Node, - currentSLAP EdgeSet, - currentLevel int, - matching EdgeSet, - guideLayers []NodeOrderedSet, - used map[Node]bool, -) (EdgeSet, bool) { - used[currentNode] = true - - if currentLevel == 0 { - return currentSLAP, true - } - - for _, nextNode := range guideLayers[currentLevel-1] { - if used[nextNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(currentNode, nextNode) - if !found { - continue - } - - if matching.Contains(edge) == util.Odd(currentLevel) { - continue - } - - currentSLAP = append(currentSLAP, edge) - slap, found := bg.findDisjointSLAPHelper(nextNode, currentSLAP, currentLevel-1, matching, guideLayers, used) - if found { - return slap, true - } - currentSLAP = currentSLAP[:len(currentSLAP)-1] - } - - used[currentNode] = false - return nil, false -} - -func (bg *BipartiteGraph) createSLAPGuideLayers(matching EdgeSet) (guideLayers []NodeOrderedSet) { - used := make(map[Node]bool) - currentLayer := NodeOrderedSet{} - - for _, node := range bg.Left { - if matching.Free(node) { - used[node] = true - currentLayer = append(currentLayer, node) - } - } - - if len(currentLayer) == 0 { - return []NodeOrderedSet{} - } - guideLayers = append(guideLayers, currentLayer) - - done := false - - for !done { - lastLayer := currentLayer - currentLayer = NodeOrderedSet{} - - if util.Odd(len(guideLayers)) { - for _, leftNode := range lastLayer { - for _, rightNode := range bg.Right { - if used[rightNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(leftNode, rightNode) - if !found || matching.Contains(edge) { - continue - } - - currentLayer = append(currentLayer, rightNode) - used[rightNode] = true - - if matching.Free(rightNode) { - done = true - } - } - } - } else { - for _, rightNode := range lastLayer { - for _, leftNode := range bg.Left { - if used[leftNode] { - continue - } - - edge, found := bg.Edges.FindByNodes(leftNode, rightNode) - if !found || !matching.Contains(edge) { - continue - } - - currentLayer = append(currentLayer, leftNode) - used[leftNode] = true - } - } - - } - - if len(currentLayer) == 0 { - return []NodeOrderedSet{} - } - guideLayers = append(guideLayers, currentLayer) - } - - return -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go deleted file mode 100644 index 4fd15cc069..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/edge/edge.go +++ /dev/null @@ -1,61 +0,0 @@ -package edge - -import . "github.com/onsi/gomega/matchers/support/goraph/node" - -type Edge struct { - Node1 Node - Node2 Node -} - -type EdgeSet []Edge - -func (ec EdgeSet) Free(node Node) bool { - for _, e := range ec { - if e.Node1 == node || e.Node2 == node { - return false - } - } - - return true -} - -func (ec EdgeSet) Contains(edge Edge) bool { - for _, e := range ec { - if e == edge { - return true - } - } - - return false -} - -func (ec EdgeSet) FindByNodes(node1, node2 Node) (Edge, bool) { - for _, e := range ec { - if (e.Node1 == node1 && e.Node2 == node2) || (e.Node1 == node2 && e.Node2 == node1) { - return e, true - } - } - - return Edge{}, false -} - -func (ec EdgeSet) SymmetricDifference(ec2 EdgeSet) EdgeSet { - edgesToInclude := make(map[Edge]bool) - - for _, e := range ec { - edgesToInclude[e] = true - } - - for _, e := range ec2 { - edgesToInclude[e] = !edgesToInclude[e] - } - - result := EdgeSet{} - for e, include := range edgesToInclude { - if include { - result = append(result, e) - } - } - - return result -} diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go deleted file mode 100644 index 800c2ea8ca..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/node/node.go +++ /dev/null @@ -1,7 +0,0 @@ -package node - -type Node struct { - Id int -} - -type NodeOrderedSet []Node diff --git a/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go b/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go deleted file mode 100644 index d76a1ee00a..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/support/goraph/util/util.go +++ /dev/null @@ -1,7 +0,0 @@ -package util - -import "math" - -func Odd(n int) bool { - return math.Mod(float64(n), 2.0) == 1.0 -} diff --git a/vendor/github.com/onsi/gomega/matchers/type_support.go b/vendor/github.com/onsi/gomega/matchers/type_support.go deleted file mode 100644 index b05a5e75d4..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/type_support.go +++ /dev/null @@ -1,173 +0,0 @@ -/* -Gomega matchers - -This package implements the Gomega matchers and does not typically need to be imported. -See the docs for Gomega for documentation on the matchers - -http://onsi.github.io/gomega/ -*/ -package matchers - -import ( - "fmt" - "reflect" -) - -type omegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) -} - -func isBool(a interface{}) bool { - return reflect.TypeOf(a).Kind() == reflect.Bool -} - -func isNumber(a interface{}) bool { - if a == nil { - return false - } - kind := reflect.TypeOf(a).Kind() - return reflect.Int <= kind && kind <= reflect.Float64 -} - -func isInteger(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Int <= kind && kind <= reflect.Int64 -} - -func isUnsignedInteger(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Uint <= kind && kind <= reflect.Uint64 -} - -func isFloat(a interface{}) bool { - kind := reflect.TypeOf(a).Kind() - return reflect.Float32 <= kind && kind <= reflect.Float64 -} - -func toInteger(a interface{}) int64 { - if isInteger(a) { - return reflect.ValueOf(a).Int() - } else if isUnsignedInteger(a) { - return int64(reflect.ValueOf(a).Uint()) - } else if isFloat(a) { - return int64(reflect.ValueOf(a).Float()) - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func toUnsignedInteger(a interface{}) uint64 { - if isInteger(a) { - return uint64(reflect.ValueOf(a).Int()) - } else if isUnsignedInteger(a) { - return reflect.ValueOf(a).Uint() - } else if isFloat(a) { - return uint64(reflect.ValueOf(a).Float()) - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func toFloat(a interface{}) float64 { - if isInteger(a) { - return float64(reflect.ValueOf(a).Int()) - } else if isUnsignedInteger(a) { - return float64(reflect.ValueOf(a).Uint()) - } else if isFloat(a) { - return reflect.ValueOf(a).Float() - } - panic(fmt.Sprintf("Expected a number! Got <%T> %#v", a, a)) -} - -func isError(a interface{}) bool { - _, ok := a.(error) - return ok -} - -func isChan(a interface{}) bool { - if isNil(a) { - return false - } - return reflect.TypeOf(a).Kind() == reflect.Chan -} - -func isMap(a interface{}) bool { - if a == nil { - return false - } - return reflect.TypeOf(a).Kind() == reflect.Map -} - -func isArrayOrSlice(a interface{}) bool { - if a == nil { - return false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Array, reflect.Slice: - return true - default: - return false - } -} - -func isString(a interface{}) bool { - if a == nil { - return false - } - return reflect.TypeOf(a).Kind() == reflect.String -} - -func toString(a interface{}) (string, bool) { - aString, isString := a.(string) - if isString { - return aString, true - } - - aBytes, isBytes := a.([]byte) - if isBytes { - return string(aBytes), true - } - - aStringer, isStringer := a.(fmt.Stringer) - if isStringer { - return aStringer.String(), true - } - - return "", false -} - -func lengthOf(a interface{}) (int, bool) { - if a == nil { - return 0, false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Map, reflect.Array, reflect.String, reflect.Chan, reflect.Slice: - return reflect.ValueOf(a).Len(), true - default: - return 0, false - } -} -func capOf(a interface{}) (int, bool) { - if a == nil { - return 0, false - } - switch reflect.TypeOf(a).Kind() { - case reflect.Array, reflect.Chan, reflect.Slice: - return reflect.ValueOf(a).Cap(), true - default: - return 0, false - } -} - -func isNil(a interface{}) bool { - if a == nil { - return true - } - - switch reflect.TypeOf(a).Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return reflect.ValueOf(a).IsNil() - } - - return false -} diff --git a/vendor/github.com/onsi/gomega/matchers/with_transform.go b/vendor/github.com/onsi/gomega/matchers/with_transform.go deleted file mode 100644 index 8e58d8a0fb..0000000000 --- a/vendor/github.com/onsi/gomega/matchers/with_transform.go +++ /dev/null @@ -1,72 +0,0 @@ -package matchers - -import ( - "fmt" - "reflect" - - "github.com/onsi/gomega/internal/oraclematcher" - "github.com/onsi/gomega/types" -) - -type WithTransformMatcher struct { - // input - Transform interface{} // must be a function of one parameter that returns one value - Matcher types.GomegaMatcher - - // cached value - transformArgType reflect.Type - - // state - transformedValue interface{} -} - -func NewWithTransformMatcher(transform interface{}, matcher types.GomegaMatcher) *WithTransformMatcher { - if transform == nil { - panic("transform function cannot be nil") - } - txType := reflect.TypeOf(transform) - if txType.NumIn() != 1 { - panic("transform function must have 1 argument") - } - if txType.NumOut() != 1 { - panic("transform function must have 1 return value") - } - - return &WithTransformMatcher{ - Transform: transform, - Matcher: matcher, - transformArgType: reflect.TypeOf(transform).In(0), - } -} - -func (m *WithTransformMatcher) Match(actual interface{}) (bool, error) { - // return error if actual's type is incompatible with Transform function's argument type - actualType := reflect.TypeOf(actual) - if !actualType.AssignableTo(m.transformArgType) { - return false, fmt.Errorf("Transform function expects '%s' but we have '%s'", m.transformArgType, actualType) - } - - // call the Transform function with `actual` - fn := reflect.ValueOf(m.Transform) - result := fn.Call([]reflect.Value{reflect.ValueOf(actual)}) - m.transformedValue = result[0].Interface() // expect exactly one value - - return m.Matcher.Match(m.transformedValue) -} - -func (m *WithTransformMatcher) FailureMessage(_ interface{}) (message string) { - return m.Matcher.FailureMessage(m.transformedValue) -} - -func (m *WithTransformMatcher) NegatedFailureMessage(_ interface{}) (message string) { - return m.Matcher.NegatedFailureMessage(m.transformedValue) -} - -func (m *WithTransformMatcher) MatchMayChangeInTheFuture(_ interface{}) bool { - // TODO: Maybe this should always just return true? (Only an issue for non-deterministic transformers.) - // - // Querying the next matcher is fine if the transformer always will return the same value. - // But if the transformer is non-deterministic and returns a different value each time, then there - // is no point in querying the next matcher, since it can only comment on the last transformed value. - return oraclematcher.MatchMayChangeInTheFuture(m.Matcher, m.transformedValue) -} diff --git a/vendor/github.com/onsi/gomega/types/types.go b/vendor/github.com/onsi/gomega/types/types.go deleted file mode 100644 index a83b40110c..0000000000 --- a/vendor/github.com/onsi/gomega/types/types.go +++ /dev/null @@ -1,17 +0,0 @@ -package types - -type GomegaFailHandler func(message string, callerSkip ...int) - -//A simple *testing.T interface wrapper -type GomegaTestingT interface { - Fatalf(format string, args ...interface{}) -} - -//All Gomega matchers must implement the GomegaMatcher interface -// -//For details on writing custom matchers, check out: http://onsi.github.io/gomega/#adding_your_own_matchers -type GomegaMatcher interface { - Match(actual interface{}) (success bool, err error) - FailureMessage(actual interface{}) (message string) - NegatedFailureMessage(actual interface{}) (message string) -} diff --git a/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md b/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md deleted file mode 100644 index e4d962ac16..0000000000 --- a/vendor/github.com/opencontainers/go-digest/CONTRIBUTING.md +++ /dev/null @@ -1,72 +0,0 @@ -# Contributing to Docker open source projects - -Want to hack on this project? Awesome! Here are instructions to get you started. - -This project is a part of the [Docker](https://www.docker.com) project, and follows -the same rules and principles. If you're already familiar with the way -Docker does things, you'll feel right at home. - -Otherwise, go read Docker's -[contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), -[issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), -[review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and -[branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). - -For an in-depth description of our contribution process, visit the -contributors guide: [Understand how to contribute](https://docs.docker.com/opensource/workflow/make-a-contribution/) - -### Sign your work - -The sign-off is a simple line at the end of the explanation for the patch. Your -signature certifies that you wrote the patch or otherwise have the right to pass -it on as an open-source patch. The rules are pretty simple: if you can certify -the below (from [developercertificate.org](http://developercertificate.org/)): - -``` -Developer Certificate of Origin -Version 1.1 - -Copyright (C) 2004, 2006 The Linux Foundation and its contributors. -1 Letterman Drive -Suite D4700 -San Francisco, CA, 94129 - -Everyone is permitted to copy and distribute verbatim copies of this -license document, but changing it is not allowed. - - -Developer's Certificate of Origin 1.1 - -By making a contribution to this project, I certify that: - -(a) The contribution was created in whole or in part by me and I - have the right to submit it under the open source license - indicated in the file; or - -(b) The contribution is based upon previous work that, to the best - of my knowledge, is covered under an appropriate open source - license and I have the right under that license to submit that - work with modifications, whether created in whole or in part - by me, under the same open source license (unless I am - permitted to submit under a different license), as indicated - in the file; or - -(c) The contribution was provided directly to me by some other - person who certified (a), (b) or (c) and I have not modified - it. - -(d) I understand and agree that this project and the contribution - are public and that a record of the contribution (including all - personal information I submit with it, including my sign-off) is - maintained indefinitely and may be redistributed consistent with - this project or the open source license(s) involved. -``` - -Then you just add a line to every git commit message: - - Signed-off-by: Joe Smith - -Use your real name (sorry, no pseudonyms or anonymous contributions.) - -If you set your `user.name` and `user.email` git configs, you can sign your -commit automatically with `git commit -s`. diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.code b/vendor/github.com/opencontainers/go-digest/LICENSE.code deleted file mode 100644 index 0ea3ff81e3..0000000000 --- a/vendor/github.com/opencontainers/go-digest/LICENSE.code +++ /dev/null @@ -1,191 +0,0 @@ - - Apache License - Version 2.0, January 2004 - https://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. - - END OF TERMS AND CONDITIONS - - Copyright 2016 Docker, Inc. - - 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 - - https://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. diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.docs b/vendor/github.com/opencontainers/go-digest/LICENSE.docs deleted file mode 100644 index e26cd4fc8e..0000000000 --- a/vendor/github.com/opencontainers/go-digest/LICENSE.docs +++ /dev/null @@ -1,425 +0,0 @@ -Attribution-ShareAlike 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution-ShareAlike 4.0 International Public -License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution-ShareAlike 4.0 International Public License ("Public -License"). To the extent this Public License may be interpreted as a -contract, You are granted the Licensed Rights in consideration of Your -acceptance of these terms and conditions, and the Licensor grants You -such rights in consideration of benefits the Licensor receives from -making the Licensed Material available under these terms and -conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. BY-SA Compatible License means a license listed at - creativecommons.org/compatiblelicenses, approved by Creative - Commons as essentially the equivalent of this Public License. - - d. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - e. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - f. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - g. License Elements means the license attributes listed in the name - of a Creative Commons Public License. The License Elements of this - Public License are Attribution and ShareAlike. - - h. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - i. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - j. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - k. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - l. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - m. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. Additional offer from the Licensor -- Adapted Material. - Every recipient of Adapted Material from You - automatically receives an offer from the Licensor to - exercise the Licensed Rights in the Adapted Material - under the conditions of the Adapter's License You apply. - - c. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - b. ShareAlike. - - In addition to the conditions in Section 3(a), if You Share - Adapted Material You produce, the following conditions also apply. - - 1. The Adapter's License You apply must be a Creative Commons - license with the same License Elements, this version or - later, or a BY-SA Compatible License. - - 2. You must include the text of, or the URI or hyperlink to, the - Adapter's License You apply. You may satisfy this condition - in any reasonable manner based on the medium, means, and - context in which You Share Adapted Material. - - 3. You may not offer or impose any additional or different terms - or conditions on, or apply any Effective Technological - Measures to, Adapted Material that restrict exercise of the - rights granted under the Adapter's License You apply. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material, - - including for purposes of Section 3(b); and - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public licenses. -Notwithstanding, Creative Commons may elect to apply one of its public -licenses to material it publishes and in those instances will be -considered the "Licensor." Except for the limited purpose of indicating -that material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the public -licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/opencontainers/go-digest/MAINTAINERS b/vendor/github.com/opencontainers/go-digest/MAINTAINERS deleted file mode 100644 index 42a29795d7..0000000000 --- a/vendor/github.com/opencontainers/go-digest/MAINTAINERS +++ /dev/null @@ -1,9 +0,0 @@ -Aaron Lehmann (@aaronlehmann) -Brandon Philips (@philips) -Brendan Burns (@brendandburns) -Derek McGowan (@dmcgowan) -Jason Bouzane (@jbouzane) -John Starks (@jstarks) -Jonathan Boulle (@jonboulle) -Stephen Day (@stevvooe) -Vincent Batts (@vbatts) diff --git a/vendor/github.com/opencontainers/go-digest/README.md b/vendor/github.com/opencontainers/go-digest/README.md deleted file mode 100644 index 0f5a04092c..0000000000 --- a/vendor/github.com/opencontainers/go-digest/README.md +++ /dev/null @@ -1,104 +0,0 @@ -# go-digest - -[![GoDoc](https://godoc.org/github.com/opencontainers/go-digest?status.svg)](https://godoc.org/github.com/opencontainers/go-digest) [![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/go-digest)](https://goreportcard.com/report/github.com/opencontainers/go-digest) [![Build Status](https://travis-ci.org/opencontainers/go-digest.svg?branch=master)](https://travis-ci.org/opencontainers/go-digest) - -Common digest package used across the container ecosystem. - -Please see the [godoc](https://godoc.org/github.com/opencontainers/go-digest) for more information. - -# What is a digest? - -A digest is just a hash. - -The most common use case for a digest is to create a content -identifier for use in [Content Addressable Storage](https://en.wikipedia.org/wiki/Content-addressable_storage) -systems: - -```go -id := digest.FromBytes([]byte("my content")) -``` - -In the example above, the id can be used to uniquely identify -the byte slice "my content". This allows two disparate applications -to agree on a verifiable identifier without having to trust one -another. - -An identifying digest can be verified, as follows: - -```go -if id != digest.FromBytes([]byte("my content")) { - return errors.New("the content has changed!") -} -``` - -A `Verifier` type can be used to handle cases where an `io.Reader` -makes more sense: - -```go -rd := getContent() -verifier := id.Verifier() -io.Copy(verifier, rd) - -if !verifier.Verified() { - return errors.New("the content has changed!") -} -``` - -Using [Merkle DAGs](https://en.wikipedia.org/wiki/Merkle_tree), this -can power a rich, safe, content distribution system. - -# Usage - -While the [godoc](https://godoc.org/github.com/opencontainers/go-digest) is -considered the best resource, a few important items need to be called -out when using this package. - -1. Make sure to import the hash implementations into your application - or the package will panic. You should have something like the - following in the main (or other entrypoint) of your application: - - ```go - import ( - _ "crypto/sha256" - _ "crypto/sha512" - ) - ``` - This may seem inconvenient but it allows you replace the hash - implementations with others, such as https://github.com/stevvooe/resumable. - -2. Even though `digest.Digest` may be assemable as a string, _always_ - verify your input with `digest.Parse` or use `Digest.Validate` - when accepting untrusted input. While there are measures to - avoid common problems, this will ensure you have valid digests - in the rest of your application. - -# Stability - -The Go API, at this stage, is considered stable, unless otherwise noted. - -As always, before using a package export, read the [godoc](https://godoc.org/github.com/opencontainers/go-digest). - -# Contributing - -This package is considered fairly complete. It has been in production -in thousands (millions?) of deployments and is fairly battle-hardened. -New additions will be met with skepticism. If you think there is a -missing feature, please file a bug clearly describing the problem and -the alternatives you tried before submitting a PR. - -# Reporting security issues - -Please DO NOT file a public issue, instead send your report privately to -security@opencontainers.org. - -The maintainers take security seriously. If you discover a security issue, -please bring it to their attention right away! - -If you are reporting a security issue, do not create an issue or file a pull -request on GitHub. Instead, disclose the issue responsibly by sending an email -to security@opencontainers.org (which is inhabited only by the maintainers of -the various OCI projects). - -# Copyright and license - -Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the [Apache 2.0 license](LICENSE.code). This `README.md` file and the [`CONTRIBUTING.md`](CONTRIBUTING.md) file are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file [`LICENSE.docs`](LICENSE.docs). You may obtain a duplicate copy of the same license, titled CC BY-SA 4.0, at http://creativecommons.org/licenses/by-sa/4.0/. diff --git a/vendor/github.com/opencontainers/go-digest/algorithm.go b/vendor/github.com/opencontainers/go-digest/algorithm.go deleted file mode 100644 index bdff42d929..0000000000 --- a/vendor/github.com/opencontainers/go-digest/algorithm.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2017 Docker, Inc. -// -// 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 -// -// https://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 digest - -import ( - "crypto" - "fmt" - "hash" - "io" -) - -// Algorithm identifies and implementation of a digester by an identifier. -// Note the that this defines both the hash algorithm used and the string -// encoding. -type Algorithm string - -// supported digest types -const ( - SHA256 Algorithm = "sha256" // sha256 with hex encoding - SHA384 Algorithm = "sha384" // sha384 with hex encoding - SHA512 Algorithm = "sha512" // sha512 with hex encoding - - // Canonical is the primary digest algorithm used with the distribution - // project. Other digests may be used but this one is the primary storage - // digest. - Canonical = SHA256 -) - -var ( - // TODO(stevvooe): Follow the pattern of the standard crypto package for - // registration of digests. Effectively, we are a registerable set and - // common symbol access. - - // algorithms maps values to hash.Hash implementations. Other algorithms - // may be available but they cannot be calculated by the digest package. - algorithms = map[Algorithm]crypto.Hash{ - SHA256: crypto.SHA256, - SHA384: crypto.SHA384, - SHA512: crypto.SHA512, - } -) - -// Available returns true if the digest type is available for use. If this -// returns false, Digester and Hash will return nil. -func (a Algorithm) Available() bool { - h, ok := algorithms[a] - if !ok { - return false - } - - // check availability of the hash, as well - return h.Available() -} - -func (a Algorithm) String() string { - return string(a) -} - -// Size returns number of bytes returned by the hash. -func (a Algorithm) Size() int { - h, ok := algorithms[a] - if !ok { - return 0 - } - return h.Size() -} - -// Set implemented to allow use of Algorithm as a command line flag. -func (a *Algorithm) Set(value string) error { - if value == "" { - *a = Canonical - } else { - // just do a type conversion, support is queried with Available. - *a = Algorithm(value) - } - - if !a.Available() { - return ErrDigestUnsupported - } - - return nil -} - -// Digester returns a new digester for the specified algorithm. If the algorithm -// does not have a digester implementation, nil will be returned. This can be -// checked by calling Available before calling Digester. -func (a Algorithm) Digester() Digester { - return &digester{ - alg: a, - hash: a.Hash(), - } -} - -// Hash returns a new hash as used by the algorithm. If not available, the -// method will panic. Check Algorithm.Available() before calling. -func (a Algorithm) Hash() hash.Hash { - if !a.Available() { - // Empty algorithm string is invalid - if a == "" { - panic(fmt.Sprintf("empty digest algorithm, validate before calling Algorithm.Hash()")) - } - - // NOTE(stevvooe): A missing hash is usually a programming error that - // must be resolved at compile time. We don't import in the digest - // package to allow users to choose their hash implementation (such as - // when using stevvooe/resumable or a hardware accelerated package). - // - // Applications that may want to resolve the hash at runtime should - // call Algorithm.Available before call Algorithm.Hash(). - panic(fmt.Sprintf("%v not available (make sure it is imported)", a)) - } - - return algorithms[a].New() -} - -// FromReader returns the digest of the reader using the algorithm. -func (a Algorithm) FromReader(rd io.Reader) (Digest, error) { - digester := a.Digester() - - if _, err := io.Copy(digester.Hash(), rd); err != nil { - return "", err - } - - return digester.Digest(), nil -} - -// FromBytes digests the input and returns a Digest. -func (a Algorithm) FromBytes(p []byte) Digest { - digester := a.Digester() - - if _, err := digester.Hash().Write(p); err != nil { - // Writes to a Hash should never fail. None of the existing - // hash implementations in the stdlib or hashes vendored - // here can return errors from Write. Having a panic in this - // condition instead of having FromBytes return an error value - // avoids unnecessary error handling paths in all callers. - panic("write to hash function returned error: " + err.Error()) - } - - return digester.Digest() -} - -// FromString digests the string input and returns a Digest. -func (a Algorithm) FromString(s string) Digest { - return a.FromBytes([]byte(s)) -} diff --git a/vendor/github.com/opencontainers/go-digest/digest.go b/vendor/github.com/opencontainers/go-digest/digest.go deleted file mode 100644 index 69e1d2b542..0000000000 --- a/vendor/github.com/opencontainers/go-digest/digest.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2017 Docker, Inc. -// -// 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 -// -// https://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 digest - -import ( - "fmt" - "hash" - "io" - "regexp" - "strings" -) - -// Digest allows simple protection of hex formatted digest strings, prefixed -// by their algorithm. Strings of type Digest have some guarantee of being in -// the correct format and it provides quick access to the components of a -// digest string. -// -// The following is an example of the contents of Digest types: -// -// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc -// -// This allows to abstract the digest behind this type and work only in those -// terms. -type Digest string - -// NewDigest returns a Digest from alg and a hash.Hash object. -func NewDigest(alg Algorithm, h hash.Hash) Digest { - return NewDigestFromBytes(alg, h.Sum(nil)) -} - -// NewDigestFromBytes returns a new digest from the byte contents of p. -// Typically, this can come from hash.Hash.Sum(...) or xxx.SumXXX(...) -// functions. This is also useful for rebuilding digests from binary -// serializations. -func NewDigestFromBytes(alg Algorithm, p []byte) Digest { - return Digest(fmt.Sprintf("%s:%x", alg, p)) -} - -// NewDigestFromHex returns a Digest from alg and a the hex encoded digest. -func NewDigestFromHex(alg, hex string) Digest { - return Digest(fmt.Sprintf("%s:%s", alg, hex)) -} - -// DigestRegexp matches valid digest types. -var DigestRegexp = regexp.MustCompile(`[a-zA-Z0-9-_+.]+:[a-fA-F0-9]+`) - -// DigestRegexpAnchored matches valid digest types, anchored to the start and end of the match. -var DigestRegexpAnchored = regexp.MustCompile(`^` + DigestRegexp.String() + `$`) - -var ( - // ErrDigestInvalidFormat returned when digest format invalid. - ErrDigestInvalidFormat = fmt.Errorf("invalid checksum digest format") - - // ErrDigestInvalidLength returned when digest has invalid length. - ErrDigestInvalidLength = fmt.Errorf("invalid checksum digest length") - - // ErrDigestUnsupported returned when the digest algorithm is unsupported. - ErrDigestUnsupported = fmt.Errorf("unsupported digest algorithm") -) - -// Parse parses s and returns the validated digest object. An error will -// be returned if the format is invalid. -func Parse(s string) (Digest, error) { - d := Digest(s) - return d, d.Validate() -} - -// FromReader consumes the content of rd until io.EOF, returning canonical digest. -func FromReader(rd io.Reader) (Digest, error) { - return Canonical.FromReader(rd) -} - -// FromBytes digests the input and returns a Digest. -func FromBytes(p []byte) Digest { - return Canonical.FromBytes(p) -} - -// FromString digests the input and returns a Digest. -func FromString(s string) Digest { - return Canonical.FromString(s) -} - -// Validate checks that the contents of d is a valid digest, returning an -// error if not. -func (d Digest) Validate() error { - s := string(d) - - i := strings.Index(s, ":") - - // validate i then run through regexp - if i < 0 || i+1 == len(s) || !DigestRegexpAnchored.MatchString(s) { - return ErrDigestInvalidFormat - } - - algorithm := Algorithm(s[:i]) - if !algorithm.Available() { - return ErrDigestUnsupported - } - - // Digests much always be hex-encoded, ensuring that their hex portion will - // always be size*2 - if algorithm.Size()*2 != len(s[i+1:]) { - return ErrDigestInvalidLength - } - - return nil -} - -// Algorithm returns the algorithm portion of the digest. This will panic if -// the underlying digest is not in a valid format. -func (d Digest) Algorithm() Algorithm { - return Algorithm(d[:d.sepIndex()]) -} - -// Verifier returns a writer object that can be used to verify a stream of -// content against the digest. If the digest is invalid, the method will panic. -func (d Digest) Verifier() Verifier { - return hashVerifier{ - hash: d.Algorithm().Hash(), - digest: d, - } -} - -// Hex returns the hex digest portion of the digest. This will panic if the -// underlying digest is not in a valid format. -func (d Digest) Hex() string { - return string(d[d.sepIndex()+1:]) -} - -func (d Digest) String() string { - return string(d) -} - -func (d Digest) sepIndex() int { - i := strings.Index(string(d), ":") - - if i < 0 { - panic(fmt.Sprintf("no ':' separator in digest %q", d)) - } - - return i -} diff --git a/vendor/github.com/opencontainers/go-digest/digester.go b/vendor/github.com/opencontainers/go-digest/digester.go deleted file mode 100644 index 36fa2728ef..0000000000 --- a/vendor/github.com/opencontainers/go-digest/digester.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017 Docker, Inc. -// -// 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 -// -// https://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 digest - -import "hash" - -// Digester calculates the digest of written data. Writes should go directly -// to the return value of Hash, while calling Digest will return the current -// value of the digest. -type Digester interface { - Hash() hash.Hash // provides direct access to underlying hash instance. - Digest() Digest -} - -// digester provides a simple digester definition that embeds a hasher. -type digester struct { - alg Algorithm - hash hash.Hash -} - -func (d *digester) Hash() hash.Hash { - return d.hash -} - -func (d *digester) Digest() Digest { - return NewDigest(d.alg, d.hash) -} diff --git a/vendor/github.com/opencontainers/go-digest/doc.go b/vendor/github.com/opencontainers/go-digest/doc.go deleted file mode 100644 index 491ea1ef1f..0000000000 --- a/vendor/github.com/opencontainers/go-digest/doc.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2017 Docker, Inc. -// -// 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 -// -// https://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 digest provides a generalized type to opaquely represent message -// digests and their operations within the registry. The Digest type is -// designed to serve as a flexible identifier in a content-addressable system. -// More importantly, it provides tools and wrappers to work with -// hash.Hash-based digests with little effort. -// -// Basics -// -// The format of a digest is simply a string with two parts, dubbed the -// "algorithm" and the "digest", separated by a colon: -// -// : -// -// An example of a sha256 digest representation follows: -// -// sha256:7173b809ca12ec5dee4506cd86be934c4596dd234ee82c0662eac04a8c2c71dc -// -// In this case, the string "sha256" is the algorithm and the hex bytes are -// the "digest". -// -// Because the Digest type is simply a string, once a valid Digest is -// obtained, comparisons are cheap, quick and simple to express with the -// standard equality operator. -// -// Verification -// -// The main benefit of using the Digest type is simple verification against a -// given digest. The Verifier interface, modeled after the stdlib hash.Hash -// interface, provides a common write sink for digest verification. After -// writing is complete, calling the Verifier.Verified method will indicate -// whether or not the stream of bytes matches the target digest. -// -// Missing Features -// -// In addition to the above, we intend to add the following features to this -// package: -// -// 1. A Digester type that supports write sink digest calculation. -// -// 2. Suspend and resume of ongoing digest calculations to support efficient digest verification in the registry. -// -package digest diff --git a/vendor/github.com/opencontainers/go-digest/verifiers.go b/vendor/github.com/opencontainers/go-digest/verifiers.go deleted file mode 100644 index 32125e9187..0000000000 --- a/vendor/github.com/opencontainers/go-digest/verifiers.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2017 Docker, Inc. -// -// 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 -// -// https://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 digest - -import ( - "hash" - "io" -) - -// Verifier presents a general verification interface to be used with message -// digests and other byte stream verifications. Users instantiate a Verifier -// from one of the various methods, write the data under test to it then check -// the result with the Verified method. -type Verifier interface { - io.Writer - - // Verified will return true if the content written to Verifier matches - // the digest. - Verified() bool -} - -type hashVerifier struct { - digest Digest - hash hash.Hash -} - -func (hv hashVerifier) Write(p []byte) (n int, err error) { - return hv.hash.Write(p) -} - -func (hv hashVerifier) Verified() bool { - return hv.digest == NewDigest(hv.digest.Algorithm(), hv.hash) -} diff --git a/vendor/github.com/pkg/errors/LICENSE b/vendor/github.com/pkg/errors/LICENSE deleted file mode 100644 index 835ba3e755..0000000000 --- a/vendor/github.com/pkg/errors/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2015, Dave Cheney -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md deleted file mode 100644 index 273db3c98a..0000000000 --- a/vendor/github.com/pkg/errors/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) - -Package errors provides simple error handling primitives. - -`go get github.com/pkg/errors` - -The traditional error handling idiom in Go is roughly akin to -```go -if err != nil { - return err -} -``` -which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. - -## Adding context to an error - -The errors.Wrap function returns a new error that adds context to the original error. For example -```go -_, err := ioutil.ReadAll(r) -if err != nil { - return errors.Wrap(err, "read failed") -} -``` -## Retrieving the cause of an error - -Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. -```go -type causer interface { - Cause() error -} -``` -`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: -```go -switch err := errors.Cause(err).(type) { -case *MyError: - // handle specifically -default: - // unknown error -} -``` - -[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). - -## Contributing - -We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. - -Before proposing a change, please discuss your change by raising an issue. - -## Licence - -BSD-2-Clause diff --git a/vendor/github.com/pkg/errors/appveyor.yml b/vendor/github.com/pkg/errors/appveyor.yml deleted file mode 100644 index a932eade02..0000000000 --- a/vendor/github.com/pkg/errors/appveyor.yml +++ /dev/null @@ -1,32 +0,0 @@ -version: build-{build}.{branch} - -clone_folder: C:\gopath\src\github.com\pkg\errors -shallow_clone: true # for startup speed - -environment: - GOPATH: C:\gopath - -platform: - - x64 - -# http://www.appveyor.com/docs/installed-software -install: - # some helpful output for debugging builds - - go version - - go env - # pre-installed MinGW at C:\MinGW is 32bit only - # but MSYS2 at C:\msys64 has mingw64 - - set PATH=C:\msys64\mingw64\bin;%PATH% - - gcc --version - - g++ --version - -build_script: - - go install -v ./... - -test_script: - - set PATH=C:\gopath\bin;%PATH% - - go test -v ./... - -#artifacts: -# - path: '%GOPATH%\bin\*.exe' -deploy: off diff --git a/vendor/github.com/pkg/errors/errors.go b/vendor/github.com/pkg/errors/errors.go deleted file mode 100644 index 842ee80456..0000000000 --- a/vendor/github.com/pkg/errors/errors.go +++ /dev/null @@ -1,269 +0,0 @@ -// Package errors provides simple error handling primitives. -// -// The traditional error handling idiom in Go is roughly akin to -// -// if err != nil { -// return err -// } -// -// which applied recursively up the call stack results in error reports -// without context or debugging information. The errors package allows -// programmers to add context to the failure path in their code in a way -// that does not destroy the original value of the error. -// -// Adding context to an error -// -// The errors.Wrap function returns a new error that adds context to the -// original error by recording a stack trace at the point Wrap is called, -// and the supplied message. For example -// -// _, err := ioutil.ReadAll(r) -// if err != nil { -// return errors.Wrap(err, "read failed") -// } -// -// If additional control is required the errors.WithStack and errors.WithMessage -// functions destructure errors.Wrap into its component operations of annotating -// an error with a stack trace and an a message, respectively. -// -// Retrieving the cause of an error -// -// Using errors.Wrap constructs a stack of errors, adding context to the -// preceding error. Depending on the nature of the error it may be necessary -// to reverse the operation of errors.Wrap to retrieve the original error -// for inspection. Any error value which implements this interface -// -// type causer interface { -// Cause() error -// } -// -// can be inspected by errors.Cause. errors.Cause will recursively retrieve -// the topmost error which does not implement causer, which is assumed to be -// the original cause. For example: -// -// switch err := errors.Cause(err).(type) { -// case *MyError: -// // handle specifically -// default: -// // unknown error -// } -// -// causer interface is not exported by this package, but is considered a part -// of stable public API. -// -// Formatted printing of errors -// -// All error values returned from this package implement fmt.Formatter and can -// be formatted by the fmt package. The following verbs are supported -// -// %s print the error. If the error has a Cause it will be -// printed recursively -// %v see %s -// %+v extended format. Each Frame of the error's StackTrace will -// be printed in detail. -// -// Retrieving the stack trace of an error or wrapper -// -// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are -// invoked. This information can be retrieved with the following interface. -// -// type stackTracer interface { -// StackTrace() errors.StackTrace -// } -// -// Where errors.StackTrace is defined as -// -// type StackTrace []Frame -// -// The Frame type represents a call site in the stack trace. Frame supports -// the fmt.Formatter interface that can be used for printing information about -// the stack trace of this error. For example: -// -// if err, ok := err.(stackTracer); ok { -// for _, f := range err.StackTrace() { -// fmt.Printf("%+s:%d", f) -// } -// } -// -// stackTracer interface is not exported by this package, but is considered a part -// of stable public API. -// -// See the documentation for Frame.Format for more details. -package errors - -import ( - "fmt" - "io" -) - -// New returns an error with the supplied message. -// New also records the stack trace at the point it was called. -func New(message string) error { - return &fundamental{ - msg: message, - stack: callers(), - } -} - -// Errorf formats according to a format specifier and returns the string -// as a value that satisfies error. -// Errorf also records the stack trace at the point it was called. -func Errorf(format string, args ...interface{}) error { - return &fundamental{ - msg: fmt.Sprintf(format, args...), - stack: callers(), - } -} - -// fundamental is an error that has a message and a stack, but no caller. -type fundamental struct { - msg string - *stack -} - -func (f *fundamental) Error() string { return f.msg } - -func (f *fundamental) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} - -// WithStack annotates err with a stack trace at the point WithStack was called. -// If err is nil, WithStack returns nil. -func WithStack(err error) error { - if err == nil { - return nil - } - return &withStack{ - err, - callers(), - } -} - -type withStack struct { - error - *stack -} - -func (w *withStack) Cause() error { return w.error } - -func (w *withStack) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v", w.Cause()) - w.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, w.Error()) - case 'q': - fmt.Fprintf(s, "%q", w.Error()) - } -} - -// Wrap returns an error annotating err with a stack trace -// at the point Wrap is called, and the supplied message. -// If err is nil, Wrap returns nil. -func Wrap(err error, message string) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: message, - } - return &withStack{ - err, - callers(), - } -} - -// Wrapf returns an error annotating err with a stack trace -// at the point Wrapf is call, and the format specifier. -// If err is nil, Wrapf returns nil. -func Wrapf(err error, format string, args ...interface{}) error { - if err == nil { - return nil - } - err = &withMessage{ - cause: err, - msg: fmt.Sprintf(format, args...), - } - return &withStack{ - err, - callers(), - } -} - -// WithMessage annotates err with a new message. -// If err is nil, WithMessage returns nil. -func WithMessage(err error, message string) error { - if err == nil { - return nil - } - return &withMessage{ - cause: err, - msg: message, - } -} - -type withMessage struct { - cause error - msg string -} - -func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() } -func (w *withMessage) Cause() error { return w.cause } - -func (w *withMessage) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - fmt.Fprintf(s, "%+v\n", w.Cause()) - io.WriteString(s, w.msg) - return - } - fallthrough - case 's', 'q': - io.WriteString(s, w.Error()) - } -} - -// Cause returns the underlying cause of the error, if possible. -// An error value has a cause if it implements the following -// interface: -// -// type causer interface { -// Cause() error -// } -// -// If the error does not implement Cause, the original error will -// be returned. If the error is nil, nil will be returned without further -// investigation. -func Cause(err error) error { - type causer interface { - Cause() error - } - - for err != nil { - cause, ok := err.(causer) - if !ok { - break - } - err = cause.Cause() - } - return err -} diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go deleted file mode 100644 index 6b1f2891a5..0000000000 --- a/vendor/github.com/pkg/errors/stack.go +++ /dev/null @@ -1,178 +0,0 @@ -package errors - -import ( - "fmt" - "io" - "path" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type Frame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f Frame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f Frame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f Frame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f Frame) Format(s fmt.State, verb rune) { - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// StackTrace is stack of Frames from innermost (newest) to outermost (oldest). -type StackTrace []Frame - -func (st StackTrace) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case s.Flag('+'): - for _, f := range st { - fmt.Fprintf(s, "\n%+v", f) - } - case s.Flag('#'): - fmt.Fprintf(s, "%#v", []Frame(st)) - default: - fmt.Fprintf(s, "%v", []Frame(st)) - } - case 's': - fmt.Fprintf(s, "%s", []Frame(st)) - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := Frame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func (s *stack) StackTrace() StackTrace { - f := make([]Frame, len(*s)) - for i := 0; i < len(f); i++ { - f[i] = Frame((*s)[i]) - } - return f -} - -func callers() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// funcname removes the path prefix component of a function's name reported by func.Name(). -func funcname(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] -} - -func trimGOPATH(name, file string) string { - // Here we want to get the source file path relative to the compile time - // GOPATH. As of Go 1.6.x there is no direct way to know the compiled - // GOPATH at runtime, but we can infer the number of path segments in the - // GOPATH. We note that fn.Name() returns the function name qualified by - // the import path, which does not include the GOPATH. Thus we can trim - // segments from the beginning of the file path until the number of path - // separators remaining is one more than the number of path separators in - // the function name. For example, given: - // - // GOPATH /home/user - // file /home/user/src/pkg/sub/file.go - // fn.Name() pkg/sub.Type.Method - // - // We want to produce: - // - // pkg/sub/file.go - // - // From this we can easily see that fn.Name() has one less path separator - // than our desired output. We count separators from the end of the file - // path until it finds two more than in the function name and then move - // one character forward to preserve the initial path segment without a - // leading separator. - const sep = "/" - goal := strings.Count(name, sep) + 2 - i := len(file) - for n := 0; n < goal; n++ { - i = strings.LastIndex(file[:i], sep) - if i == -1 { - // not enough separators found, set i so that the slice expression - // below leaves file unmodified - i = -len(sep) - break - } - } - // get back to 0 or trim the leading separator - file = file[i+len(sep):] - return file -} diff --git a/vendor/github.com/sanathkr/go-yaml/LICENSE b/vendor/github.com/sanathkr/go-yaml/LICENSE deleted file mode 100644 index 8dada3edaf..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. diff --git a/vendor/github.com/sanathkr/go-yaml/LICENSE.libyaml b/vendor/github.com/sanathkr/go-yaml/LICENSE.libyaml deleted file mode 100644 index 8da58fbf6f..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/LICENSE.libyaml +++ /dev/null @@ -1,31 +0,0 @@ -The following files were ported to Go from C files of libyaml, and thus -are still covered by their original copyright and license: - - apic.go - emitterc.go - parserc.go - readerc.go - scannerc.go - writerc.go - yamlh.go - yamlprivateh.go - -Copyright (c) 2006 Kirill Simonov - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/sanathkr/go-yaml/README.md b/vendor/github.com/sanathkr/go-yaml/README.md deleted file mode 100644 index 7a512d67c2..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/README.md +++ /dev/null @@ -1,133 +0,0 @@ -# YAML support for the Go language - -Introduction ------------- - -The yaml package enables Go programs to comfortably encode and decode YAML -values. It was developed within [Canonical](https://www.canonical.com) as -part of the [juju](https://juju.ubuntu.com) project, and is based on a -pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML) -C library to parse and generate YAML data quickly and reliably. - -Compatibility -------------- - -The yaml package supports most of YAML 1.1 and 1.2, including support for -anchors, tags, map merging, etc. Multi-document unmarshalling is not yet -implemented, and base-60 floats from YAML 1.1 are purposefully not -supported since they're a poor design and are gone in YAML 1.2. - -Installation and usage ----------------------- - -The import path for the package is *gopkg.in/yaml.v2*. - -To install it, run: - - go get gopkg.in/yaml.v2 - -API documentation ------------------ - -If opened in a browser, the import path itself leads to the API documentation: - - * [https://gopkg.in/yaml.v2](https://gopkg.in/yaml.v2) - -API stability -------------- - -The package API for yaml v2 will remain stable as described in [gopkg.in](https://gopkg.in). - - -License -------- - -The yaml package is licensed under the Apache License 2.0. Please see the LICENSE file for details. - - -Example -------- - -Some more examples can be found in the "examples" folder. - -```Go -package main - -import ( - "fmt" - "log" - - "gopkg.in/yaml.v2" -) - -var data = ` -a: Easy! -b: - c: 2 - d: [3, 4] -` - -type T struct { - A string - B struct { - RenamedC int `yaml:"c"` - D []int `yaml:",flow"` - } -} - -func main() { - t := T{} - - err := yaml.Unmarshal([]byte(data), &t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t:\n%v\n\n", t) - - d, err := yaml.Marshal(&t) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- t dump:\n%s\n\n", string(d)) - - m := make(map[interface{}]interface{}) - - err = yaml.Unmarshal([]byte(data), &m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m:\n%v\n\n", m) - - d, err = yaml.Marshal(&m) - if err != nil { - log.Fatalf("error: %v", err) - } - fmt.Printf("--- m dump:\n%s\n\n", string(d)) -} -``` - -This example will generate the following output: - -``` ---- t: -{Easy! {2 [3 4]}} - ---- t dump: -a: Easy! -b: - c: 2 - d: [3, 4] - - ---- m: -map[a:Easy! b:map[c:2 d:[3 4]]] - ---- m dump: -a: Easy! -b: - c: 2 - d: - - 3 - - 4 -``` - diff --git a/vendor/github.com/sanathkr/go-yaml/apic.go b/vendor/github.com/sanathkr/go-yaml/apic.go deleted file mode 100644 index 95ec014e8c..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/apic.go +++ /dev/null @@ -1,742 +0,0 @@ -package yaml - -import ( - "io" - "os" -) - -func yaml_insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { - //fmt.Println("yaml_insert_token", "pos:", pos, "typ:", token.typ, "head:", parser.tokens_head, "len:", len(parser.tokens)) - - // Check if we can move the queue at the beginning of the buffer. - if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { - if parser.tokens_head != len(parser.tokens) { - copy(parser.tokens, parser.tokens[parser.tokens_head:]) - } - parser.tokens = parser.tokens[:len(parser.tokens)-parser.tokens_head] - parser.tokens_head = 0 - } - parser.tokens = append(parser.tokens, *token) - if pos < 0 { - return - } - copy(parser.tokens[parser.tokens_head+pos+1:], parser.tokens[parser.tokens_head+pos:]) - parser.tokens[parser.tokens_head+pos] = *token -} - -// Create a new parser object. -func yaml_parser_initialize(parser *yaml_parser_t) bool { - *parser = yaml_parser_t{ - raw_buffer: make([]byte, 0, input_raw_buffer_size), - buffer: make([]byte, 0, input_buffer_size), - } - return true -} - -// Destroy a parser object. -func yaml_parser_delete(parser *yaml_parser_t) { - *parser = yaml_parser_t{} -} - -// String read handler. -func yaml_string_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - if parser.input_pos == len(parser.input) { - return 0, io.EOF - } - n = copy(buffer, parser.input[parser.input_pos:]) - parser.input_pos += n - return n, nil -} - -// File read handler. -func yaml_file_read_handler(parser *yaml_parser_t, buffer []byte) (n int, err error) { - return parser.input_file.Read(buffer) -} - -// Set a string input. -func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_string_read_handler - parser.input = input - parser.input_pos = 0 -} - -// Set a file input. -func yaml_parser_set_input_file(parser *yaml_parser_t, file *os.File) { - if parser.read_handler != nil { - panic("must set the input source only once") - } - parser.read_handler = yaml_file_read_handler - parser.input_file = file -} - -// Set the source encoding. -func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { - if parser.encoding != yaml_ANY_ENCODING { - panic("must set the encoding only once") - } - parser.encoding = encoding -} - -// Create a new emitter object. -func yaml_emitter_initialize(emitter *yaml_emitter_t) bool { - *emitter = yaml_emitter_t{ - buffer: make([]byte, output_buffer_size), - raw_buffer: make([]byte, 0, output_raw_buffer_size), - states: make([]yaml_emitter_state_t, 0, initial_stack_size), - events: make([]yaml_event_t, 0, initial_queue_size), - } - return true -} - -// Destroy an emitter object. -func yaml_emitter_delete(emitter *yaml_emitter_t) { - *emitter = yaml_emitter_t{} -} - -// String write handler. -func yaml_string_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - *emitter.output_buffer = append(*emitter.output_buffer, buffer...) - return nil -} - -// File write handler. -func yaml_file_write_handler(emitter *yaml_emitter_t, buffer []byte) error { - _, err := emitter.output_file.Write(buffer) - return err -} - -// Set a string output. -func yaml_emitter_set_output_string(emitter *yaml_emitter_t, output_buffer *[]byte) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_string_write_handler - emitter.output_buffer = output_buffer -} - -// Set a file output. -func yaml_emitter_set_output_file(emitter *yaml_emitter_t, file io.Writer) { - if emitter.write_handler != nil { - panic("must set the output target only once") - } - emitter.write_handler = yaml_file_write_handler - emitter.output_file = file -} - -// Set the output encoding. -func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { - if emitter.encoding != yaml_ANY_ENCODING { - panic("must set the output encoding only once") - } - emitter.encoding = encoding -} - -// Set the canonical output style. -func yaml_emitter_set_canonical(emitter *yaml_emitter_t, canonical bool) { - emitter.canonical = canonical -} - -//// Set the indentation increment. -func yaml_emitter_set_indent(emitter *yaml_emitter_t, indent int) { - if indent < 2 || indent > 9 { - indent = 2 - } - emitter.best_indent = indent -} - -// Set the preferred line width. -func yaml_emitter_set_width(emitter *yaml_emitter_t, width int) { - if width < 0 { - width = -1 - } - emitter.best_width = width -} - -// Set if unescaped non-ASCII characters are allowed. -func yaml_emitter_set_unicode(emitter *yaml_emitter_t, unicode bool) { - emitter.unicode = unicode -} - -// Set the preferred line break character. -func yaml_emitter_set_break(emitter *yaml_emitter_t, line_break yaml_break_t) { - emitter.line_break = line_break -} - -///* -// * Destroy a token object. -// */ -// -//YAML_DECLARE(void) -//yaml_token_delete(yaml_token_t *token) -//{ -// assert(token); // Non-NULL token object expected. -// -// switch (token.type) -// { -// case YAML_TAG_DIRECTIVE_TOKEN: -// yaml_free(token.data.tag_directive.handle); -// yaml_free(token.data.tag_directive.prefix); -// break; -// -// case YAML_ALIAS_TOKEN: -// yaml_free(token.data.alias.value); -// break; -// -// case YAML_ANCHOR_TOKEN: -// yaml_free(token.data.anchor.value); -// break; -// -// case YAML_TAG_TOKEN: -// yaml_free(token.data.tag.handle); -// yaml_free(token.data.tag.suffix); -// break; -// -// case YAML_SCALAR_TOKEN: -// yaml_free(token.data.scalar.value); -// break; -// -// default: -// break; -// } -// -// memset(token, 0, sizeof(yaml_token_t)); -//} -// -///* -// * Check if a string is a valid UTF-8 sequence. -// * -// * Check 'reader.c' for more details on UTF-8 encoding. -// */ -// -//static int -//yaml_check_utf8(yaml_char_t *start, size_t length) -//{ -// yaml_char_t *end = start+length; -// yaml_char_t *pointer = start; -// -// while (pointer < end) { -// unsigned char octet; -// unsigned int width; -// unsigned int value; -// size_t k; -// -// octet = pointer[0]; -// width = (octet & 0x80) == 0x00 ? 1 : -// (octet & 0xE0) == 0xC0 ? 2 : -// (octet & 0xF0) == 0xE0 ? 3 : -// (octet & 0xF8) == 0xF0 ? 4 : 0; -// value = (octet & 0x80) == 0x00 ? octet & 0x7F : -// (octet & 0xE0) == 0xC0 ? octet & 0x1F : -// (octet & 0xF0) == 0xE0 ? octet & 0x0F : -// (octet & 0xF8) == 0xF0 ? octet & 0x07 : 0; -// if (!width) return 0; -// if (pointer+width > end) return 0; -// for (k = 1; k < width; k ++) { -// octet = pointer[k]; -// if ((octet & 0xC0) != 0x80) return 0; -// value = (value << 6) + (octet & 0x3F); -// } -// if (!((width == 1) || -// (width == 2 && value >= 0x80) || -// (width == 3 && value >= 0x800) || -// (width == 4 && value >= 0x10000))) return 0; -// -// pointer += width; -// } -// -// return 1; -//} -// - -// Create STREAM-START. -func yaml_stream_start_event_initialize(event *yaml_event_t, encoding yaml_encoding_t) bool { - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - encoding: encoding, - } - return true -} - -// Create STREAM-END. -func yaml_stream_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - } - return true -} - -// Create DOCUMENT-START. -func yaml_document_start_event_initialize(event *yaml_event_t, version_directive *yaml_version_directive_t, - tag_directives []yaml_tag_directive_t, implicit bool) bool { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: implicit, - } - return true -} - -// Create DOCUMENT-END. -func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) bool { - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - implicit: implicit, - } - return true -} - -///* -// * Create ALIAS. -// */ -// -//YAML_DECLARE(int) -//yaml_alias_event_initialize(event *yaml_event_t, anchor *yaml_char_t) -//{ -// mark yaml_mark_t = { 0, 0, 0 } -// anchor_copy *yaml_char_t = NULL -// -// assert(event) // Non-NULL event object is expected. -// assert(anchor) // Non-NULL anchor is expected. -// -// if (!yaml_check_utf8(anchor, strlen((char *)anchor))) return 0 -// -// anchor_copy = yaml_strdup(anchor) -// if (!anchor_copy) -// return 0 -// -// ALIAS_EVENT_INIT(*event, anchor_copy, mark, mark) -// -// return 1 -//} - -// Create SCALAR. -func yaml_scalar_event_initialize(event *yaml_event_t, anchor, tag, value []byte, plain_implicit, quoted_implicit bool, style yaml_scalar_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - anchor: anchor, - tag: tag, - value: value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-START. -func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_sequence_style_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create SEQUENCE-END. -func yaml_sequence_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - } - return true -} - -// Create MAPPING-START. -func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor, tag []byte, implicit bool, style yaml_mapping_style_t) bool { - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(style), - } - return true -} - -// Create MAPPING-END. -func yaml_mapping_end_event_initialize(event *yaml_event_t) bool { - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - } - return true -} - -// Destroy an event object. -func yaml_event_delete(event *yaml_event_t) { - *event = yaml_event_t{} -} - -///* -// * Create a document object. -// */ -// -//YAML_DECLARE(int) -//yaml_document_initialize(document *yaml_document_t, -// version_directive *yaml_version_directive_t, -// tag_directives_start *yaml_tag_directive_t, -// tag_directives_end *yaml_tag_directive_t, -// start_implicit int, end_implicit int) -//{ -// struct { -// error yaml_error_type_t -// } context -// struct { -// start *yaml_node_t -// end *yaml_node_t -// top *yaml_node_t -// } nodes = { NULL, NULL, NULL } -// version_directive_copy *yaml_version_directive_t = NULL -// struct { -// start *yaml_tag_directive_t -// end *yaml_tag_directive_t -// top *yaml_tag_directive_t -// } tag_directives_copy = { NULL, NULL, NULL } -// value yaml_tag_directive_t = { NULL, NULL } -// mark yaml_mark_t = { 0, 0, 0 } -// -// assert(document) // Non-NULL document object is expected. -// assert((tag_directives_start && tag_directives_end) || -// (tag_directives_start == tag_directives_end)) -// // Valid tag directives are expected. -// -// if (!STACK_INIT(&context, nodes, INITIAL_STACK_SIZE)) goto error -// -// if (version_directive) { -// version_directive_copy = yaml_malloc(sizeof(yaml_version_directive_t)) -// if (!version_directive_copy) goto error -// version_directive_copy.major = version_directive.major -// version_directive_copy.minor = version_directive.minor -// } -// -// if (tag_directives_start != tag_directives_end) { -// tag_directive *yaml_tag_directive_t -// if (!STACK_INIT(&context, tag_directives_copy, INITIAL_STACK_SIZE)) -// goto error -// for (tag_directive = tag_directives_start -// tag_directive != tag_directives_end; tag_directive ++) { -// assert(tag_directive.handle) -// assert(tag_directive.prefix) -// if (!yaml_check_utf8(tag_directive.handle, -// strlen((char *)tag_directive.handle))) -// goto error -// if (!yaml_check_utf8(tag_directive.prefix, -// strlen((char *)tag_directive.prefix))) -// goto error -// value.handle = yaml_strdup(tag_directive.handle) -// value.prefix = yaml_strdup(tag_directive.prefix) -// if (!value.handle || !value.prefix) goto error -// if (!PUSH(&context, tag_directives_copy, value)) -// goto error -// value.handle = NULL -// value.prefix = NULL -// } -// } -// -// DOCUMENT_INIT(*document, nodes.start, nodes.end, version_directive_copy, -// tag_directives_copy.start, tag_directives_copy.top, -// start_implicit, end_implicit, mark, mark) -// -// return 1 -// -//error: -// STACK_DEL(&context, nodes) -// yaml_free(version_directive_copy) -// while (!STACK_EMPTY(&context, tag_directives_copy)) { -// value yaml_tag_directive_t = POP(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// } -// STACK_DEL(&context, tag_directives_copy) -// yaml_free(value.handle) -// yaml_free(value.prefix) -// -// return 0 -//} -// -///* -// * Destroy a document object. -// */ -// -//YAML_DECLARE(void) -//yaml_document_delete(document *yaml_document_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// tag_directive *yaml_tag_directive_t -// -// context.error = YAML_NO_ERROR // Eliminate a compliler warning. -// -// assert(document) // Non-NULL document object is expected. -// -// while (!STACK_EMPTY(&context, document.nodes)) { -// node yaml_node_t = POP(&context, document.nodes) -// yaml_free(node.tag) -// switch (node.type) { -// case YAML_SCALAR_NODE: -// yaml_free(node.data.scalar.value) -// break -// case YAML_SEQUENCE_NODE: -// STACK_DEL(&context, node.data.sequence.items) -// break -// case YAML_MAPPING_NODE: -// STACK_DEL(&context, node.data.mapping.pairs) -// break -// default: -// assert(0) // Should not happen. -// } -// } -// STACK_DEL(&context, document.nodes) -// -// yaml_free(document.version_directive) -// for (tag_directive = document.tag_directives.start -// tag_directive != document.tag_directives.end -// tag_directive++) { -// yaml_free(tag_directive.handle) -// yaml_free(tag_directive.prefix) -// } -// yaml_free(document.tag_directives.start) -// -// memset(document, 0, sizeof(yaml_document_t)) -//} -// -///** -// * Get a document node. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_node(document *yaml_document_t, index int) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (index > 0 && document.nodes.start + index <= document.nodes.top) { -// return document.nodes.start + index - 1 -// } -// return NULL -//} -// -///** -// * Get the root object. -// */ -// -//YAML_DECLARE(yaml_node_t *) -//yaml_document_get_root_node(document *yaml_document_t) -//{ -// assert(document) // Non-NULL document object is expected. -// -// if (document.nodes.top != document.nodes.start) { -// return document.nodes.start -// } -// return NULL -//} -// -///* -// * Add a scalar node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_scalar(document *yaml_document_t, -// tag *yaml_char_t, value *yaml_char_t, length int, -// style yaml_scalar_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// value_copy *yaml_char_t = NULL -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// assert(value) // Non-NULL value is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SCALAR_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (length < 0) { -// length = strlen((char *)value) -// } -// -// if (!yaml_check_utf8(value, length)) goto error -// value_copy = yaml_malloc(length+1) -// if (!value_copy) goto error -// memcpy(value_copy, value, length) -// value_copy[length] = '\0' -// -// SCALAR_NODE_INIT(node, tag_copy, value_copy, length, style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// yaml_free(tag_copy) -// yaml_free(value_copy) -// -// return 0 -//} -// -///* -// * Add a sequence node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_sequence(document *yaml_document_t, -// tag *yaml_char_t, style yaml_sequence_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_item_t -// end *yaml_node_item_t -// top *yaml_node_item_t -// } items = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_SEQUENCE_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, items, INITIAL_STACK_SIZE)) goto error -// -// SEQUENCE_NODE_INIT(node, tag_copy, items.start, items.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, items) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Add a mapping node to a document. -// */ -// -//YAML_DECLARE(int) -//yaml_document_add_mapping(document *yaml_document_t, -// tag *yaml_char_t, style yaml_mapping_style_t) -//{ -// struct { -// error yaml_error_type_t -// } context -// mark yaml_mark_t = { 0, 0, 0 } -// tag_copy *yaml_char_t = NULL -// struct { -// start *yaml_node_pair_t -// end *yaml_node_pair_t -// top *yaml_node_pair_t -// } pairs = { NULL, NULL, NULL } -// node yaml_node_t -// -// assert(document) // Non-NULL document object is expected. -// -// if (!tag) { -// tag = (yaml_char_t *)YAML_DEFAULT_MAPPING_TAG -// } -// -// if (!yaml_check_utf8(tag, strlen((char *)tag))) goto error -// tag_copy = yaml_strdup(tag) -// if (!tag_copy) goto error -// -// if (!STACK_INIT(&context, pairs, INITIAL_STACK_SIZE)) goto error -// -// MAPPING_NODE_INIT(node, tag_copy, pairs.start, pairs.end, -// style, mark, mark) -// if (!PUSH(&context, document.nodes, node)) goto error -// -// return document.nodes.top - document.nodes.start -// -//error: -// STACK_DEL(&context, pairs) -// yaml_free(tag_copy) -// -// return 0 -//} -// -///* -// * Append an item to a sequence node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_sequence_item(document *yaml_document_t, -// sequence int, item int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// assert(document) // Non-NULL document is required. -// assert(sequence > 0 -// && document.nodes.start + sequence <= document.nodes.top) -// // Valid sequence id is required. -// assert(document.nodes.start[sequence-1].type == YAML_SEQUENCE_NODE) -// // A sequence node is required. -// assert(item > 0 && document.nodes.start + item <= document.nodes.top) -// // Valid item id is required. -// -// if (!PUSH(&context, -// document.nodes.start[sequence-1].data.sequence.items, item)) -// return 0 -// -// return 1 -//} -// -///* -// * Append a pair of a key and a value to a mapping node. -// */ -// -//YAML_DECLARE(int) -//yaml_document_append_mapping_pair(document *yaml_document_t, -// mapping int, key int, value int) -//{ -// struct { -// error yaml_error_type_t -// } context -// -// pair yaml_node_pair_t -// -// assert(document) // Non-NULL document is required. -// assert(mapping > 0 -// && document.nodes.start + mapping <= document.nodes.top) -// // Valid mapping id is required. -// assert(document.nodes.start[mapping-1].type == YAML_MAPPING_NODE) -// // A mapping node is required. -// assert(key > 0 && document.nodes.start + key <= document.nodes.top) -// // Valid key id is required. -// assert(value > 0 && document.nodes.start + value <= document.nodes.top) -// // Valid value id is required. -// -// pair.key = key -// pair.value = value -// -// if (!PUSH(&context, -// document.nodes.start[mapping-1].data.mapping.pairs, pair)) -// return 0 -// -// return 1 -//} -// -// diff --git a/vendor/github.com/sanathkr/go-yaml/decode.go b/vendor/github.com/sanathkr/go-yaml/decode.go deleted file mode 100644 index c359328459..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/decode.go +++ /dev/null @@ -1,709 +0,0 @@ -package yaml - -import ( - "encoding" - "encoding/base64" - "fmt" - "math" - "reflect" - "strconv" - "time" -) - -const ( - documentNode = 1 << iota - mappingNode - sequenceNode - scalarNode - aliasNode -) - -type node struct { - kind int - line, column int - tag string - value string - implicit bool - children []*node - anchors map[string]*node -} - -// ---------------------------------------------------------------------------- -// Parser, produces a node tree out of a libyaml event stream. - -type parser struct { - parser yaml_parser_t - event yaml_event_t - doc *node -} - -func newParser(b []byte) *parser { - p := parser{} - if !yaml_parser_initialize(&p.parser) { - panic("failed to initialize YAML emitter") - } - - if len(b) == 0 { - b = []byte{'\n'} - } - - yaml_parser_set_input_string(&p.parser, b) - - p.skip() - if p.event.typ != yaml_STREAM_START_EVENT { - panic("expected stream start event, got " + strconv.Itoa(int(p.event.typ))) - } - p.skip() - return &p -} - -func (p *parser) destroy() { - if p.event.typ != yaml_NO_EVENT { - yaml_event_delete(&p.event) - } - yaml_parser_delete(&p.parser) -} - -func (p *parser) skip() { - if p.event.typ != yaml_NO_EVENT { - if p.event.typ == yaml_STREAM_END_EVENT { - failf("attempted to go past the end of stream; corrupted value?") - } - yaml_event_delete(&p.event) - } - if !yaml_parser_parse(&p.parser, &p.event) { - p.fail() - } -} - -func (p *parser) fail() { - var where string - var line int - if p.parser.problem_mark.line != 0 { - line = p.parser.problem_mark.line - } else if p.parser.context_mark.line != 0 { - line = p.parser.context_mark.line - } - if line != 0 { - where = "line " + strconv.Itoa(line) + ": " - } - var msg string - if len(p.parser.problem) > 0 { - msg = p.parser.problem - } else { - msg = "unknown problem parsing YAML content" - } - failf("%s%s", where, msg) -} - -func (p *parser) anchor(n *node, anchor []byte) { - if anchor != nil { - p.doc.anchors[string(anchor)] = n - } -} - -func (p *parser) parse() *node { - switch p.event.typ { - case yaml_SCALAR_EVENT: - return p.scalar() - case yaml_ALIAS_EVENT: - return p.alias() - case yaml_MAPPING_START_EVENT: - return p.mapping() - case yaml_SEQUENCE_START_EVENT: - return p.sequence() - case yaml_DOCUMENT_START_EVENT: - return p.document() - case yaml_STREAM_END_EVENT: - // Happens when attempting to decode an empty buffer. - return nil - default: - panic("attempted to parse unknown event: " + strconv.Itoa(int(p.event.typ))) - } -} - -func (p *parser) node(kind int) *node { - return &node{ - kind: kind, - line: p.event.start_mark.line, - column: p.event.start_mark.column, - } -} - -func (p *parser) document() *node { - n := p.node(documentNode) - n.anchors = make(map[string]*node) - p.doc = n - p.skip() - n.children = append(n.children, p.parse()) - if p.event.typ != yaml_DOCUMENT_END_EVENT { - panic("expected end of document event but got " + strconv.Itoa(int(p.event.typ))) - } - p.skip() - return n -} - -func (p *parser) alias() *node { - n := p.node(aliasNode) - n.value = string(p.event.anchor) - p.skip() - return n -} - -func (p *parser) scalar() *node { - n := p.node(scalarNode) - n.value = string(p.event.value) - n.tag = string(p.event.tag) - n.implicit = p.event.implicit - p.anchor(n, p.event.anchor) - p.skip() - return n -} - -func (p *parser) sequence() *node { - n := p.node(sequenceNode) - n.tag = string(p.event.tag) - p.anchor(n, p.event.anchor) - p.skip() - for p.event.typ != yaml_SEQUENCE_END_EVENT { - n.children = append(n.children, p.parse()) - } - p.skip() - return n -} - -func (p *parser) mapping() *node { - n := p.node(mappingNode) - n.tag = string(p.event.tag) - p.anchor(n, p.event.anchor) - p.skip() - for p.event.typ != yaml_MAPPING_END_EVENT { - n.children = append(n.children, p.parse(), p.parse()) - } - p.skip() - return n -} - -// ---------------------------------------------------------------------------- -// Decoder, unmarshals a node into a provided value. - -type decoder struct { - doc *node - aliases map[string]bool - mapType reflect.Type - terrors []string - strict bool -} - -var ( - mapItemType = reflect.TypeOf(MapItem{}) - durationType = reflect.TypeOf(time.Duration(0)) - defaultMapType = reflect.TypeOf(map[interface{}]interface{}{}) - ifaceType = defaultMapType.Elem() - tagUnmarshalers = map[string]TagUnmarshaler{} -) - -func newDecoder(strict bool) *decoder { - d := &decoder{mapType: defaultMapType, strict: strict} - d.aliases = make(map[string]bool) - return d -} - -func registerCustomTagUnmarshaler(tag string, unmarshaler TagUnmarshaler) { - tagUnmarshalers[tag] = unmarshaler -} - -func unregisterCustomTagUnmarshaler(tag string) { - if _, ok := tagUnmarshalers[tag]; ok { - delete(tagUnmarshalers, tag) - } -} - -func (d *decoder) terror(n *node, tag string, out reflect.Value) { - if n.tag != "" { - tag = n.tag - } - value := n.value - if tag != yaml_SEQ_TAG && tag != yaml_MAP_TAG { - if len(value) > 10 { - value = " `" + value[:7] + "...`" - } else { - value = " `" + value + "`" - } - } - d.terrors = append(d.terrors, fmt.Sprintf("line %d: cannot unmarshal %s%s into %s", n.line+1, shortTag(tag), value, out.Type())) -} - -func (d *decoder) callUnmarshaler(n *node, u Unmarshaler) (good bool) { - terrlen := len(d.terrors) - err := u.UnmarshalYAML(func(v interface{}) (err error) { - defer handleErr(&err) - d.unmarshal(n, reflect.ValueOf(v)) - if len(d.terrors) > terrlen { - issues := d.terrors[terrlen:] - d.terrors = d.terrors[:terrlen] - return &TypeError{issues} - } - return nil - }) - if e, ok := err.(*TypeError); ok { - d.terrors = append(d.terrors, e.Errors...) - return false - } - if err != nil { - fail(err) - } - return true -} - -// d.prepare initializes and dereferences pointers and calls UnmarshalYAML -// if a value is found to implement it. -// It returns the initialized and dereferenced out value, whether -// unmarshalling was already done by UnmarshalYAML, and if so whether -// its types unmarshalled appropriately. -// -// If n holds a null value, prepare returns before doing anything. -func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unmarshaled, good bool) { - if n.tag == yaml_NULL_TAG || n.kind == scalarNode && n.tag == "" && (n.value == "null" || n.value == "" && n.implicit) { - return out, false, false - } - again := true - for again { - again = false - if out.Kind() == reflect.Ptr { - if out.IsNil() { - out.Set(reflect.New(out.Type().Elem())) - } - out = out.Elem() - again = true - } - if out.CanAddr() { - if u, ok := out.Addr().Interface().(Unmarshaler); ok { - good = d.callUnmarshaler(n, u) - return out, true, good - } - } - } - return out, false, false -} - -func (d *decoder) unmarshal(n *node, out reflect.Value) (good bool) { - switch n.kind { - case documentNode: - return d.document(n, out) - case aliasNode: - return d.alias(n, out) - } - out, unmarshaled, good := d.prepare(n, out) - if unmarshaled { - return good - } - switch n.kind { - case scalarNode: - good = d.scalar(n, out) - case mappingNode: - good = d.mapping(n, out) - case sequenceNode: - good = d.sequence(n, out) - default: - panic("internal error: unknown node kind: " + strconv.Itoa(n.kind)) - } - - // If the node has a tag, and a custom tag unmarshaler is registered, - // then call it to unmarshal rest of the tree - if good && len(n.tag) > 0 { - if unmarshaller, found := tagUnmarshalers[n.tag]; found { - tagSuffix := n.tag[1:] // Remove starting ! from tag - newOutput := unmarshaller.UnmarshalYAMLTag(tagSuffix, out) - out.Set(newOutput) - } - } - - return good -} - -func (d *decoder) document(n *node, out reflect.Value) (good bool) { - if len(n.children) == 1 { - d.doc = n - d.unmarshal(n.children[0], out) - return true - } - return false -} - -func (d *decoder) alias(n *node, out reflect.Value) (good bool) { - an, ok := d.doc.anchors[n.value] - if !ok { - failf("unknown anchor '%s' referenced", n.value) - } - if d.aliases[n.value] { - failf("anchor '%s' value contains itself", n.value) - } - d.aliases[n.value] = true - good = d.unmarshal(an, out) - delete(d.aliases, n.value) - return good -} - -var zeroValue reflect.Value - -func resetMap(out reflect.Value) { - for _, k := range out.MapKeys() { - out.SetMapIndex(k, zeroValue) - } -} - -func (d *decoder) scalar(n *node, out reflect.Value) (good bool) { - var tag string - var resolved interface{} - if n.tag == "" && !n.implicit { - tag = yaml_STR_TAG - resolved = n.value - } else { - tag, resolved = resolve(n.tag, n.value) - if tag == yaml_BINARY_TAG { - data, err := base64.StdEncoding.DecodeString(resolved.(string)) - if err != nil { - failf("!!binary value contains invalid base64 data") - } - resolved = string(data) - } - } - if resolved == nil { - if out.Kind() == reflect.Map && !out.CanAddr() { - resetMap(out) - } else { - out.Set(reflect.Zero(out.Type())) - } - return true - } - if s, ok := resolved.(string); ok && out.CanAddr() { - if u, ok := out.Addr().Interface().(encoding.TextUnmarshaler); ok { - err := u.UnmarshalText([]byte(s)) - if err != nil { - fail(err) - } - return true - } - } - switch out.Kind() { - case reflect.String: - if tag == yaml_BINARY_TAG { - out.SetString(resolved.(string)) - good = true - } else if resolved != nil { - out.SetString(n.value) - good = true - } - case reflect.Interface: - if resolved == nil { - out.Set(reflect.Zero(out.Type())) - } else { - out.Set(reflect.ValueOf(resolved)) - } - good = true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch resolved := resolved.(type) { - case int: - if !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - good = true - } - case int64: - if !out.OverflowInt(resolved) { - out.SetInt(resolved) - good = true - } - case uint64: - if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - good = true - } - case float64: - if resolved <= math.MaxInt64 && !out.OverflowInt(int64(resolved)) { - out.SetInt(int64(resolved)) - good = true - } - case string: - if out.Type() == durationType { - d, err := time.ParseDuration(resolved) - if err == nil { - out.SetInt(int64(d)) - good = true - } - } - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch resolved := resolved.(type) { - case int: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - good = true - } - case int64: - if resolved >= 0 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - good = true - } - case uint64: - if !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - good = true - } - case float64: - if resolved <= math.MaxUint64 && !out.OverflowUint(uint64(resolved)) { - out.SetUint(uint64(resolved)) - good = true - } - } - case reflect.Bool: - switch resolved := resolved.(type) { - case bool: - out.SetBool(resolved) - good = true - } - case reflect.Float32, reflect.Float64: - switch resolved := resolved.(type) { - case int: - out.SetFloat(float64(resolved)) - good = true - case int64: - out.SetFloat(float64(resolved)) - good = true - case uint64: - out.SetFloat(float64(resolved)) - good = true - case float64: - out.SetFloat(resolved) - good = true - } - case reflect.Ptr: - if out.Type().Elem() == reflect.TypeOf(resolved) { - // TODO DOes this make sense? When is out a Ptr except when decoding a nil value? - elem := reflect.New(out.Type().Elem()) - elem.Elem().Set(reflect.ValueOf(resolved)) - out.Set(elem) - good = true - } - } - if !good { - d.terror(n, tag, out) - } - return good -} - -func settableValueOf(i interface{}) reflect.Value { - v := reflect.ValueOf(i) - sv := reflect.New(v.Type()).Elem() - sv.Set(v) - return sv -} - -func (d *decoder) sequence(n *node, out reflect.Value) (good bool) { - l := len(n.children) - - var iface reflect.Value - switch out.Kind() { - case reflect.Slice: - out.Set(reflect.MakeSlice(out.Type(), l, l)) - case reflect.Interface: - // No type hints. Will have to use a generic sequence. - iface = out - out = settableValueOf(make([]interface{}, l)) - default: - d.terror(n, yaml_SEQ_TAG, out) - return false - } - et := out.Type().Elem() - - j := 0 - for i := 0; i < l; i++ { - e := reflect.New(et).Elem() - if ok := d.unmarshal(n.children[i], e); ok { - out.Index(j).Set(e) - j++ - } - } - out.Set(out.Slice(0, j)) - if iface.IsValid() { - iface.Set(out) - } - return true -} - -func (d *decoder) mapping(n *node, out reflect.Value) (good bool) { - switch out.Kind() { - case reflect.Struct: - return d.mappingStruct(n, out) - case reflect.Slice: - return d.mappingSlice(n, out) - case reflect.Map: - // okay - case reflect.Interface: - if d.mapType.Kind() == reflect.Map { - iface := out - out = reflect.MakeMap(d.mapType) - iface.Set(out) - } else { - slicev := reflect.New(d.mapType).Elem() - if !d.mappingSlice(n, slicev) { - return false - } - out.Set(slicev) - return true - } - default: - d.terror(n, yaml_MAP_TAG, out) - return false - } - outt := out.Type() - kt := outt.Key() - et := outt.Elem() - - mapType := d.mapType - if outt.Key() == ifaceType && outt.Elem() == ifaceType { - d.mapType = outt - } - - if out.IsNil() { - out.Set(reflect.MakeMap(outt)) - } - l := len(n.children) - for i := 0; i < l; i += 2 { - if isMerge(n.children[i]) { - d.merge(n.children[i+1], out) - continue - } - k := reflect.New(kt).Elem() - if d.unmarshal(n.children[i], k) { - kkind := k.Kind() - if kkind == reflect.Interface { - kkind = k.Elem().Kind() - } - if kkind == reflect.Map || kkind == reflect.Slice { - failf("invalid map key: %#v", k.Interface()) - } - e := reflect.New(et).Elem() - if d.unmarshal(n.children[i+1], e) { - out.SetMapIndex(k, e) - } - } - } - d.mapType = mapType - return true -} - -func (d *decoder) mappingSlice(n *node, out reflect.Value) (good bool) { - outt := out.Type() - if outt.Elem() != mapItemType { - d.terror(n, yaml_MAP_TAG, out) - return false - } - - mapType := d.mapType - d.mapType = outt - - var slice []MapItem - var l = len(n.children) - for i := 0; i < l; i += 2 { - if isMerge(n.children[i]) { - d.merge(n.children[i+1], out) - continue - } - item := MapItem{} - k := reflect.ValueOf(&item.Key).Elem() - if d.unmarshal(n.children[i], k) { - v := reflect.ValueOf(&item.Value).Elem() - if d.unmarshal(n.children[i+1], v) { - slice = append(slice, item) - } - } - } - out.Set(reflect.ValueOf(slice)) - d.mapType = mapType - return true -} - -func (d *decoder) mappingStruct(n *node, out reflect.Value) (good bool) { - sinfo, err := getStructInfo(out.Type()) - if err != nil { - panic(err) - } - name := settableValueOf("") - l := len(n.children) - - var inlineMap reflect.Value - var elemType reflect.Type - if sinfo.InlineMap != -1 { - inlineMap = out.Field(sinfo.InlineMap) - inlineMap.Set(reflect.New(inlineMap.Type()).Elem()) - elemType = inlineMap.Type().Elem() - } - - for i := 0; i < l; i += 2 { - ni := n.children[i] - if isMerge(ni) { - d.merge(n.children[i+1], out) - continue - } - if !d.unmarshal(ni, name) { - continue - } - if info, ok := sinfo.FieldsMap[name.String()]; ok { - var field reflect.Value - if info.Inline == nil { - field = out.Field(info.Num) - } else { - field = out.FieldByIndex(info.Inline) - } - d.unmarshal(n.children[i+1], field) - } else if sinfo.InlineMap != -1 { - if inlineMap.IsNil() { - inlineMap.Set(reflect.MakeMap(inlineMap.Type())) - } - value := reflect.New(elemType).Elem() - d.unmarshal(n.children[i+1], value) - inlineMap.SetMapIndex(name, value) - } else if d.strict { - d.terrors = append(d.terrors, fmt.Sprintf("line %d: field %s not found in struct %s", n.line+1, name.String(), out.Type())) - } - } - return true -} - -func failWantMap() { - failf("map merge requires map or sequence of maps as the value") -} - -func (d *decoder) merge(n *node, out reflect.Value) { - switch n.kind { - case mappingNode: - d.unmarshal(n, out) - case aliasNode: - an, ok := d.doc.anchors[n.value] - if ok && an.kind != mappingNode { - failWantMap() - } - d.unmarshal(n, out) - case sequenceNode: - // Step backwards as earlier nodes take precedence. - for i := len(n.children) - 1; i >= 0; i-- { - ni := n.children[i] - if ni.kind == aliasNode { - an, ok := d.doc.anchors[ni.value] - if ok && an.kind != mappingNode { - failWantMap() - } - } else if ni.kind != mappingNode { - failWantMap() - } - d.unmarshal(ni, out) - } - default: - failWantMap() - } -} - -func isMerge(n *node) bool { - return n.kind == scalarNode && n.value == "<<" && (n.implicit == true || n.tag == yaml_MERGE_TAG) -} diff --git a/vendor/github.com/sanathkr/go-yaml/emitterc.go b/vendor/github.com/sanathkr/go-yaml/emitterc.go deleted file mode 100644 index 41de8b856c..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/emitterc.go +++ /dev/null @@ -1,1684 +0,0 @@ -package yaml - -import ( - "bytes" -) - -// Flush the buffer if needed. -func flush(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) { - return yaml_emitter_flush(emitter) - } - return true -} - -// Put a character to the output buffer. -func put(emitter *yaml_emitter_t, value byte) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - emitter.buffer[emitter.buffer_pos] = value - emitter.buffer_pos++ - emitter.column++ - return true -} - -// Put a line break to the output buffer. -func put_break(emitter *yaml_emitter_t) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - switch emitter.line_break { - case yaml_CR_BREAK: - emitter.buffer[emitter.buffer_pos] = '\r' - emitter.buffer_pos += 1 - case yaml_LN_BREAK: - emitter.buffer[emitter.buffer_pos] = '\n' - emitter.buffer_pos += 1 - case yaml_CRLN_BREAK: - emitter.buffer[emitter.buffer_pos+0] = '\r' - emitter.buffer[emitter.buffer_pos+1] = '\n' - emitter.buffer_pos += 2 - default: - panic("unknown line break setting") - } - emitter.column = 0 - emitter.line++ - return true -} - -// Copy a character from a string into buffer. -func write(emitter *yaml_emitter_t, s []byte, i *int) bool { - if emitter.buffer_pos+5 >= len(emitter.buffer) && !yaml_emitter_flush(emitter) { - return false - } - p := emitter.buffer_pos - w := width(s[*i]) - switch w { - case 4: - emitter.buffer[p+3] = s[*i+3] - fallthrough - case 3: - emitter.buffer[p+2] = s[*i+2] - fallthrough - case 2: - emitter.buffer[p+1] = s[*i+1] - fallthrough - case 1: - emitter.buffer[p+0] = s[*i+0] - default: - panic("unknown character width") - } - emitter.column++ - emitter.buffer_pos += w - *i += w - return true -} - -// Write a whole string into buffer. -func write_all(emitter *yaml_emitter_t, s []byte) bool { - for i := 0; i < len(s); { - if !write(emitter, s, &i) { - return false - } - } - return true -} - -// Copy a line break character from a string into buffer. -func write_break(emitter *yaml_emitter_t, s []byte, i *int) bool { - if s[*i] == '\n' { - if !put_break(emitter) { - return false - } - *i++ - } else { - if !write(emitter, s, i) { - return false - } - emitter.column = 0 - emitter.line++ - } - return true -} - -// Set an emitter error and return false. -func yaml_emitter_set_emitter_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_EMITTER_ERROR - emitter.problem = problem - return false -} - -// Emit an event. -func yaml_emitter_emit(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.events = append(emitter.events, *event) - for !yaml_emitter_need_more_events(emitter) { - event := &emitter.events[emitter.events_head] - if !yaml_emitter_analyze_event(emitter, event) { - return false - } - if !yaml_emitter_state_machine(emitter, event) { - return false - } - yaml_event_delete(event) - emitter.events_head++ - } - return true -} - -// Check if we need to accumulate more events before emitting. -// -// We accumulate extra -// - 1 event for DOCUMENT-START -// - 2 events for SEQUENCE-START -// - 3 events for MAPPING-START -// -func yaml_emitter_need_more_events(emitter *yaml_emitter_t) bool { - if emitter.events_head == len(emitter.events) { - return true - } - var accumulate int - switch emitter.events[emitter.events_head].typ { - case yaml_DOCUMENT_START_EVENT: - accumulate = 1 - break - case yaml_SEQUENCE_START_EVENT: - accumulate = 2 - break - case yaml_MAPPING_START_EVENT: - accumulate = 3 - break - default: - return false - } - if len(emitter.events)-emitter.events_head > accumulate { - return false - } - var level int - for i := emitter.events_head; i < len(emitter.events); i++ { - switch emitter.events[i].typ { - case yaml_STREAM_START_EVENT, yaml_DOCUMENT_START_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT: - level++ - case yaml_STREAM_END_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_END_EVENT, yaml_MAPPING_END_EVENT: - level-- - } - if level == 0 { - return false - } - } - return true -} - -// Append a directive to the directives stack. -func yaml_emitter_append_tag_directive(emitter *yaml_emitter_t, value *yaml_tag_directive_t, allow_duplicates bool) bool { - for i := 0; i < len(emitter.tag_directives); i++ { - if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_emitter_set_emitter_error(emitter, "duplicate %TAG directive") - } - } - - // [Go] Do we actually need to copy this given garbage collection - // and the lack of deallocating destructors? - tag_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(tag_copy.handle, value.handle) - copy(tag_copy.prefix, value.prefix) - emitter.tag_directives = append(emitter.tag_directives, tag_copy) - return true -} - -// Increase the indentation level. -func yaml_emitter_increase_indent(emitter *yaml_emitter_t, flow, indentless bool) bool { - emitter.indents = append(emitter.indents, emitter.indent) - if emitter.indent < 0 { - if flow { - emitter.indent = emitter.best_indent - } else { - emitter.indent = 0 - } - } else if !indentless { - emitter.indent += emitter.best_indent - } - return true -} - -// State dispatcher. -func yaml_emitter_state_machine(emitter *yaml_emitter_t, event *yaml_event_t) bool { - switch emitter.state { - default: - case yaml_EMIT_STREAM_START_STATE: - return yaml_emitter_emit_stream_start(emitter, event) - - case yaml_EMIT_FIRST_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, true) - - case yaml_EMIT_DOCUMENT_START_STATE: - return yaml_emitter_emit_document_start(emitter, event, false) - - case yaml_EMIT_DOCUMENT_CONTENT_STATE: - return yaml_emitter_emit_document_content(emitter, event) - - case yaml_EMIT_DOCUMENT_END_STATE: - return yaml_emitter_emit_document_end(emitter, event) - - case yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, true) - - case yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_flow_sequence_item(emitter, event, false) - - case yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_KEY_STATE: - return yaml_emitter_emit_flow_mapping_key(emitter, event, false) - - case yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, true) - - case yaml_EMIT_FLOW_MAPPING_VALUE_STATE: - return yaml_emitter_emit_flow_mapping_value(emitter, event, false) - - case yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, true) - - case yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE: - return yaml_emitter_emit_block_sequence_item(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_KEY_STATE: - return yaml_emitter_emit_block_mapping_key(emitter, event, false) - - case yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, true) - - case yaml_EMIT_BLOCK_MAPPING_VALUE_STATE: - return yaml_emitter_emit_block_mapping_value(emitter, event, false) - - case yaml_EMIT_END_STATE: - return yaml_emitter_set_emitter_error(emitter, "expected nothing after STREAM-END") - } - panic("invalid emitter state") -} - -// Expect STREAM-START. -func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_STREAM_START_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected STREAM-START") - } - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = event.encoding - if emitter.encoding == yaml_ANY_ENCODING { - emitter.encoding = yaml_UTF8_ENCODING - } - } - if emitter.best_indent < 2 || emitter.best_indent > 9 { - emitter.best_indent = 2 - } - if emitter.best_width >= 0 && emitter.best_width <= emitter.best_indent*2 { - emitter.best_width = 80 - } - if emitter.best_width < 0 { - emitter.best_width = 1<<31 - 1 - } - if emitter.line_break == yaml_ANY_BREAK { - emitter.line_break = yaml_LN_BREAK - } - - emitter.indent = -1 - emitter.line = 0 - emitter.column = 0 - emitter.whitespace = true - emitter.indention = true - - if emitter.encoding != yaml_UTF8_ENCODING { - if !yaml_emitter_write_bom(emitter) { - return false - } - } - emitter.state = yaml_EMIT_FIRST_DOCUMENT_START_STATE - return true -} - -// Expect DOCUMENT-START or STREAM-END. -func yaml_emitter_emit_document_start(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - - if event.typ == yaml_DOCUMENT_START_EVENT { - - if event.version_directive != nil { - if !yaml_emitter_analyze_version_directive(emitter, event.version_directive) { - return false - } - } - - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_analyze_tag_directive(emitter, tag_directive) { - return false - } - if !yaml_emitter_append_tag_directive(emitter, tag_directive, false) { - return false - } - } - - for i := 0; i < len(default_tag_directives); i++ { - tag_directive := &default_tag_directives[i] - if !yaml_emitter_append_tag_directive(emitter, tag_directive, true) { - return false - } - } - - implicit := event.implicit - if !first || emitter.canonical { - implicit = false - } - - if emitter.open_ended && (event.version_directive != nil || len(event.tag_directives) > 0) { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if event.version_directive != nil { - implicit = false - if !yaml_emitter_write_indicator(emitter, []byte("%YAML"), true, false, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("1.1"), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if len(event.tag_directives) > 0 { - implicit = false - for i := 0; i < len(event.tag_directives); i++ { - tag_directive := &event.tag_directives[i] - if !yaml_emitter_write_indicator(emitter, []byte("%TAG"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_handle(emitter, tag_directive.handle) { - return false - } - if !yaml_emitter_write_tag_content(emitter, tag_directive.prefix, true) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - if yaml_emitter_check_empty_document(emitter) { - implicit = false - } - if !implicit { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte("---"), true, false, false) { - return false - } - if emitter.canonical { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - } - - emitter.state = yaml_EMIT_DOCUMENT_CONTENT_STATE - return true - } - - if event.typ == yaml_STREAM_END_EVENT { - if emitter.open_ended { - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_END_STATE - return true - } - - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-START or STREAM-END") -} - -// Expect the root node. -func yaml_emitter_emit_document_content(emitter *yaml_emitter_t, event *yaml_event_t) bool { - emitter.states = append(emitter.states, yaml_EMIT_DOCUMENT_END_STATE) - return yaml_emitter_emit_node(emitter, event, true, false, false, false) -} - -// Expect DOCUMENT-END. -func yaml_emitter_emit_document_end(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if event.typ != yaml_DOCUMENT_END_EVENT { - return yaml_emitter_set_emitter_error(emitter, "expected DOCUMENT-END") - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !event.implicit { - // [Go] Allocate the slice elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("..."), true, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_flush(emitter) { - return false - } - emitter.state = yaml_EMIT_DOCUMENT_START_STATE - emitter.tag_directives = emitter.tag_directives[:0] - return true -} - -// Expect a flow item node. -func yaml_emitter_emit_flow_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'['}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{']'}, false, false, false) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - - return true - } - - if !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) -} - -// Expect a flow key node. -func yaml_emitter_emit_flow_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_write_indicator(emitter, []byte{'{'}, true, true, false) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - emitter.flow_level++ - } - - if event.typ == yaml_MAPPING_END_EVENT { - emitter.flow_level-- - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - if emitter.canonical && !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'}'}, false, false, false) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - - if !first { - if !yaml_emitter_write_indicator(emitter, []byte{','}, false, false, false) { - return false - } - } - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - - if !emitter.canonical && yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, false) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a flow value node. -func yaml_emitter_emit_flow_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if emitter.canonical || emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, false) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_FLOW_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block item node. -func yaml_emitter_emit_block_sequence_item(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, emitter.mapping_context && !emitter.indention) { - return false - } - } - if event.typ == yaml_SEQUENCE_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'-'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE) - return yaml_emitter_emit_node(emitter, event, false, true, false, false) -} - -// Expect a block key node. -func yaml_emitter_emit_block_mapping_key(emitter *yaml_emitter_t, event *yaml_event_t, first bool) bool { - if first { - if !yaml_emitter_increase_indent(emitter, false, false) { - return false - } - } - if event.typ == yaml_MAPPING_END_EVENT { - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true - } - if !yaml_emitter_write_indent(emitter) { - return false - } - if yaml_emitter_check_simple_key(emitter) { - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, true) - } - if !yaml_emitter_write_indicator(emitter, []byte{'?'}, true, false, true) { - return false - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_VALUE_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a block value node. -func yaml_emitter_emit_block_mapping_value(emitter *yaml_emitter_t, event *yaml_event_t, simple bool) bool { - if simple { - if !yaml_emitter_write_indicator(emitter, []byte{':'}, false, false, false) { - return false - } - } else { - if !yaml_emitter_write_indent(emitter) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{':'}, true, false, true) { - return false - } - } - emitter.states = append(emitter.states, yaml_EMIT_BLOCK_MAPPING_KEY_STATE) - return yaml_emitter_emit_node(emitter, event, false, false, true, false) -} - -// Expect a node. -func yaml_emitter_emit_node(emitter *yaml_emitter_t, event *yaml_event_t, - root bool, sequence bool, mapping bool, simple_key bool) bool { - - emitter.root_context = root - emitter.sequence_context = sequence - emitter.mapping_context = mapping - emitter.simple_key_context = simple_key - - switch event.typ { - case yaml_ALIAS_EVENT: - return yaml_emitter_emit_alias(emitter, event) - case yaml_SCALAR_EVENT: - return yaml_emitter_emit_scalar(emitter, event) - case yaml_SEQUENCE_START_EVENT: - return yaml_emitter_emit_sequence_start(emitter, event) - case yaml_MAPPING_START_EVENT: - return yaml_emitter_emit_mapping_start(emitter, event) - default: - return yaml_emitter_set_emitter_error(emitter, - "expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS") - } -} - -// Expect ALIAS. -func yaml_emitter_emit_alias(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SCALAR. -func yaml_emitter_emit_scalar(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_select_scalar_style(emitter, event) { - return false - } - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if !yaml_emitter_increase_indent(emitter, true, false) { - return false - } - if !yaml_emitter_process_scalar(emitter) { - return false - } - emitter.indent = emitter.indents[len(emitter.indents)-1] - emitter.indents = emitter.indents[:len(emitter.indents)-1] - emitter.state = emitter.states[len(emitter.states)-1] - emitter.states = emitter.states[:len(emitter.states)-1] - return true -} - -// Expect SEQUENCE-START. -func yaml_emitter_emit_sequence_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.sequence_style() == yaml_FLOW_SEQUENCE_STYLE || - yaml_emitter_check_empty_sequence(emitter) { - emitter.state = yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE - } - return true -} - -// Expect MAPPING-START. -func yaml_emitter_emit_mapping_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { - if !yaml_emitter_process_anchor(emitter) { - return false - } - if !yaml_emitter_process_tag(emitter) { - return false - } - if emitter.flow_level > 0 || emitter.canonical || event.mapping_style() == yaml_FLOW_MAPPING_STYLE || - yaml_emitter_check_empty_mapping(emitter) { - emitter.state = yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE - } else { - emitter.state = yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE - } - return true -} - -// Check if the document content is an empty scalar. -func yaml_emitter_check_empty_document(emitter *yaml_emitter_t) bool { - return false // [Go] Huh? -} - -// Check if the next events represent an empty sequence. -func yaml_emitter_check_empty_sequence(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_SEQUENCE_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_SEQUENCE_END_EVENT -} - -// Check if the next events represent an empty mapping. -func yaml_emitter_check_empty_mapping(emitter *yaml_emitter_t) bool { - if len(emitter.events)-emitter.events_head < 2 { - return false - } - return emitter.events[emitter.events_head].typ == yaml_MAPPING_START_EVENT && - emitter.events[emitter.events_head+1].typ == yaml_MAPPING_END_EVENT -} - -// Check if the next node can be expressed as a simple key. -func yaml_emitter_check_simple_key(emitter *yaml_emitter_t) bool { - length := 0 - switch emitter.events[emitter.events_head].typ { - case yaml_ALIAS_EVENT: - length += len(emitter.anchor_data.anchor) - case yaml_SCALAR_EVENT: - if emitter.scalar_data.multiline { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) + - len(emitter.scalar_data.value) - case yaml_SEQUENCE_START_EVENT: - if !yaml_emitter_check_empty_sequence(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - case yaml_MAPPING_START_EVENT: - if !yaml_emitter_check_empty_mapping(emitter) { - return false - } - length += len(emitter.anchor_data.anchor) + - len(emitter.tag_data.handle) + - len(emitter.tag_data.suffix) - default: - return false - } - return length <= 128 -} - -// Determine an acceptable scalar style. -func yaml_emitter_select_scalar_style(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - no_tag := len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 - if no_tag && !event.implicit && !event.quoted_implicit { - return yaml_emitter_set_emitter_error(emitter, "neither tag nor implicit flags are specified") - } - - style := event.scalar_style() - if style == yaml_ANY_SCALAR_STYLE { - style = yaml_PLAIN_SCALAR_STYLE - } - if emitter.canonical { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - if emitter.simple_key_context && emitter.scalar_data.multiline { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - - if style == yaml_PLAIN_SCALAR_STYLE { - if emitter.flow_level > 0 && !emitter.scalar_data.flow_plain_allowed || - emitter.flow_level == 0 && !emitter.scalar_data.block_plain_allowed { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if len(emitter.scalar_data.value) == 0 && (emitter.flow_level > 0 || emitter.simple_key_context) { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - if no_tag && !event.implicit { - style = yaml_SINGLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_SINGLE_QUOTED_SCALAR_STYLE { - if !emitter.scalar_data.single_quoted_allowed { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - if style == yaml_LITERAL_SCALAR_STYLE || style == yaml_FOLDED_SCALAR_STYLE { - if !emitter.scalar_data.block_allowed || emitter.flow_level > 0 || emitter.simple_key_context { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - } - - if no_tag && !event.quoted_implicit && style != yaml_PLAIN_SCALAR_STYLE { - emitter.tag_data.handle = []byte{'!'} - } - emitter.scalar_data.style = style - return true -} - -// Write an achor. -func yaml_emitter_process_anchor(emitter *yaml_emitter_t) bool { - if emitter.anchor_data.anchor == nil { - return true - } - c := []byte{'&'} - if emitter.anchor_data.alias { - c[0] = '*' - } - if !yaml_emitter_write_indicator(emitter, c, true, false, false) { - return false - } - return yaml_emitter_write_anchor(emitter, emitter.anchor_data.anchor) -} - -// Write a tag. -func yaml_emitter_process_tag(emitter *yaml_emitter_t) bool { - if len(emitter.tag_data.handle) == 0 && len(emitter.tag_data.suffix) == 0 { - return true - } - if len(emitter.tag_data.handle) > 0 { - if !yaml_emitter_write_tag_handle(emitter, emitter.tag_data.handle) { - return false - } - if len(emitter.tag_data.suffix) > 0 { - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - } - } else { - // [Go] Allocate these slices elsewhere. - if !yaml_emitter_write_indicator(emitter, []byte("!<"), true, false, false) { - return false - } - if !yaml_emitter_write_tag_content(emitter, emitter.tag_data.suffix, false) { - return false - } - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, false, false, false) { - return false - } - } - return true -} - -// Write a scalar. -func yaml_emitter_process_scalar(emitter *yaml_emitter_t) bool { - switch emitter.scalar_data.style { - case yaml_PLAIN_SCALAR_STYLE: - return yaml_emitter_write_plain_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_SINGLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_single_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_DOUBLE_QUOTED_SCALAR_STYLE: - return yaml_emitter_write_double_quoted_scalar(emitter, emitter.scalar_data.value, !emitter.simple_key_context) - - case yaml_LITERAL_SCALAR_STYLE: - return yaml_emitter_write_literal_scalar(emitter, emitter.scalar_data.value) - - case yaml_FOLDED_SCALAR_STYLE: - return yaml_emitter_write_folded_scalar(emitter, emitter.scalar_data.value) - } - panic("unknown scalar style") -} - -// Check if a %YAML directive is valid. -func yaml_emitter_analyze_version_directive(emitter *yaml_emitter_t, version_directive *yaml_version_directive_t) bool { - if version_directive.major != 1 || version_directive.minor != 1 { - return yaml_emitter_set_emitter_error(emitter, "incompatible %YAML directive") - } - return true -} - -// Check if a %TAG directive is valid. -func yaml_emitter_analyze_tag_directive(emitter *yaml_emitter_t, tag_directive *yaml_tag_directive_t) bool { - handle := tag_directive.handle - prefix := tag_directive.prefix - if len(handle) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag handle must not be empty") - } - if handle[0] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must start with '!'") - } - if handle[len(handle)-1] != '!' { - return yaml_emitter_set_emitter_error(emitter, "tag handle must end with '!'") - } - for i := 1; i < len(handle)-1; i += width(handle[i]) { - if !is_alpha(handle, i) { - return yaml_emitter_set_emitter_error(emitter, "tag handle must contain alphanumerical characters only") - } - } - if len(prefix) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag prefix must not be empty") - } - return true -} - -// Check if an anchor is valid. -func yaml_emitter_analyze_anchor(emitter *yaml_emitter_t, anchor []byte, alias bool) bool { - if len(anchor) == 0 { - problem := "anchor value must not be empty" - if alias { - problem = "alias value must not be empty" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - for i := 0; i < len(anchor); i += width(anchor[i]) { - if !is_alpha(anchor, i) { - problem := "anchor value must contain alphanumerical characters only" - if alias { - problem = "alias value must contain alphanumerical characters only" - } - return yaml_emitter_set_emitter_error(emitter, problem) - } - } - emitter.anchor_data.anchor = anchor - emitter.anchor_data.alias = alias - return true -} - -// Check if a tag is valid. -func yaml_emitter_analyze_tag(emitter *yaml_emitter_t, tag []byte) bool { - if len(tag) == 0 { - return yaml_emitter_set_emitter_error(emitter, "tag value must not be empty") - } - for i := 0; i < len(emitter.tag_directives); i++ { - tag_directive := &emitter.tag_directives[i] - if bytes.HasPrefix(tag, tag_directive.prefix) { - emitter.tag_data.handle = tag_directive.handle - emitter.tag_data.suffix = tag[len(tag_directive.prefix):] - return true - } - } - emitter.tag_data.suffix = tag - return true -} - -// Check if a scalar is valid. -func yaml_emitter_analyze_scalar(emitter *yaml_emitter_t, value []byte) bool { - var ( - block_indicators = false - flow_indicators = false - line_breaks = false - special_characters = false - - leading_space = false - leading_break = false - trailing_space = false - trailing_break = false - break_space = false - space_break = false - - preceded_by_whitespace = false - followed_by_whitespace = false - previous_space = false - previous_break = false - ) - - emitter.scalar_data.value = value - - if len(value) == 0 { - emitter.scalar_data.multiline = false - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = false - return true - } - - if len(value) >= 3 && ((value[0] == '-' && value[1] == '-' && value[2] == '-') || (value[0] == '.' && value[1] == '.' && value[2] == '.')) { - block_indicators = true - flow_indicators = true - } - - preceded_by_whitespace = true - for i, w := 0, 0; i < len(value); i += w { - w = width(value[i]) - followed_by_whitespace = i+w >= len(value) || is_blank(value, i+w) - - if i == 0 { - switch value[i] { - case '#', ',', '[', ']', '{', '}', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`': - flow_indicators = true - block_indicators = true - case '?', ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '-': - if followed_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } else { - switch value[i] { - case ',', '?', '[', ']', '{', '}': - flow_indicators = true - case ':': - flow_indicators = true - if followed_by_whitespace { - block_indicators = true - } - case '#': - if preceded_by_whitespace { - flow_indicators = true - block_indicators = true - } - } - } - - if !is_printable(value, i) || !is_ascii(value, i) && !emitter.unicode { - special_characters = true - } - if is_space(value, i) { - if i == 0 { - leading_space = true - } - if i+width(value[i]) == len(value) { - trailing_space = true - } - if previous_break { - break_space = true - } - previous_space = true - previous_break = false - } else if is_break(value, i) { - line_breaks = true - if i == 0 { - leading_break = true - } - if i+width(value[i]) == len(value) { - trailing_break = true - } - if previous_space { - space_break = true - } - previous_space = false - previous_break = true - } else { - previous_space = false - previous_break = false - } - - // [Go]: Why 'z'? Couldn't be the end of the string as that's the loop condition. - preceded_by_whitespace = is_blankz(value, i) - } - - emitter.scalar_data.multiline = line_breaks - emitter.scalar_data.flow_plain_allowed = true - emitter.scalar_data.block_plain_allowed = true - emitter.scalar_data.single_quoted_allowed = true - emitter.scalar_data.block_allowed = true - - if leading_space || leading_break || trailing_space || trailing_break { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if trailing_space { - emitter.scalar_data.block_allowed = false - } - if break_space { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - } - if space_break || special_characters { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - emitter.scalar_data.single_quoted_allowed = false - emitter.scalar_data.block_allowed = false - } - if line_breaks { - emitter.scalar_data.flow_plain_allowed = false - emitter.scalar_data.block_plain_allowed = false - } - if flow_indicators { - emitter.scalar_data.flow_plain_allowed = false - } - if block_indicators { - emitter.scalar_data.block_plain_allowed = false - } - return true -} - -// Check if the event data is valid. -func yaml_emitter_analyze_event(emitter *yaml_emitter_t, event *yaml_event_t) bool { - - emitter.anchor_data.anchor = nil - emitter.tag_data.handle = nil - emitter.tag_data.suffix = nil - emitter.scalar_data.value = nil - - switch event.typ { - case yaml_ALIAS_EVENT: - if !yaml_emitter_analyze_anchor(emitter, event.anchor, true) { - return false - } - - case yaml_SCALAR_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || (!event.implicit && !event.quoted_implicit)) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - if !yaml_emitter_analyze_scalar(emitter, event.value) { - return false - } - - case yaml_SEQUENCE_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - - case yaml_MAPPING_START_EVENT: - if len(event.anchor) > 0 { - if !yaml_emitter_analyze_anchor(emitter, event.anchor, false) { - return false - } - } - if len(event.tag) > 0 && (emitter.canonical || !event.implicit) { - if !yaml_emitter_analyze_tag(emitter, event.tag) { - return false - } - } - } - return true -} - -// Write the BOM character. -func yaml_emitter_write_bom(emitter *yaml_emitter_t) bool { - if !flush(emitter) { - return false - } - pos := emitter.buffer_pos - emitter.buffer[pos+0] = '\xEF' - emitter.buffer[pos+1] = '\xBB' - emitter.buffer[pos+2] = '\xBF' - emitter.buffer_pos += 3 - return true -} - -func yaml_emitter_write_indent(emitter *yaml_emitter_t) bool { - indent := emitter.indent - if indent < 0 { - indent = 0 - } - if !emitter.indention || emitter.column > indent || (emitter.column == indent && !emitter.whitespace) { - if !put_break(emitter) { - return false - } - } - for emitter.column < indent { - if !put(emitter, ' ') { - return false - } - } - emitter.whitespace = true - emitter.indention = true - return true -} - -func yaml_emitter_write_indicator(emitter *yaml_emitter_t, indicator []byte, need_whitespace, is_whitespace, is_indention bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, indicator) { - return false - } - emitter.whitespace = is_whitespace - emitter.indention = (emitter.indention && is_indention) - emitter.open_ended = false - return true -} - -func yaml_emitter_write_anchor(emitter *yaml_emitter_t, value []byte) bool { - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_handle(emitter *yaml_emitter_t, value []byte) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - if !write_all(emitter, value) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_tag_content(emitter *yaml_emitter_t, value []byte, need_whitespace bool) bool { - if need_whitespace && !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - for i := 0; i < len(value); { - var must_write bool - switch value[i] { - case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '~', '*', '\'', '(', ')', '[', ']': - must_write = true - default: - must_write = is_alpha(value, i) - } - if must_write { - if !write(emitter, value, &i) { - return false - } - } else { - w := width(value[i]) - for k := 0; k < w; k++ { - octet := value[i] - i++ - if !put(emitter, '%') { - return false - } - - c := octet >> 4 - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - - c = octet & 0x0f - if c < 10 { - c += '0' - } else { - c += 'A' - 10 - } - if !put(emitter, c) { - return false - } - } - } - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_plain_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - if !emitter.whitespace { - if !put(emitter, ' ') { - return false - } - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - - emitter.whitespace = false - emitter.indention = false - if emitter.root_context { - emitter.open_ended = true - } - - return true -} - -func yaml_emitter_write_single_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, true, false, false) { - return false - } - - spaces := false - breaks := false - for i := 0; i < len(value); { - if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 && !is_space(value, i+1) { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - spaces = true - } else if is_break(value, i) { - if !breaks && value[i] == '\n' { - if !put_break(emitter) { - return false - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if value[i] == '\'' { - if !put(emitter, '\'') { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - spaces = false - breaks = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'\''}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_double_quoted_scalar(emitter *yaml_emitter_t, value []byte, allow_breaks bool) bool { - spaces := false - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, true, false, false) { - return false - } - - for i := 0; i < len(value); { - if !is_printable(value, i) || (!emitter.unicode && !is_ascii(value, i)) || - is_bom(value, i) || is_break(value, i) || - value[i] == '"' || value[i] == '\\' { - - octet := value[i] - - var w int - var v rune - switch { - case octet&0x80 == 0x00: - w, v = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, v = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, v = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, v = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = value[i+k] - v = (v << 6) + (rune(octet) & 0x3F) - } - i += w - - if !put(emitter, '\\') { - return false - } - - var ok bool - switch v { - case 0x00: - ok = put(emitter, '0') - case 0x07: - ok = put(emitter, 'a') - case 0x08: - ok = put(emitter, 'b') - case 0x09: - ok = put(emitter, 't') - case 0x0A: - ok = put(emitter, 'n') - case 0x0b: - ok = put(emitter, 'v') - case 0x0c: - ok = put(emitter, 'f') - case 0x0d: - ok = put(emitter, 'r') - case 0x1b: - ok = put(emitter, 'e') - case 0x22: - ok = put(emitter, '"') - case 0x5c: - ok = put(emitter, '\\') - case 0x85: - ok = put(emitter, 'N') - case 0xA0: - ok = put(emitter, '_') - case 0x2028: - ok = put(emitter, 'L') - case 0x2029: - ok = put(emitter, 'P') - default: - if v <= 0xFF { - ok = put(emitter, 'x') - w = 2 - } else if v <= 0xFFFF { - ok = put(emitter, 'u') - w = 4 - } else { - ok = put(emitter, 'U') - w = 8 - } - for k := (w - 1) * 4; ok && k >= 0; k -= 4 { - digit := byte((v >> uint(k)) & 0x0F) - if digit < 10 { - ok = put(emitter, digit+'0') - } else { - ok = put(emitter, digit+'A'-10) - } - } - } - if !ok { - return false - } - spaces = false - } else if is_space(value, i) { - if allow_breaks && !spaces && emitter.column > emitter.best_width && i > 0 && i < len(value)-1 { - if !yaml_emitter_write_indent(emitter) { - return false - } - if is_space(value, i+1) { - if !put(emitter, '\\') { - return false - } - } - i += width(value[i]) - } else if !write(emitter, value, &i) { - return false - } - spaces = true - } else { - if !write(emitter, value, &i) { - return false - } - spaces = false - } - } - if !yaml_emitter_write_indicator(emitter, []byte{'"'}, false, false, false) { - return false - } - emitter.whitespace = false - emitter.indention = false - return true -} - -func yaml_emitter_write_block_scalar_hints(emitter *yaml_emitter_t, value []byte) bool { - if is_space(value, 0) || is_break(value, 0) { - indent_hint := []byte{'0' + byte(emitter.best_indent)} - if !yaml_emitter_write_indicator(emitter, indent_hint, false, false, false) { - return false - } - } - - emitter.open_ended = false - - var chomp_hint [1]byte - if len(value) == 0 { - chomp_hint[0] = '-' - } else { - i := len(value) - 1 - for value[i]&0xC0 == 0x80 { - i-- - } - if !is_break(value, i) { - chomp_hint[0] = '-' - } else if i == 0 { - chomp_hint[0] = '+' - emitter.open_ended = true - } else { - i-- - for value[i]&0xC0 == 0x80 { - i-- - } - if is_break(value, i) { - chomp_hint[0] = '+' - emitter.open_ended = true - } - } - } - if chomp_hint[0] != 0 { - if !yaml_emitter_write_indicator(emitter, chomp_hint[:], false, false, false) { - return false - } - } - return true -} - -func yaml_emitter_write_literal_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'|'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - if !put_break(emitter) { - return false - } - emitter.indention = true - emitter.whitespace = true - breaks := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - } - if !write(emitter, value, &i) { - return false - } - emitter.indention = false - breaks = false - } - } - - return true -} - -func yaml_emitter_write_folded_scalar(emitter *yaml_emitter_t, value []byte) bool { - if !yaml_emitter_write_indicator(emitter, []byte{'>'}, true, false, false) { - return false - } - if !yaml_emitter_write_block_scalar_hints(emitter, value) { - return false - } - - if !put_break(emitter) { - return false - } - emitter.indention = true - emitter.whitespace = true - - breaks := true - leading_spaces := true - for i := 0; i < len(value); { - if is_break(value, i) { - if !breaks && !leading_spaces && value[i] == '\n' { - k := 0 - for is_break(value, k) { - k += width(value[k]) - } - if !is_blankz(value, k) { - if !put_break(emitter) { - return false - } - } - } - if !write_break(emitter, value, &i) { - return false - } - emitter.indention = true - breaks = true - } else { - if breaks { - if !yaml_emitter_write_indent(emitter) { - return false - } - leading_spaces = is_blank(value, i) - } - if !breaks && is_space(value, i) && !is_space(value, i+1) && emitter.column > emitter.best_width { - if !yaml_emitter_write_indent(emitter) { - return false - } - i += width(value[i]) - } else { - if !write(emitter, value, &i) { - return false - } - } - emitter.indention = false - breaks = false - } - } - return true -} diff --git a/vendor/github.com/sanathkr/go-yaml/encode.go b/vendor/github.com/sanathkr/go-yaml/encode.go deleted file mode 100644 index 84f8499551..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/encode.go +++ /dev/null @@ -1,306 +0,0 @@ -package yaml - -import ( - "encoding" - "fmt" - "reflect" - "regexp" - "sort" - "strconv" - "strings" - "time" -) - -type encoder struct { - emitter yaml_emitter_t - event yaml_event_t - out []byte - flow bool -} - -func newEncoder() (e *encoder) { - e = &encoder{} - e.must(yaml_emitter_initialize(&e.emitter)) - yaml_emitter_set_output_string(&e.emitter, &e.out) - yaml_emitter_set_unicode(&e.emitter, true) - e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)) - e.emit() - e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true)) - e.emit() - return e -} - -func (e *encoder) finish() { - e.must(yaml_document_end_event_initialize(&e.event, true)) - e.emit() - e.emitter.open_ended = false - e.must(yaml_stream_end_event_initialize(&e.event)) - e.emit() -} - -func (e *encoder) destroy() { - yaml_emitter_delete(&e.emitter) -} - -func (e *encoder) emit() { - // This will internally delete the e.event value. - if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT { - e.must(false) - } -} - -func (e *encoder) must(ok bool) { - if !ok { - msg := e.emitter.problem - if msg == "" { - msg = "unknown problem generating YAML content" - } - failf("%s", msg) - } -} - -func (e *encoder) marshal(tag string, in reflect.Value) { - if !in.IsValid() { - e.nilv() - return - } - iface := in.Interface() - if m, ok := iface.(Marshaler); ok { - v, err := m.MarshalYAML() - if err != nil { - fail(err) - } - if v == nil { - e.nilv() - return - } - in = reflect.ValueOf(v) - } else if m, ok := iface.(encoding.TextMarshaler); ok { - text, err := m.MarshalText() - if err != nil { - fail(err) - } - in = reflect.ValueOf(string(text)) - } - switch in.Kind() { - case reflect.Interface: - if in.IsNil() { - e.nilv() - } else { - e.marshal(tag, in.Elem()) - } - case reflect.Map: - e.mapv(tag, in) - case reflect.Ptr: - if in.IsNil() { - e.nilv() - } else { - e.marshal(tag, in.Elem()) - } - case reflect.Struct: - e.structv(tag, in) - case reflect.Slice: - if in.Type().Elem() == mapItemType { - e.itemsv(tag, in) - } else { - e.slicev(tag, in) - } - case reflect.String: - e.stringv(tag, in) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if in.Type() == durationType { - e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String())) - } else { - e.intv(tag, in) - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - e.uintv(tag, in) - case reflect.Float32, reflect.Float64: - e.floatv(tag, in) - case reflect.Bool: - e.boolv(tag, in) - default: - panic("cannot marshal type: " + in.Type().String()) - } -} - -func (e *encoder) mapv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - keys := keyList(in.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - e.marshal("", k) - e.marshal("", in.MapIndex(k)) - } - }) -} - -func (e *encoder) itemsv(tag string, in reflect.Value) { - e.mappingv(tag, func() { - slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem) - for _, item := range slice { - e.marshal("", reflect.ValueOf(item.Key)) - e.marshal("", reflect.ValueOf(item.Value)) - } - }) -} - -func (e *encoder) structv(tag string, in reflect.Value) { - sinfo, err := getStructInfo(in.Type()) - if err != nil { - panic(err) - } - e.mappingv(tag, func() { - for _, info := range sinfo.FieldsList { - var value reflect.Value - if info.Inline == nil { - value = in.Field(info.Num) - } else { - value = in.FieldByIndex(info.Inline) - } - if info.OmitEmpty && isZero(value) { - continue - } - e.marshal("", reflect.ValueOf(info.Key)) - e.flow = info.Flow - e.marshal("", value) - } - if sinfo.InlineMap >= 0 { - m := in.Field(sinfo.InlineMap) - if m.Len() > 0 { - e.flow = false - keys := keyList(m.MapKeys()) - sort.Sort(keys) - for _, k := range keys { - if _, found := sinfo.FieldsMap[k.String()]; found { - panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String())) - } - e.marshal("", k) - e.flow = false - e.marshal("", m.MapIndex(k)) - } - } - } - }) -} - -func (e *encoder) mappingv(tag string, f func()) { - implicit := tag == "" - style := yaml_BLOCK_MAPPING_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_MAPPING_STYLE - } - e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) - e.emit() - f() - e.must(yaml_mapping_end_event_initialize(&e.event)) - e.emit() -} - -func (e *encoder) slicev(tag string, in reflect.Value) { - implicit := tag == "" - style := yaml_BLOCK_SEQUENCE_STYLE - if e.flow { - e.flow = false - style = yaml_FLOW_SEQUENCE_STYLE - } - e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)) - e.emit() - n := in.Len() - for i := 0; i < n; i++ { - e.marshal("", in.Index(i)) - } - e.must(yaml_sequence_end_event_initialize(&e.event)) - e.emit() -} - -// isBase60 returns whether s is in base 60 notation as defined in YAML 1.1. -// -// The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported -// in YAML 1.2 and by this package, but these should be marshalled quoted for -// the time being for compatibility with other parsers. -func isBase60Float(s string) (result bool) { - // Fast path. - if s == "" { - return false - } - c := s[0] - if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 { - return false - } - // Do the full match. - return base60float.MatchString(s) -} - -// From http://yaml.org/type/float.html, except the regular expression there -// is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix. -var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`) - -func (e *encoder) stringv(tag string, in reflect.Value) { - var style yaml_scalar_style_t - s := in.String() - rtag, rs := resolve("", s) - if rtag == yaml_BINARY_TAG { - if tag == "" || tag == yaml_STR_TAG { - tag = rtag - s = rs.(string) - } else if tag == yaml_BINARY_TAG { - failf("explicitly tagged !!binary data must be base64-encoded") - } else { - failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag)) - } - } - if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) { - style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } else if strings.Contains(s, "\n") { - style = yaml_LITERAL_SCALAR_STYLE - } else { - style = yaml_PLAIN_SCALAR_STYLE - } - e.emitScalar(s, "", tag, style) -} - -func (e *encoder) boolv(tag string, in reflect.Value) { - var s string - if in.Bool() { - s = "true" - } else { - s = "false" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) intv(tag string, in reflect.Value) { - s := strconv.FormatInt(in.Int(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) uintv(tag string, in reflect.Value) { - s := strconv.FormatUint(in.Uint(), 10) - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) floatv(tag string, in reflect.Value) { - // FIXME: Handle 64 bits here. - s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) nilv() { - e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) -} - -func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { - implicit := tag == "" - e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style)) - e.emit() -} diff --git a/vendor/github.com/sanathkr/go-yaml/parserc.go b/vendor/github.com/sanathkr/go-yaml/parserc.go deleted file mode 100644 index 81d05dfe57..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/parserc.go +++ /dev/null @@ -1,1095 +0,0 @@ -package yaml - -import ( - "bytes" -) - -// The parser implements the following grammar: -// -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// implicit_document ::= block_node DOCUMENT-END* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// block_node_or_indentless_sequence ::= -// ALIAS -// | properties (block_content | indentless_block_sequence)? -// | block_content -// | indentless_block_sequence -// block_node ::= ALIAS -// | properties block_content? -// | block_content -// flow_node ::= ALIAS -// | properties flow_content? -// | flow_content -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// block_content ::= block_collection | flow_collection | SCALAR -// flow_content ::= flow_collection | SCALAR -// block_collection ::= block_sequence | block_mapping -// flow_collection ::= flow_sequence | flow_mapping -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// block_mapping ::= BLOCK-MAPPING_START -// ((KEY block_node_or_indentless_sequence?)? -// (VALUE block_node_or_indentless_sequence?)?)* -// BLOCK-END -// flow_sequence ::= FLOW-SEQUENCE-START -// (flow_sequence_entry FLOW-ENTRY)* -// flow_sequence_entry? -// FLOW-SEQUENCE-END -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// flow_mapping ::= FLOW-MAPPING-START -// (flow_mapping_entry FLOW-ENTRY)* -// flow_mapping_entry? -// FLOW-MAPPING-END -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? - -// Peek the next token in the token queue. -func peek_token(parser *yaml_parser_t) *yaml_token_t { - if parser.token_available || yaml_parser_fetch_more_tokens(parser) { - return &parser.tokens[parser.tokens_head] - } - return nil -} - -// Remove the next token from the queue (must be called after peek_token). -func skip_token(parser *yaml_parser_t) { - parser.token_available = false - parser.tokens_parsed++ - parser.stream_end_produced = parser.tokens[parser.tokens_head].typ == yaml_STREAM_END_TOKEN - parser.tokens_head++ -} - -// Get the next event. -func yaml_parser_parse(parser *yaml_parser_t, event *yaml_event_t) bool { - // Erase the event object. - *event = yaml_event_t{} - - // No events after the end of the stream or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR || parser.state == yaml_PARSE_END_STATE { - return true - } - - // Generate the next event. - return yaml_parser_state_machine(parser, event) -} - -// Set parser error. -func yaml_parser_set_parser_error(parser *yaml_parser_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -func yaml_parser_set_parser_error_context(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string, problem_mark yaml_mark_t) bool { - parser.error = yaml_PARSER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = problem_mark - return false -} - -// State dispatcher. -func yaml_parser_state_machine(parser *yaml_parser_t, event *yaml_event_t) bool { - //trace("yaml_parser_state_machine", "state:", parser.state.String()) - - switch parser.state { - case yaml_PARSE_STREAM_START_STATE: - return yaml_parser_parse_stream_start(parser, event) - - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, true) - - case yaml_PARSE_DOCUMENT_START_STATE: - return yaml_parser_parse_document_start(parser, event, false) - - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return yaml_parser_parse_document_content(parser, event) - - case yaml_PARSE_DOCUMENT_END_STATE: - return yaml_parser_parse_document_end(parser, event) - - case yaml_PARSE_BLOCK_NODE_STATE: - return yaml_parser_parse_node(parser, event, true, false) - - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return yaml_parser_parse_node(parser, event, true, true) - - case yaml_PARSE_FLOW_NODE_STATE: - return yaml_parser_parse_node(parser, event, false, false) - - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, true) - - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_block_sequence_entry(parser, event, false) - - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_indentless_sequence_entry(parser, event) - - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, true) - - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return yaml_parser_parse_block_mapping_key(parser, event, false) - - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return yaml_parser_parse_block_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, true) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return yaml_parser_parse_flow_sequence_entry(parser, event, false) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_key(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_value(parser, event) - - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return yaml_parser_parse_flow_sequence_entry_mapping_end(parser, event) - - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, true) - - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return yaml_parser_parse_flow_mapping_key(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, false) - - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return yaml_parser_parse_flow_mapping_value(parser, event, true) - - default: - panic("invalid parser state") - } -} - -// Parse the production: -// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END -// ************ -func yaml_parser_parse_stream_start(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_STREAM_START_TOKEN { - return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) - } - parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - encoding: token.encoding, - } - skip_token(parser) - return true -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// * -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// ************************* -func yaml_parser_parse_document_start(parser *yaml_parser_t, event *yaml_event_t, implicit bool) bool { - - token := peek_token(parser) - if token == nil { - return false - } - - // Parse extra document end indicators. - if !implicit { - for token.typ == yaml_DOCUMENT_END_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - if implicit && token.typ != yaml_VERSION_DIRECTIVE_TOKEN && - token.typ != yaml_TAG_DIRECTIVE_TOKEN && - token.typ != yaml_DOCUMENT_START_TOKEN && - token.typ != yaml_STREAM_END_TOKEN { - // Parse an implicit document. - if !yaml_parser_process_directives(parser, nil, nil) { - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_BLOCK_NODE_STATE - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - } else if token.typ != yaml_STREAM_END_TOKEN { - // Parse an explicit document. - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - start_mark := token.start_mark - if !yaml_parser_process_directives(parser, &version_directive, &tag_directives) { - return false - } - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_DOCUMENT_START_TOKEN { - yaml_parser_set_parser_error(parser, - "did not find expected ", token.start_mark) - return false - } - parser.states = append(parser.states, yaml_PARSE_DOCUMENT_END_STATE) - parser.state = yaml_PARSE_DOCUMENT_CONTENT_STATE - end_mark := token.end_mark - - *event = yaml_event_t{ - typ: yaml_DOCUMENT_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - version_directive: version_directive, - tag_directives: tag_directives, - implicit: false, - } - skip_token(parser) - - } else { - // Parse the stream end. - parser.state = yaml_PARSE_END_STATE - *event = yaml_event_t{ - typ: yaml_STREAM_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - } - - return true -} - -// Parse the productions: -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// *********** -// -func yaml_parser_parse_document_content(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN || - token.typ == yaml_TAG_DIRECTIVE_TOKEN || - token.typ == yaml_DOCUMENT_START_TOKEN || - token.typ == yaml_DOCUMENT_END_TOKEN || - token.typ == yaml_STREAM_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - return yaml_parser_process_empty_scalar(parser, event, - token.start_mark) - } - return yaml_parser_parse_node(parser, event, true, false) -} - -// Parse the productions: -// implicit_document ::= block_node DOCUMENT-END* -// ************* -// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* -// -func yaml_parser_parse_document_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - start_mark := token.start_mark - end_mark := token.start_mark - - implicit := true - if token.typ == yaml_DOCUMENT_END_TOKEN { - end_mark = token.end_mark - skip_token(parser) - implicit = false - } - - parser.tag_directives = parser.tag_directives[:0] - - parser.state = yaml_PARSE_DOCUMENT_START_STATE - *event = yaml_event_t{ - typ: yaml_DOCUMENT_END_EVENT, - start_mark: start_mark, - end_mark: end_mark, - implicit: implicit, - } - return true -} - -// Parse the productions: -// block_node_or_indentless_sequence ::= -// ALIAS -// ***** -// | properties (block_content | indentless_block_sequence)? -// ********** * -// | block_content | indentless_block_sequence -// * -// block_node ::= ALIAS -// ***** -// | properties block_content? -// ********** * -// | block_content -// * -// flow_node ::= ALIAS -// ***** -// | properties flow_content? -// ********** * -// | flow_content -// * -// properties ::= TAG ANCHOR? | ANCHOR TAG? -// ************************* -// block_content ::= block_collection | flow_collection | SCALAR -// ****** -// flow_content ::= flow_collection | SCALAR -// ****** -func yaml_parser_parse_node(parser *yaml_parser_t, event *yaml_event_t, block, indentless_sequence bool) bool { - //defer trace("yaml_parser_parse_node", "block:", block, "indentless_sequence:", indentless_sequence)() - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_ALIAS_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - *event = yaml_event_t{ - typ: yaml_ALIAS_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - anchor: token.value, - } - skip_token(parser) - return true - } - - start_mark := token.start_mark - end_mark := token.start_mark - - var tag_token bool - var tag_handle, tag_suffix, anchor []byte - var tag_mark yaml_mark_t - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - start_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } else if token.typ == yaml_TAG_TOKEN { - tag_token = true - tag_handle = token.value - tag_suffix = token.suffix - start_mark = token.start_mark - tag_mark = token.start_mark - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_ANCHOR_TOKEN { - anchor = token.value - end_mark = token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - } - - var tag []byte - if tag_token { - if len(tag_handle) == 0 { - tag = tag_suffix - tag_suffix = nil - } else { - for i := range parser.tag_directives { - if bytes.Equal(parser.tag_directives[i].handle, tag_handle) { - tag = append([]byte(nil), parser.tag_directives[i].prefix...) - tag = append(tag, tag_suffix...) - break - } - } - if len(tag) == 0 { - yaml_parser_set_parser_error_context(parser, - "while parsing a node", start_mark, - "found undefined tag handle", tag_mark) - return false - } - } - } - - implicit := len(tag) == 0 - if indentless_sequence && token.typ == yaml_BLOCK_ENTRY_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_SCALAR_TOKEN { - var plain_implicit, quoted_implicit bool - end_mark = token.end_mark - if (len(tag) == 0 && token.style == yaml_PLAIN_SCALAR_STYLE) || (len(tag) == 1 && tag[0] == '!') { - plain_implicit = true - } else if len(tag) == 0 { - quoted_implicit = true - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - value: token.value, - implicit: plain_implicit, - quoted_implicit: quoted_implicit, - style: yaml_style_t(token.style), - } - skip_token(parser) - return true - } - if token.typ == yaml_FLOW_SEQUENCE_START_TOKEN { - // [Go] Some of the events below can be merged as they differ only on style. - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_SEQUENCE_STYLE), - } - return true - } - if token.typ == yaml_FLOW_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_SEQUENCE_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_SEQUENCE_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_SEQUENCE_STYLE), - } - return true - } - if block && token.typ == yaml_BLOCK_MAPPING_START_TOKEN { - end_mark = token.end_mark - parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - style: yaml_style_t(yaml_BLOCK_MAPPING_STYLE), - } - return true - } - if len(anchor) > 0 || len(tag) > 0 { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: start_mark, - end_mark: end_mark, - anchor: anchor, - tag: tag, - implicit: implicit, - quoted_implicit: false, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true - } - - context := "while parsing a flow node" - if block { - context = "while parsing a block node" - } - yaml_parser_set_parser_error_context(parser, context, start_mark, - "did not find expected node content", token.start_mark) - return false -} - -// Parse the productions: -// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END -// ******************** *********** * ********* -// -func yaml_parser_parse_block_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } else { - parser.state = yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } - if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block collection", context_mark, - "did not find expected '-' indicator", token.start_mark) -} - -// Parse the productions: -// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ -// *********** * -func yaml_parser_parse_indentless_sequence_entry(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_BLOCK_ENTRY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_BLOCK_ENTRY_TOKEN && - token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, true, false) - } - parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be token.end_mark? - } - return true -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// ******************* -// ((KEY block_node_or_indentless_sequence?)? -// *** * -// (VALUE block_node_or_indentless_sequence?)?)* -// -// BLOCK-END -// ********* -// -func yaml_parser_parse_block_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ == yaml_KEY_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } else { - parser.state = yaml_PARSE_BLOCK_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - } else if token.typ == yaml_BLOCK_END_TOKEN { - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true - } - - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a block mapping", context_mark, - "did not find expected key", token.start_mark) -} - -// Parse the productions: -// block_mapping ::= BLOCK-MAPPING_START -// -// ((KEY block_node_or_indentless_sequence?)? -// -// (VALUE block_node_or_indentless_sequence?)?)* -// ***** * -// BLOCK-END -// -// -func yaml_parser_parse_block_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - mark := token.end_mark - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_KEY_TOKEN && - token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_BLOCK_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, true, true) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) - } - parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence ::= FLOW-SEQUENCE-START -// ******************* -// (flow_sequence_entry FLOW-ENTRY)* -// * ********** -// flow_sequence_entry? -// * -// FLOW-SEQUENCE-END -// ***************** -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow sequence", context_mark, - "did not find expected ',' or ']'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_START_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - implicit: true, - style: yaml_style_t(yaml_FLOW_MAPPING_STYLE), - } - skip_token(parser) - return true - } else if token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - - *event = yaml_event_t{ - typ: yaml_SEQUENCE_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - - skip_token(parser) - return true -} - -// -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// *** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_key(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - mark := token.end_mark - skip_token(parser) - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// ***** * -// -func yaml_parser_parse_flow_sequence_entry_mapping_value(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token := peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_SEQUENCE_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Parse the productions: -// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * -// -func yaml_parser_parse_flow_sequence_entry_mapping_end(parser *yaml_parser_t, event *yaml_event_t) bool { - token := peek_token(parser) - if token == nil { - return false - } - parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.start_mark, // [Go] Shouldn't this be end_mark? - } - return true -} - -// Parse the productions: -// flow_mapping ::= FLOW-MAPPING-START -// ****************** -// (flow_mapping_entry FLOW-ENTRY)* -// * ********** -// flow_mapping_entry? -// ****************** -// FLOW-MAPPING-END -// **************** -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * *** * -// -func yaml_parser_parse_flow_mapping_key(parser *yaml_parser_t, event *yaml_event_t, first bool) bool { - if first { - token := peek_token(parser) - parser.marks = append(parser.marks, token.start_mark) - skip_token(parser) - } - - token := peek_token(parser) - if token == nil { - return false - } - - if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - if !first { - if token.typ == yaml_FLOW_ENTRY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } else { - context_mark := parser.marks[len(parser.marks)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - return yaml_parser_set_parser_error_context(parser, - "while parsing a flow mapping", context_mark, - "did not find expected ',' or '}'", token.start_mark) - } - } - - if token.typ == yaml_KEY_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_VALUE_TOKEN && - token.typ != yaml_FLOW_ENTRY_TOKEN && - token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } else { - parser.state = yaml_PARSE_FLOW_MAPPING_VALUE_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - } else if token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - - parser.state = parser.states[len(parser.states)-1] - parser.states = parser.states[:len(parser.states)-1] - parser.marks = parser.marks[:len(parser.marks)-1] - *event = yaml_event_t{ - typ: yaml_MAPPING_END_EVENT, - start_mark: token.start_mark, - end_mark: token.end_mark, - } - skip_token(parser) - return true -} - -// Parse the productions: -// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? -// * ***** * -// -func yaml_parser_parse_flow_mapping_value(parser *yaml_parser_t, event *yaml_event_t, empty bool) bool { - token := peek_token(parser) - if token == nil { - return false - } - if empty { - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) - } - if token.typ == yaml_VALUE_TOKEN { - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - if token.typ != yaml_FLOW_ENTRY_TOKEN && token.typ != yaml_FLOW_MAPPING_END_TOKEN { - parser.states = append(parser.states, yaml_PARSE_FLOW_MAPPING_KEY_STATE) - return yaml_parser_parse_node(parser, event, false, false) - } - } - parser.state = yaml_PARSE_FLOW_MAPPING_KEY_STATE - return yaml_parser_process_empty_scalar(parser, event, token.start_mark) -} - -// Generate an empty scalar event. -func yaml_parser_process_empty_scalar(parser *yaml_parser_t, event *yaml_event_t, mark yaml_mark_t) bool { - *event = yaml_event_t{ - typ: yaml_SCALAR_EVENT, - start_mark: mark, - end_mark: mark, - value: nil, // Empty - implicit: true, - style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), - } - return true -} - -var default_tag_directives = []yaml_tag_directive_t{ - {[]byte("!"), []byte("!")}, - {[]byte("!!"), []byte("tag:yaml.org,2002:")}, -} - -// Parse directives. -func yaml_parser_process_directives(parser *yaml_parser_t, - version_directive_ref **yaml_version_directive_t, - tag_directives_ref *[]yaml_tag_directive_t) bool { - - var version_directive *yaml_version_directive_t - var tag_directives []yaml_tag_directive_t - - token := peek_token(parser) - if token == nil { - return false - } - - for token.typ == yaml_VERSION_DIRECTIVE_TOKEN || token.typ == yaml_TAG_DIRECTIVE_TOKEN { - if token.typ == yaml_VERSION_DIRECTIVE_TOKEN { - if version_directive != nil { - yaml_parser_set_parser_error(parser, - "found duplicate %YAML directive", token.start_mark) - return false - } - if token.major != 1 || token.minor != 1 { - yaml_parser_set_parser_error(parser, - "found incompatible YAML document", token.start_mark) - return false - } - version_directive = &yaml_version_directive_t{ - major: token.major, - minor: token.minor, - } - } else if token.typ == yaml_TAG_DIRECTIVE_TOKEN { - value := yaml_tag_directive_t{ - handle: token.value, - prefix: token.prefix, - } - if !yaml_parser_append_tag_directive(parser, value, false, token.start_mark) { - return false - } - tag_directives = append(tag_directives, value) - } - - skip_token(parser) - token = peek_token(parser) - if token == nil { - return false - } - } - - for i := range default_tag_directives { - if !yaml_parser_append_tag_directive(parser, default_tag_directives[i], true, token.start_mark) { - return false - } - } - - if version_directive_ref != nil { - *version_directive_ref = version_directive - } - if tag_directives_ref != nil { - *tag_directives_ref = tag_directives - } - return true -} - -// Append a tag directive to the directives stack. -func yaml_parser_append_tag_directive(parser *yaml_parser_t, value yaml_tag_directive_t, allow_duplicates bool, mark yaml_mark_t) bool { - for i := range parser.tag_directives { - if bytes.Equal(value.handle, parser.tag_directives[i].handle) { - if allow_duplicates { - return true - } - return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) - } - } - - // [Go] I suspect the copy is unnecessary. This was likely done - // because there was no way to track ownership of the data. - value_copy := yaml_tag_directive_t{ - handle: make([]byte, len(value.handle)), - prefix: make([]byte, len(value.prefix)), - } - copy(value_copy.handle, value.handle) - copy(value_copy.prefix, value.prefix) - parser.tag_directives = append(parser.tag_directives, value_copy) - return true -} diff --git a/vendor/github.com/sanathkr/go-yaml/readerc.go b/vendor/github.com/sanathkr/go-yaml/readerc.go deleted file mode 100644 index f450791717..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/readerc.go +++ /dev/null @@ -1,394 +0,0 @@ -package yaml - -import ( - "io" -) - -// Set the reader error and return 0. -func yaml_parser_set_reader_error(parser *yaml_parser_t, problem string, offset int, value int) bool { - parser.error = yaml_READER_ERROR - parser.problem = problem - parser.problem_offset = offset - parser.problem_value = value - return false -} - -// Byte order marks. -const ( - bom_UTF8 = "\xef\xbb\xbf" - bom_UTF16LE = "\xff\xfe" - bom_UTF16BE = "\xfe\xff" -) - -// Determine the input stream encoding by checking the BOM symbol. If no BOM is -// found, the UTF-8 encoding is assumed. Return 1 on success, 0 on failure. -func yaml_parser_determine_encoding(parser *yaml_parser_t) bool { - // Ensure that we had enough bytes in the raw buffer. - for !parser.eof && len(parser.raw_buffer)-parser.raw_buffer_pos < 3 { - if !yaml_parser_update_raw_buffer(parser) { - return false - } - } - - // Determine the encoding. - buf := parser.raw_buffer - pos := parser.raw_buffer_pos - avail := len(buf) - pos - if avail >= 2 && buf[pos] == bom_UTF16LE[0] && buf[pos+1] == bom_UTF16LE[1] { - parser.encoding = yaml_UTF16LE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 2 && buf[pos] == bom_UTF16BE[0] && buf[pos+1] == bom_UTF16BE[1] { - parser.encoding = yaml_UTF16BE_ENCODING - parser.raw_buffer_pos += 2 - parser.offset += 2 - } else if avail >= 3 && buf[pos] == bom_UTF8[0] && buf[pos+1] == bom_UTF8[1] && buf[pos+2] == bom_UTF8[2] { - parser.encoding = yaml_UTF8_ENCODING - parser.raw_buffer_pos += 3 - parser.offset += 3 - } else { - parser.encoding = yaml_UTF8_ENCODING - } - return true -} - -// Update the raw buffer. -func yaml_parser_update_raw_buffer(parser *yaml_parser_t) bool { - size_read := 0 - - // Return if the raw buffer is full. - if parser.raw_buffer_pos == 0 && len(parser.raw_buffer) == cap(parser.raw_buffer) { - return true - } - - // Return on EOF. - if parser.eof { - return true - } - - // Move the remaining bytes in the raw buffer to the beginning. - if parser.raw_buffer_pos > 0 && parser.raw_buffer_pos < len(parser.raw_buffer) { - copy(parser.raw_buffer, parser.raw_buffer[parser.raw_buffer_pos:]) - } - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)-parser.raw_buffer_pos] - parser.raw_buffer_pos = 0 - - // Call the read handler to fill the buffer. - size_read, err := parser.read_handler(parser, parser.raw_buffer[len(parser.raw_buffer):cap(parser.raw_buffer)]) - parser.raw_buffer = parser.raw_buffer[:len(parser.raw_buffer)+size_read] - if err == io.EOF { - parser.eof = true - } else if err != nil { - return yaml_parser_set_reader_error(parser, "input error: "+err.Error(), parser.offset, -1) - } - return true -} - -// Ensure that the buffer contains at least `length` characters. -// Return true on success, false on failure. -// -// The length is supposed to be significantly less that the buffer size. -func yaml_parser_update_buffer(parser *yaml_parser_t, length int) bool { - if parser.read_handler == nil { - panic("read handler must be set") - } - - // If the EOF flag is set and the raw buffer is empty, do nothing. - if parser.eof && parser.raw_buffer_pos == len(parser.raw_buffer) { - return true - } - - // Return if the buffer contains enough characters. - if parser.unread >= length { - return true - } - - // Determine the input encoding if it is not known yet. - if parser.encoding == yaml_ANY_ENCODING { - if !yaml_parser_determine_encoding(parser) { - return false - } - } - - // Move the unread characters to the beginning of the buffer. - buffer_len := len(parser.buffer) - if parser.buffer_pos > 0 && parser.buffer_pos < buffer_len { - copy(parser.buffer, parser.buffer[parser.buffer_pos:]) - buffer_len -= parser.buffer_pos - parser.buffer_pos = 0 - } else if parser.buffer_pos == buffer_len { - buffer_len = 0 - parser.buffer_pos = 0 - } - - // Open the whole buffer for writing, and cut it before returning. - parser.buffer = parser.buffer[:cap(parser.buffer)] - - // Fill the buffer until it has enough characters. - first := true - for parser.unread < length { - - // Fill the raw buffer if necessary. - if !first || parser.raw_buffer_pos == len(parser.raw_buffer) { - if !yaml_parser_update_raw_buffer(parser) { - parser.buffer = parser.buffer[:buffer_len] - return false - } - } - first = false - - // Decode the raw buffer. - inner: - for parser.raw_buffer_pos != len(parser.raw_buffer) { - var value rune - var width int - - raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos - - // Decode the next character. - switch parser.encoding { - case yaml_UTF8_ENCODING: - // Decode a UTF-8 character. Check RFC 3629 - // (http://www.ietf.org/rfc/rfc3629.txt) for more details. - // - // The following table (taken from the RFC) is used for - // decoding. - // - // Char. number range | UTF-8 octet sequence - // (hexadecimal) | (binary) - // --------------------+------------------------------------ - // 0000 0000-0000 007F | 0xxxxxxx - // 0000 0080-0000 07FF | 110xxxxx 10xxxxxx - // 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx - // 0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // - // Additionally, the characters in the range 0xD800-0xDFFF - // are prohibited as they are reserved for use with UTF-16 - // surrogate pairs. - - // Determine the length of the UTF-8 sequence. - octet := parser.raw_buffer[parser.raw_buffer_pos] - switch { - case octet&0x80 == 0x00: - width = 1 - case octet&0xE0 == 0xC0: - width = 2 - case octet&0xF0 == 0xE0: - width = 3 - case octet&0xF8 == 0xF0: - width = 4 - default: - // The leading octet is invalid. - return yaml_parser_set_reader_error(parser, - "invalid leading UTF-8 octet", - parser.offset, int(octet)) - } - - // Check if the raw buffer contains an incomplete character. - if width > raw_unread { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-8 octet sequence", - parser.offset, -1) - } - break inner - } - - // Decode the leading octet. - switch { - case octet&0x80 == 0x00: - value = rune(octet & 0x7F) - case octet&0xE0 == 0xC0: - value = rune(octet & 0x1F) - case octet&0xF0 == 0xE0: - value = rune(octet & 0x0F) - case octet&0xF8 == 0xF0: - value = rune(octet & 0x07) - default: - value = 0 - } - - // Check and decode the trailing octets. - for k := 1; k < width; k++ { - octet = parser.raw_buffer[parser.raw_buffer_pos+k] - - // Check if the octet is valid. - if (octet & 0xC0) != 0x80 { - return yaml_parser_set_reader_error(parser, - "invalid trailing UTF-8 octet", - parser.offset+k, int(octet)) - } - - // Decode the octet. - value = (value << 6) + rune(octet&0x3F) - } - - // Check the length of the sequence against the value. - switch { - case width == 1: - case width == 2 && value >= 0x80: - case width == 3 && value >= 0x800: - case width == 4 && value >= 0x10000: - default: - return yaml_parser_set_reader_error(parser, - "invalid length of a UTF-8 sequence", - parser.offset, -1) - } - - // Check the range of the value. - if value >= 0xD800 && value <= 0xDFFF || value > 0x10FFFF { - return yaml_parser_set_reader_error(parser, - "invalid Unicode character", - parser.offset, int(value)) - } - - case yaml_UTF16LE_ENCODING, yaml_UTF16BE_ENCODING: - var low, high int - if parser.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - low, high = 1, 0 - } - - // The UTF-16 encoding is not as simple as one might - // naively think. Check RFC 2781 - // (http://www.ietf.org/rfc/rfc2781.txt). - // - // Normally, two subsequent bytes describe a Unicode - // character. However a special technique (called a - // surrogate pair) is used for specifying character - // values larger than 0xFFFF. - // - // A surrogate pair consists of two pseudo-characters: - // high surrogate area (0xD800-0xDBFF) - // low surrogate area (0xDC00-0xDFFF) - // - // The following formulas are used for decoding - // and encoding characters using surrogate pairs: - // - // U = U' + 0x10000 (0x01 00 00 <= U <= 0x10 FF FF) - // U' = yyyyyyyyyyxxxxxxxxxx (0 <= U' <= 0x0F FF FF) - // W1 = 110110yyyyyyyyyy - // W2 = 110111xxxxxxxxxx - // - // where U is the character value, W1 is the high surrogate - // area, W2 is the low surrogate area. - - // Check for incomplete UTF-16 character. - if raw_unread < 2 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 character", - parser.offset, -1) - } - break inner - } - - // Get the character. - value = rune(parser.raw_buffer[parser.raw_buffer_pos+low]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high]) << 8) - - // Check for unexpected low surrogate area. - if value&0xFC00 == 0xDC00 { - return yaml_parser_set_reader_error(parser, - "unexpected low surrogate area", - parser.offset, int(value)) - } - - // Check for a high surrogate area. - if value&0xFC00 == 0xD800 { - width = 4 - - // Check for incomplete surrogate pair. - if raw_unread < 4 { - if parser.eof { - return yaml_parser_set_reader_error(parser, - "incomplete UTF-16 surrogate pair", - parser.offset, -1) - } - break inner - } - - // Get the next character. - value2 := rune(parser.raw_buffer[parser.raw_buffer_pos+low+2]) + - (rune(parser.raw_buffer[parser.raw_buffer_pos+high+2]) << 8) - - // Check for a low surrogate area. - if value2&0xFC00 != 0xDC00 { - return yaml_parser_set_reader_error(parser, - "expected low surrogate area", - parser.offset+2, int(value2)) - } - - // Generate the value of the surrogate pair. - value = 0x10000 + ((value & 0x3FF) << 10) + (value2 & 0x3FF) - } else { - width = 2 - } - - default: - panic("impossible") - } - - // Check if the character is in the allowed range: - // #x9 | #xA | #xD | [#x20-#x7E] (8 bit) - // | #x85 | [#xA0-#xD7FF] | [#xE000-#xFFFD] (16 bit) - // | [#x10000-#x10FFFF] (32 bit) - switch { - case value == 0x09: - case value == 0x0A: - case value == 0x0D: - case value >= 0x20 && value <= 0x7E: - case value == 0x85: - case value >= 0xA0 && value <= 0xD7FF: - case value >= 0xE000 && value <= 0xFFFD: - case value >= 0x10000 && value <= 0x10FFFF: - default: - return yaml_parser_set_reader_error(parser, - "control characters are not allowed", - parser.offset, int(value)) - } - - // Move the raw pointers. - parser.raw_buffer_pos += width - parser.offset += width - - // Finally put the character into the buffer. - if value <= 0x7F { - // 0000 0000-0000 007F . 0xxxxxxx - parser.buffer[buffer_len+0] = byte(value) - buffer_len += 1 - } else if value <= 0x7FF { - // 0000 0080-0000 07FF . 110xxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xC0 + (value >> 6)) - parser.buffer[buffer_len+1] = byte(0x80 + (value & 0x3F)) - buffer_len += 2 - } else if value <= 0xFFFF { - // 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xE0 + (value >> 12)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + (value & 0x3F)) - buffer_len += 3 - } else { - // 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - parser.buffer[buffer_len+0] = byte(0xF0 + (value >> 18)) - parser.buffer[buffer_len+1] = byte(0x80 + ((value >> 12) & 0x3F)) - parser.buffer[buffer_len+2] = byte(0x80 + ((value >> 6) & 0x3F)) - parser.buffer[buffer_len+3] = byte(0x80 + (value & 0x3F)) - buffer_len += 4 - } - - parser.unread++ - } - - // On EOF, put NUL into the buffer and return. - if parser.eof { - parser.buffer[buffer_len] = 0 - buffer_len++ - parser.unread++ - break - } - } - parser.buffer = parser.buffer[:buffer_len] - return true -} diff --git a/vendor/github.com/sanathkr/go-yaml/resolve.go b/vendor/github.com/sanathkr/go-yaml/resolve.go deleted file mode 100644 index 232313cc08..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/resolve.go +++ /dev/null @@ -1,208 +0,0 @@ -package yaml - -import ( - "encoding/base64" - "math" - "regexp" - "strconv" - "strings" - "unicode/utf8" -) - -type resolveMapItem struct { - value interface{} - tag string -} - -var resolveTable = make([]byte, 256) -var resolveMap = make(map[string]resolveMapItem) - -func init() { - t := resolveTable - t[int('+')] = 'S' // Sign - t[int('-')] = 'S' - for _, c := range "0123456789" { - t[int(c)] = 'D' // Digit - } - for _, c := range "yYnNtTfFoO~" { - t[int(c)] = 'M' // In map - } - t[int('.')] = '.' // Float (potentially in map) - - var resolveMapList = []struct { - v interface{} - tag string - l []string - }{ - {true, yaml_BOOL_TAG, []string{"y", "Y", "yes", "Yes", "YES"}}, - {true, yaml_BOOL_TAG, []string{"true", "True", "TRUE"}}, - {true, yaml_BOOL_TAG, []string{"on", "On", "ON"}}, - {false, yaml_BOOL_TAG, []string{"n", "N", "no", "No", "NO"}}, - {false, yaml_BOOL_TAG, []string{"false", "False", "FALSE"}}, - {false, yaml_BOOL_TAG, []string{"off", "Off", "OFF"}}, - {nil, yaml_NULL_TAG, []string{"", "~", "null", "Null", "NULL"}}, - {math.NaN(), yaml_FLOAT_TAG, []string{".nan", ".NaN", ".NAN"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{".inf", ".Inf", ".INF"}}, - {math.Inf(+1), yaml_FLOAT_TAG, []string{"+.inf", "+.Inf", "+.INF"}}, - {math.Inf(-1), yaml_FLOAT_TAG, []string{"-.inf", "-.Inf", "-.INF"}}, - {"<<", yaml_MERGE_TAG, []string{"<<"}}, - } - - m := resolveMap - for _, item := range resolveMapList { - for _, s := range item.l { - m[s] = resolveMapItem{item.v, item.tag} - } - } -} - -const longTagPrefix = "tag:yaml.org,2002:" - -func shortTag(tag string) string { - // TODO This can easily be made faster and produce less garbage. - if strings.HasPrefix(tag, longTagPrefix) { - return "!!" + tag[len(longTagPrefix):] - } - return tag -} - -func longTag(tag string) string { - if strings.HasPrefix(tag, "!!") { - return longTagPrefix + tag[2:] - } - return tag -} - -func resolvableTag(tag string) bool { - switch tag { - case "", yaml_STR_TAG, yaml_BOOL_TAG, yaml_INT_TAG, yaml_FLOAT_TAG, yaml_NULL_TAG: - return true - } - return false -} - -var yamlStyleFloat = regexp.MustCompile(`^[-+]?[0-9]*\.?[0-9]+([eE][-+][0-9]+)?$`) - -func resolve(tag string, in string) (rtag string, out interface{}) { - if !resolvableTag(tag) { - return tag, in - } - - defer func() { - switch tag { - case "", rtag, yaml_STR_TAG, yaml_BINARY_TAG: - return - } - failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag)) - }() - - // Any data is accepted as a !!str or !!binary. - // Otherwise, the prefix is enough of a hint about what it might be. - hint := byte('N') - if in != "" { - hint = resolveTable[in[0]] - } - if hint != 0 && tag != yaml_STR_TAG && tag != yaml_BINARY_TAG { - // Handle things we can lookup in a map. - if item, ok := resolveMap[in]; ok { - return item.tag, item.value - } - - // Base 60 floats are a bad idea, were dropped in YAML 1.2, and - // are purposefully unsupported here. They're still quoted on - // the way out for compatibility with other parser, though. - - switch hint { - case 'M': - // We've already checked the map above. - - case '.': - // Not in the map, so maybe a normal float. - floatv, err := strconv.ParseFloat(in, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - - case 'D', 'S': - // Int, float, or timestamp. - plain := strings.Replace(in, "_", "", -1) - intv, err := strconv.ParseInt(plain, 0, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain, 0, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - if yamlStyleFloat.MatchString(plain) { - floatv, err := strconv.ParseFloat(plain, 64) - if err == nil { - return yaml_FLOAT_TAG, floatv - } - } - if strings.HasPrefix(plain, "0b") { - intv, err := strconv.ParseInt(plain[2:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, int(intv) - } else { - return yaml_INT_TAG, intv - } - } - uintv, err := strconv.ParseUint(plain[2:], 2, 64) - if err == nil { - return yaml_INT_TAG, uintv - } - } else if strings.HasPrefix(plain, "-0b") { - intv, err := strconv.ParseInt(plain[3:], 2, 64) - if err == nil { - if intv == int64(int(intv)) { - return yaml_INT_TAG, -int(intv) - } else { - return yaml_INT_TAG, -intv - } - } - } - // XXX Handle timestamps here. - - default: - panic("resolveTable item not yet handled: " + string(rune(hint)) + " (with " + in + ")") - } - } - if tag == yaml_BINARY_TAG { - return yaml_BINARY_TAG, in - } - if utf8.ValidString(in) { - return yaml_STR_TAG, in - } - return yaml_BINARY_TAG, encodeBase64(in) -} - -// encodeBase64 encodes s as base64 that is broken up into multiple lines -// as appropriate for the resulting length. -func encodeBase64(s string) string { - const lineLen = 70 - encLen := base64.StdEncoding.EncodedLen(len(s)) - lines := encLen/lineLen + 1 - buf := make([]byte, encLen*2+lines) - in := buf[0:encLen] - out := buf[encLen:] - base64.StdEncoding.Encode(in, []byte(s)) - k := 0 - for i := 0; i < len(in); i += lineLen { - j := i + lineLen - if j > len(in) { - j = len(in) - } - k += copy(out[k:], in[i:j]) - if lines > 1 { - out[k] = '\n' - k++ - } - } - return string(out[:k]) -} diff --git a/vendor/github.com/sanathkr/go-yaml/scannerc.go b/vendor/github.com/sanathkr/go-yaml/scannerc.go deleted file mode 100644 index 0744844558..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/scannerc.go +++ /dev/null @@ -1,2711 +0,0 @@ -package yaml - -import ( - "bytes" - "fmt" -) - -// Introduction -// ************ -// -// The following notes assume that you are familiar with the YAML specification -// (http://yaml.org/spec/1.2/spec.html). We mostly follow it, although in -// some cases we are less restrictive that it requires. -// -// The process of transforming a YAML stream into a sequence of events is -// divided on two steps: Scanning and Parsing. -// -// The Scanner transforms the input stream into a sequence of tokens, while the -// parser transform the sequence of tokens produced by the Scanner into a -// sequence of parsing events. -// -// The Scanner is rather clever and complicated. The Parser, on the contrary, -// is a straightforward implementation of a recursive-descendant parser (or, -// LL(1) parser, as it is usually called). -// -// Actually there are two issues of Scanning that might be called "clever", the -// rest is quite straightforward. The issues are "block collection start" and -// "simple keys". Both issues are explained below in details. -// -// Here the Scanning step is explained and implemented. We start with the list -// of all the tokens produced by the Scanner together with short descriptions. -// -// Now, tokens: -// -// STREAM-START(encoding) # The stream start. -// STREAM-END # The stream end. -// VERSION-DIRECTIVE(major,minor) # The '%YAML' directive. -// TAG-DIRECTIVE(handle,prefix) # The '%TAG' directive. -// DOCUMENT-START # '---' -// DOCUMENT-END # '...' -// BLOCK-SEQUENCE-START # Indentation increase denoting a block -// BLOCK-MAPPING-START # sequence or a block mapping. -// BLOCK-END # Indentation decrease. -// FLOW-SEQUENCE-START # '[' -// FLOW-SEQUENCE-END # ']' -// BLOCK-SEQUENCE-START # '{' -// BLOCK-SEQUENCE-END # '}' -// BLOCK-ENTRY # '-' -// FLOW-ENTRY # ',' -// KEY # '?' or nothing (simple keys). -// VALUE # ':' -// ALIAS(anchor) # '*anchor' -// ANCHOR(anchor) # '&anchor' -// TAG(handle,suffix) # '!handle!suffix' -// SCALAR(value,style) # A scalar. -// -// The following two tokens are "virtual" tokens denoting the beginning and the -// end of the stream: -// -// STREAM-START(encoding) -// STREAM-END -// -// We pass the information about the input stream encoding with the -// STREAM-START token. -// -// The next two tokens are responsible for tags: -// -// VERSION-DIRECTIVE(major,minor) -// TAG-DIRECTIVE(handle,prefix) -// -// Example: -// -// %YAML 1.1 -// %TAG ! !foo -// %TAG !yaml! tag:yaml.org,2002: -// --- -// -// The correspoding sequence of tokens: -// -// STREAM-START(utf-8) -// VERSION-DIRECTIVE(1,1) -// TAG-DIRECTIVE("!","!foo") -// TAG-DIRECTIVE("!yaml","tag:yaml.org,2002:") -// DOCUMENT-START -// STREAM-END -// -// Note that the VERSION-DIRECTIVE and TAG-DIRECTIVE tokens occupy a whole -// line. -// -// The document start and end indicators are represented by: -// -// DOCUMENT-START -// DOCUMENT-END -// -// Note that if a YAML stream contains an implicit document (without '---' -// and '...' indicators), no DOCUMENT-START and DOCUMENT-END tokens will be -// produced. -// -// In the following examples, we present whole documents together with the -// produced tokens. -// -// 1. An implicit document: -// -// 'a scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// STREAM-END -// -// 2. An explicit document: -// -// --- -// 'a scalar' -// ... -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// SCALAR("a scalar",single-quoted) -// DOCUMENT-END -// STREAM-END -// -// 3. Several documents in a stream: -// -// 'a scalar' -// --- -// 'another scalar' -// --- -// 'yet another scalar' -// -// Tokens: -// -// STREAM-START(utf-8) -// SCALAR("a scalar",single-quoted) -// DOCUMENT-START -// SCALAR("another scalar",single-quoted) -// DOCUMENT-START -// SCALAR("yet another scalar",single-quoted) -// STREAM-END -// -// We have already introduced the SCALAR token above. The following tokens are -// used to describe aliases, anchors, tag, and scalars: -// -// ALIAS(anchor) -// ANCHOR(anchor) -// TAG(handle,suffix) -// SCALAR(value,style) -// -// The following series of examples illustrate the usage of these tokens: -// -// 1. A recursive sequence: -// -// &A [ *A ] -// -// Tokens: -// -// STREAM-START(utf-8) -// ANCHOR("A") -// FLOW-SEQUENCE-START -// ALIAS("A") -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A tagged scalar: -// -// !!float "3.14" # A good approximation. -// -// Tokens: -// -// STREAM-START(utf-8) -// TAG("!!","float") -// SCALAR("3.14",double-quoted) -// STREAM-END -// -// 3. Various scalar styles: -// -// --- # Implicit empty plain scalars do not produce tokens. -// --- a plain scalar -// --- 'a single-quoted scalar' -// --- "a double-quoted scalar" -// --- |- -// a literal scalar -// --- >- -// a folded -// scalar -// -// Tokens: -// -// STREAM-START(utf-8) -// DOCUMENT-START -// DOCUMENT-START -// SCALAR("a plain scalar",plain) -// DOCUMENT-START -// SCALAR("a single-quoted scalar",single-quoted) -// DOCUMENT-START -// SCALAR("a double-quoted scalar",double-quoted) -// DOCUMENT-START -// SCALAR("a literal scalar",literal) -// DOCUMENT-START -// SCALAR("a folded scalar",folded) -// STREAM-END -// -// Now it's time to review collection-related tokens. We will start with -// flow collections: -// -// FLOW-SEQUENCE-START -// FLOW-SEQUENCE-END -// FLOW-MAPPING-START -// FLOW-MAPPING-END -// FLOW-ENTRY -// KEY -// VALUE -// -// The tokens FLOW-SEQUENCE-START, FLOW-SEQUENCE-END, FLOW-MAPPING-START, and -// FLOW-MAPPING-END represent the indicators '[', ']', '{', and '}' -// correspondingly. FLOW-ENTRY represent the ',' indicator. Finally the -// indicators '?' and ':', which are used for denoting mapping keys and values, -// are represented by the KEY and VALUE tokens. -// -// The following examples show flow collections: -// -// 1. A flow sequence: -// -// [item 1, item 2, item 3] -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-SEQUENCE-START -// SCALAR("item 1",plain) -// FLOW-ENTRY -// SCALAR("item 2",plain) -// FLOW-ENTRY -// SCALAR("item 3",plain) -// FLOW-SEQUENCE-END -// STREAM-END -// -// 2. A flow mapping: -// -// { -// a simple key: a value, # Note that the KEY token is produced. -// ? a complex key: another value, -// } -// -// Tokens: -// -// STREAM-START(utf-8) -// FLOW-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// FLOW-ENTRY -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// FLOW-ENTRY -// FLOW-MAPPING-END -// STREAM-END -// -// A simple key is a key which is not denoted by the '?' indicator. Note that -// the Scanner still produce the KEY token whenever it encounters a simple key. -// -// For scanning block collections, the following tokens are used (note that we -// repeat KEY and VALUE here): -// -// BLOCK-SEQUENCE-START -// BLOCK-MAPPING-START -// BLOCK-END -// BLOCK-ENTRY -// KEY -// VALUE -// -// The tokens BLOCK-SEQUENCE-START and BLOCK-MAPPING-START denote indentation -// increase that precedes a block collection (cf. the INDENT token in Python). -// The token BLOCK-END denote indentation decrease that ends a block collection -// (cf. the DEDENT token in Python). However YAML has some syntax pecularities -// that makes detections of these tokens more complex. -// -// The tokens BLOCK-ENTRY, KEY, and VALUE are used to represent the indicators -// '-', '?', and ':' correspondingly. -// -// The following examples show how the tokens BLOCK-SEQUENCE-START, -// BLOCK-MAPPING-START, and BLOCK-END are emitted by the Scanner: -// -// 1. Block sequences: -// -// - item 1 -// - item 2 -// - -// - item 3.1 -// - item 3.2 -// - -// key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 3.1",plain) -// BLOCK-ENTRY -// SCALAR("item 3.2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Block mappings: -// -// a simple key: a value # The KEY token is produced here. -// ? a complex key -// : another value -// a mapping: -// key 1: value 1 -// key 2: value 2 -// a sequence: -// - item 1 -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a simple key",plain) -// VALUE -// SCALAR("a value",plain) -// KEY -// SCALAR("a complex key",plain) -// VALUE -// SCALAR("another value",plain) -// KEY -// SCALAR("a mapping",plain) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML does not always require to start a new block collection from a new -// line. If the current line contains only '-', '?', and ':' indicators, a new -// block collection may start at the current line. The following examples -// illustrate this case: -// -// 1. Collections in a sequence: -// -// - - item 1 -// - item 2 -// - key 1: value 1 -// key 2: value 2 -// - ? complex key -// : complex value -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-ENTRY -// BLOCK-MAPPING-START -// KEY -// SCALAR("complex key") -// VALUE -// SCALAR("complex value") -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// 2. Collections in a mapping: -// -// ? a sequence -// : - item 1 -// - item 2 -// ? a mapping -// : key 1: value 1 -// key 2: value 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("a sequence",plain) -// VALUE -// BLOCK-SEQUENCE-START -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// KEY -// SCALAR("a mapping",plain) -// VALUE -// BLOCK-MAPPING-START -// KEY -// SCALAR("key 1",plain) -// VALUE -// SCALAR("value 1",plain) -// KEY -// SCALAR("key 2",plain) -// VALUE -// SCALAR("value 2",plain) -// BLOCK-END -// BLOCK-END -// STREAM-END -// -// YAML also permits non-indented sequences if they are included into a block -// mapping. In this case, the token BLOCK-SEQUENCE-START is not produced: -// -// key: -// - item 1 # BLOCK-SEQUENCE-START is NOT produced here. -// - item 2 -// -// Tokens: -// -// STREAM-START(utf-8) -// BLOCK-MAPPING-START -// KEY -// SCALAR("key",plain) -// VALUE -// BLOCK-ENTRY -// SCALAR("item 1",plain) -// BLOCK-ENTRY -// SCALAR("item 2",plain) -// BLOCK-END -// - -// Ensure that the buffer contains the required number of characters. -// Return true on success, false on failure (reader error or memory error). -func cache(parser *yaml_parser_t, length int) bool { - // [Go] This was inlined: !cache(A, B) -> unread < B && !update(A, B) - return parser.unread >= length || yaml_parser_update_buffer(parser, length) -} - -// Advance the buffer pointer. -func skip(parser *yaml_parser_t) { - parser.mark.index++ - parser.mark.column++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) -} - -func skip_line(parser *yaml_parser_t) { - if is_crlf(parser.buffer, parser.buffer_pos) { - parser.mark.index += 2 - parser.mark.column = 0 - parser.mark.line++ - parser.unread -= 2 - parser.buffer_pos += 2 - } else if is_break(parser.buffer, parser.buffer_pos) { - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - parser.buffer_pos += width(parser.buffer[parser.buffer_pos]) - } -} - -// Copy a character to a string buffer and advance pointers. -func read(parser *yaml_parser_t, s []byte) []byte { - w := width(parser.buffer[parser.buffer_pos]) - if w == 0 { - panic("invalid character sequence") - } - if len(s) == 0 { - s = make([]byte, 0, 32) - } - if w == 1 && len(s)+w <= cap(s) { - s = s[:len(s)+1] - s[len(s)-1] = parser.buffer[parser.buffer_pos] - parser.buffer_pos++ - } else { - s = append(s, parser.buffer[parser.buffer_pos:parser.buffer_pos+w]...) - parser.buffer_pos += w - } - parser.mark.index++ - parser.mark.column++ - parser.unread-- - return s -} - -// Copy a line break character to a string buffer and advance pointers. -func read_line(parser *yaml_parser_t, s []byte) []byte { - buf := parser.buffer - pos := parser.buffer_pos - switch { - case buf[pos] == '\r' && buf[pos+1] == '\n': - // CR LF . LF - s = append(s, '\n') - parser.buffer_pos += 2 - parser.mark.index++ - parser.unread-- - case buf[pos] == '\r' || buf[pos] == '\n': - // CR|LF . LF - s = append(s, '\n') - parser.buffer_pos += 1 - case buf[pos] == '\xC2' && buf[pos+1] == '\x85': - // NEL . LF - s = append(s, '\n') - parser.buffer_pos += 2 - case buf[pos] == '\xE2' && buf[pos+1] == '\x80' && (buf[pos+2] == '\xA8' || buf[pos+2] == '\xA9'): - // LS|PS . LS|PS - s = append(s, buf[parser.buffer_pos:pos+3]...) - parser.buffer_pos += 3 - default: - return s - } - parser.mark.index++ - parser.mark.column = 0 - parser.mark.line++ - parser.unread-- - return s -} - -// Get the next token. -func yaml_parser_scan(parser *yaml_parser_t, token *yaml_token_t) bool { - // Erase the token object. - *token = yaml_token_t{} // [Go] Is this necessary? - - // No tokens after STREAM-END or error. - if parser.stream_end_produced || parser.error != yaml_NO_ERROR { - return true - } - - // Ensure that the tokens queue contains enough tokens. - if !parser.token_available { - if !yaml_parser_fetch_more_tokens(parser) { - return false - } - } - - // Fetch the next token from the queue. - *token = parser.tokens[parser.tokens_head] - parser.tokens_head++ - parser.tokens_parsed++ - parser.token_available = false - - if token.typ == yaml_STREAM_END_TOKEN { - parser.stream_end_produced = true - } - return true -} - -// Set the scanner error and return false. -func yaml_parser_set_scanner_error(parser *yaml_parser_t, context string, context_mark yaml_mark_t, problem string) bool { - parser.error = yaml_SCANNER_ERROR - parser.context = context - parser.context_mark = context_mark - parser.problem = problem - parser.problem_mark = parser.mark - return false -} - -func yaml_parser_set_scanner_tag_error(parser *yaml_parser_t, directive bool, context_mark yaml_mark_t, problem string) bool { - context := "while parsing a tag" - if directive { - context = "while parsing a %TAG directive" - } - return yaml_parser_set_scanner_error(parser, context, context_mark, problem) -} - -func trace(args ...interface{}) func() { - pargs := append([]interface{}{"+++"}, args...) - fmt.Println(pargs...) - pargs = append([]interface{}{"---"}, args...) - return func() { fmt.Println(pargs...) } -} - -// Ensure that the tokens queue contains at least one token which can be -// returned to the Parser. -func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { - // While we need more tokens to fetch, do it. - for { - // Check if we really need to fetch more tokens. - need_more_tokens := false - - if parser.tokens_head == len(parser.tokens) { - // Queue is empty. - need_more_tokens = true - } else { - // Check if any potential simple key may occupy the head position. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - if simple_key.possible && simple_key.token_number == parser.tokens_parsed { - need_more_tokens = true - break - } - } - } - - // We are finished. - if !need_more_tokens { - break - } - // Fetch the next token. - if !yaml_parser_fetch_next_token(parser) { - return false - } - } - - parser.token_available = true - return true -} - -// The dispatcher for token fetchers. -func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { - // Ensure that the buffer is initialized. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check if we just started scanning. Fetch STREAM-START then. - if !parser.stream_start_produced { - return yaml_parser_fetch_stream_start(parser) - } - - // Eat whitespaces and comments until we reach the next token. - if !yaml_parser_scan_to_next_token(parser) { - return false - } - - // Remove obsolete potential simple keys. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - - // Check the indentation level against the current column. - if !yaml_parser_unroll_indent(parser, parser.mark.column) { - return false - } - - // Ensure that the buffer contains at least 4 characters. 4 is the length - // of the longest indicators ('--- ' and '... '). - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - // Is it the end of the stream? - if is_z(parser.buffer, parser.buffer_pos) { - return yaml_parser_fetch_stream_end(parser) - } - - // Is it a directive? - if parser.mark.column == 0 && parser.buffer[parser.buffer_pos] == '%' { - return yaml_parser_fetch_directive(parser) - } - - buf := parser.buffer - pos := parser.buffer_pos - - // Is it the document start indicator? - if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_START_TOKEN) - } - - // Is it the document end indicator? - if parser.mark.column == 0 && buf[pos] == '.' && buf[pos+1] == '.' && buf[pos+2] == '.' && is_blankz(buf, pos+3) { - return yaml_parser_fetch_document_indicator(parser, yaml_DOCUMENT_END_TOKEN) - } - - // Is it the flow sequence start indicator? - if buf[pos] == '[' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_SEQUENCE_START_TOKEN) - } - - // Is it the flow mapping start indicator? - if parser.buffer[parser.buffer_pos] == '{' { - return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) - } - - // Is it the flow sequence end indicator? - if parser.buffer[parser.buffer_pos] == ']' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_SEQUENCE_END_TOKEN) - } - - // Is it the flow mapping end indicator? - if parser.buffer[parser.buffer_pos] == '}' { - return yaml_parser_fetch_flow_collection_end(parser, - yaml_FLOW_MAPPING_END_TOKEN) - } - - // Is it the flow entry indicator? - if parser.buffer[parser.buffer_pos] == ',' { - return yaml_parser_fetch_flow_entry(parser) - } - - // Is it the block entry indicator? - if parser.buffer[parser.buffer_pos] == '-' && is_blankz(parser.buffer, parser.buffer_pos+1) { - return yaml_parser_fetch_block_entry(parser) - } - - // Is it the key indicator? - if parser.buffer[parser.buffer_pos] == '?' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_key(parser) - } - - // Is it the value indicator? - if parser.buffer[parser.buffer_pos] == ':' && (parser.flow_level > 0 || is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_value(parser) - } - - // Is it an alias? - if parser.buffer[parser.buffer_pos] == '*' { - return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) - } - - // Is it an anchor? - if parser.buffer[parser.buffer_pos] == '&' { - return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) - } - - // Is it a tag? - if parser.buffer[parser.buffer_pos] == '!' { - return yaml_parser_fetch_tag(parser) - } - - // Is it a literal scalar? - if parser.buffer[parser.buffer_pos] == '|' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, true) - } - - // Is it a folded scalar? - if parser.buffer[parser.buffer_pos] == '>' && parser.flow_level == 0 { - return yaml_parser_fetch_block_scalar(parser, false) - } - - // Is it a single-quoted scalar? - if parser.buffer[parser.buffer_pos] == '\'' { - return yaml_parser_fetch_flow_scalar(parser, true) - } - - // Is it a double-quoted scalar? - if parser.buffer[parser.buffer_pos] == '"' { - return yaml_parser_fetch_flow_scalar(parser, false) - } - - // Is it a plain scalar? - // - // A plain scalar may start with any non-blank characters except - // - // '-', '?', ':', ',', '[', ']', '{', '}', - // '#', '&', '*', '!', '|', '>', '\'', '\"', - // '%', '@', '`'. - // - // In the block context (and, for the '-' indicator, in the flow context - // too), it may also start with the characters - // - // '-', '?', ':' - // - // if it is followed by a non-space character. - // - // The last rule is more restrictive than the specification requires. - // [Go] Make this logic more reasonable. - //switch parser.buffer[parser.buffer_pos] { - //case '-', '?', ':', ',', '?', '-', ',', ':', ']', '[', '}', '{', '&', '#', '!', '*', '>', '|', '"', '\'', '@', '%', '-', '`': - //} - if !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '-' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}' || parser.buffer[parser.buffer_pos] == '#' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '*' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '|' || - parser.buffer[parser.buffer_pos] == '>' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '"' || parser.buffer[parser.buffer_pos] == '%' || - parser.buffer[parser.buffer_pos] == '@' || parser.buffer[parser.buffer_pos] == '`') || - (parser.buffer[parser.buffer_pos] == '-' && !is_blank(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level == 0 && - (parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == ':') && - !is_blankz(parser.buffer, parser.buffer_pos+1)) { - return yaml_parser_fetch_plain_scalar(parser) - } - - // If we don't determine the token type so far, it is an error. - return yaml_parser_set_scanner_error(parser, - "while scanning for the next token", parser.mark, - "found character that cannot start any token") -} - -// Check the list of potential simple keys and remove the positions that -// cannot contain simple keys anymore. -func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { - // Check for a potential simple key for each flow level. - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - - // The specification requires that a simple key - // - // - is limited to a single line, - // - is shorter than 1024 characters. - if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { - - // Check if the potential simple key to be removed is required. - if simple_key.required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false - } - } - return true -} - -// Check if a simple key may start at the current position and add it if -// needed. -func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { - // A simple key is required at the current position if the scanner is in - // the block context and the current column coincides with the indentation - // level. - - required := parser.flow_level == 0 && parser.indent == parser.mark.column - - // A simple key is required only when it is the first token in the current - // line. Therefore it is always allowed. But we add a check anyway. - if required && !parser.simple_key_allowed { - panic("should not happen") - } - - // - // If the current position may start a simple key, save it. - // - if parser.simple_key_allowed { - simple_key := yaml_simple_key_t{ - possible: true, - required: required, - token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), - } - simple_key.mark = parser.mark - - if !yaml_parser_remove_simple_key(parser) { - return false - } - parser.simple_keys[len(parser.simple_keys)-1] = simple_key - } - return true -} - -// Remove a potential simple key at the current flow level. -func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { - i := len(parser.simple_keys) - 1 - if parser.simple_keys[i].possible { - // If the key is required, it is an error. - if parser.simple_keys[i].required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", parser.simple_keys[i].mark, - "could not find expected ':'") - } - } - // Remove the key from the stack. - parser.simple_keys[i].possible = false - return true -} - -// Increase the flow level and resize the simple key list if needed. -func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { - // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // Increase the flow level. - parser.flow_level++ - return true -} - -// Decrease the flow level. -func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { - if parser.flow_level > 0 { - parser.flow_level-- - parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] - } - return true -} - -// Push the current indentation level to the stack and set the new level -// the current column is greater than the indentation level. In this case, -// append or insert the specified token into the token queue. -func yaml_parser_roll_indent(parser *yaml_parser_t, column, number int, typ yaml_token_type_t, mark yaml_mark_t) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - if parser.indent < column { - // Push the current indentation level to the stack and set the new - // indentation level. - parser.indents = append(parser.indents, parser.indent) - parser.indent = column - - // Create a token and insert it into the queue. - token := yaml_token_t{ - typ: typ, - start_mark: mark, - end_mark: mark, - } - if number > -1 { - number -= parser.tokens_parsed - } - yaml_insert_token(parser, number, &token) - } - return true -} - -// Pop indentation levels from the indents stack until the current level -// becomes less or equal to the column. For each indentation level, append -// the BLOCK-END token. -func yaml_parser_unroll_indent(parser *yaml_parser_t, column int) bool { - // In the flow context, do nothing. - if parser.flow_level > 0 { - return true - } - - // Loop through the indentation levels in the stack. - for parser.indent > column { - // Create a token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - - // Pop the indentation level. - parser.indent = parser.indents[len(parser.indents)-1] - parser.indents = parser.indents[:len(parser.indents)-1] - } - return true -} - -// Initialize the scanner and produce the STREAM-START token. -func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { - - // Set the initial indentation. - parser.indent = -1 - - // Initialize the simple key stack. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) - - // A simple key is allowed at the beginning of the stream. - parser.simple_key_allowed = true - - // We have started. - parser.stream_start_produced = true - - // Create the STREAM-START token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_START_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - encoding: parser.encoding, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the STREAM-END token and shut down the scanner. -func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool { - - // Force new line. - if parser.mark.column != 0 { - parser.mark.column = 0 - parser.mark.line++ - } - - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the STREAM-END token and append it to the queue. - token := yaml_token_t{ - typ: yaml_STREAM_END_TOKEN, - start_mark: parser.mark, - end_mark: parser.mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce a VERSION-DIRECTIVE or TAG-DIRECTIVE token. -func yaml_parser_fetch_directive(parser *yaml_parser_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Create the YAML-DIRECTIVE or TAG-DIRECTIVE token. - token := yaml_token_t{} - if !yaml_parser_scan_directive(parser, &token) { - return false - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the DOCUMENT-START or DOCUMENT-END token. -func yaml_parser_fetch_document_indicator(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset the indentation level. - if !yaml_parser_unroll_indent(parser, -1) { - return false - } - - // Reset simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - parser.simple_key_allowed = false - - // Consume the token. - start_mark := parser.mark - - skip(parser) - skip(parser) - skip(parser) - - end_mark := parser.mark - - // Create the DOCUMENT-START or DOCUMENT-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-START or FLOW-MAPPING-START token. -func yaml_parser_fetch_flow_collection_start(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // The indicators '[' and '{' may start a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // Increase the flow level. - if !yaml_parser_increase_flow_level(parser) { - return false - } - - // A simple key may follow the indicators '[' and '{'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-START of FLOW-MAPPING-START token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-SEQUENCE-END or FLOW-MAPPING-END token. -func yaml_parser_fetch_flow_collection_end(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // Reset any potential simple key on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Decrease the flow level. - if !yaml_parser_decrease_flow_level(parser) { - return false - } - - // No simple keys after the indicators ']' and '}'. - parser.simple_key_allowed = false - - // Consume the token. - - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-SEQUENCE-END of FLOW-MAPPING-END token. - token := yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - } - // Append the token to the queue. - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the FLOW-ENTRY token. -func yaml_parser_fetch_flow_entry(parser *yaml_parser_t) bool { - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after ','. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the FLOW-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_FLOW_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the BLOCK-ENTRY token. -func yaml_parser_fetch_block_entry(parser *yaml_parser_t) bool { - // Check if the scanner is in the block context. - if parser.flow_level == 0 { - // Check if we are allowed to start a new entry. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "block sequence entries are not allowed in this context") - } - // Add the BLOCK-SEQUENCE-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_SEQUENCE_START_TOKEN, parser.mark) { - return false - } - } else { - // It is an error for the '-' indicator to occur in the flow context, - // but we let the Parser detect and report about it because the Parser - // is able to point to the context. - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '-'. - parser.simple_key_allowed = true - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the BLOCK-ENTRY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_BLOCK_ENTRY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the KEY token. -func yaml_parser_fetch_key(parser *yaml_parser_t) bool { - - // In the block context, additional checks are required. - if parser.flow_level == 0 { - // Check if we are allowed to start a new key (not nessesary simple). - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping keys are not allowed in this context") - } - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Reset any potential simple keys on the current flow level. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // Simple keys are allowed after '?' in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the KEY token and append it to the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the VALUE token. -func yaml_parser_fetch_value(parser *yaml_parser_t) bool { - - simple_key := &parser.simple_keys[len(parser.simple_keys)-1] - - // Have we found a simple key? - if simple_key.possible { - // Create the KEY token and insert it into the queue. - token := yaml_token_t{ - typ: yaml_KEY_TOKEN, - start_mark: simple_key.mark, - end_mark: simple_key.mark, - } - yaml_insert_token(parser, simple_key.token_number-parser.tokens_parsed, &token) - - // In the block context, we may need to add the BLOCK-MAPPING-START token. - if !yaml_parser_roll_indent(parser, simple_key.mark.column, - simple_key.token_number, - yaml_BLOCK_MAPPING_START_TOKEN, simple_key.mark) { - return false - } - - // Remove the simple key. - simple_key.possible = false - - // A simple key cannot follow another simple key. - parser.simple_key_allowed = false - - } else { - // The ':' indicator follows a complex key. - - // In the block context, extra checks are required. - if parser.flow_level == 0 { - - // Check if we are allowed to start a complex value. - if !parser.simple_key_allowed { - return yaml_parser_set_scanner_error(parser, "", parser.mark, - "mapping values are not allowed in this context") - } - - // Add the BLOCK-MAPPING-START token if needed. - if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) { - return false - } - } - - // Simple keys after ':' are allowed in the block context. - parser.simple_key_allowed = parser.flow_level == 0 - } - - // Consume the token. - start_mark := parser.mark - skip(parser) - end_mark := parser.mark - - // Create the VALUE token and append it to the queue. - token := yaml_token_t{ - typ: yaml_VALUE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the ALIAS or ANCHOR token. -func yaml_parser_fetch_anchor(parser *yaml_parser_t, typ yaml_token_type_t) bool { - // An anchor or an alias could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow an anchor or an alias. - parser.simple_key_allowed = false - - // Create the ALIAS or ANCHOR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_anchor(parser, &token, typ) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the TAG token. -func yaml_parser_fetch_tag(parser *yaml_parser_t) bool { - // A tag could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a tag. - parser.simple_key_allowed = false - - // Create the TAG token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_tag(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,literal) or SCALAR(...,folded) tokens. -func yaml_parser_fetch_block_scalar(parser *yaml_parser_t, literal bool) bool { - // Remove any potential simple keys. - if !yaml_parser_remove_simple_key(parser) { - return false - } - - // A simple key may follow a block scalar. - parser.simple_key_allowed = true - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_block_scalar(parser, &token, literal) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,single-quoted) or SCALAR(...,double-quoted) tokens. -func yaml_parser_fetch_flow_scalar(parser *yaml_parser_t, single bool) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_flow_scalar(parser, &token, single) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Produce the SCALAR(...,plain) token. -func yaml_parser_fetch_plain_scalar(parser *yaml_parser_t) bool { - // A plain scalar could be a simple key. - if !yaml_parser_save_simple_key(parser) { - return false - } - - // A simple key cannot follow a flow scalar. - parser.simple_key_allowed = false - - // Create the SCALAR token and append it to the queue. - var token yaml_token_t - if !yaml_parser_scan_plain_scalar(parser, &token) { - return false - } - yaml_insert_token(parser, -1, &token) - return true -} - -// Eat whitespaces and comments until the next token is found. -func yaml_parser_scan_to_next_token(parser *yaml_parser_t) bool { - - // Until the next token is not found. - for { - // Allow the BOM mark to start a line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.mark.column == 0 && is_bom(parser.buffer, parser.buffer_pos) { - skip(parser) - } - - // Eat whitespaces. - // Tabs are allowed: - // - in the flow context - // - in the block context, but not at the beginning of the line or - // after '-', '?', or ':' (complex value). - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for parser.buffer[parser.buffer_pos] == ' ' || ((parser.flow_level > 0 || !parser.simple_key_allowed) && parser.buffer[parser.buffer_pos] == '\t') { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Eat a comment until a line break. - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // If it is a line break, eat it. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - - // In the block context, a new line may start a simple key. - if parser.flow_level == 0 { - parser.simple_key_allowed = true - } - } else { - break // We have found a token. - } - } - - return true -} - -// Scan a YAML-DIRECTIVE or TAG-DIRECTIVE token. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_directive(parser *yaml_parser_t, token *yaml_token_t) bool { - // Eat '%'. - start_mark := parser.mark - skip(parser) - - // Scan the directive name. - var name []byte - if !yaml_parser_scan_directive_name(parser, start_mark, &name) { - return false - } - - // Is it a YAML directive? - if bytes.Equal(name, []byte("YAML")) { - // Scan the VERSION directive value. - var major, minor int8 - if !yaml_parser_scan_version_directive_value(parser, start_mark, &major, &minor) { - return false - } - end_mark := parser.mark - - // Create a VERSION-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_VERSION_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - major: major, - minor: minor, - } - - // Is it a TAG directive? - } else if bytes.Equal(name, []byte("TAG")) { - // Scan the TAG directive value. - var handle, prefix []byte - if !yaml_parser_scan_tag_directive_value(parser, start_mark, &handle, &prefix) { - return false - } - end_mark := parser.mark - - // Create a TAG-DIRECTIVE token. - *token = yaml_token_t{ - typ: yaml_TAG_DIRECTIVE_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - prefix: prefix, - } - - // Unknown directive. - } else { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unknown directive name") - return false - } - - // Eat the rest of the line including any comments. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - return true -} - -// Scan the directive name. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^ -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^ -// -func yaml_parser_scan_directive_name(parser *yaml_parser_t, start_mark yaml_mark_t, name *[]byte) bool { - // Consume the directive name. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - var s []byte - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the name is empty. - if len(s) == 0 { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "could not find expected directive name") - return false - } - - // Check for an blank character after the name. - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a directive", - start_mark, "found unexpected non-alphabetical character") - return false - } - *name = s - return true -} - -// Scan the value of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^^^^^^ -func yaml_parser_scan_version_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, major, minor *int8) bool { - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the major version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, major) { - return false - } - - // Eat '.'. - if parser.buffer[parser.buffer_pos] != '.' { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected digit or '.' character") - } - - skip(parser) - - // Consume the minor version number. - if !yaml_parser_scan_version_directive_number(parser, start_mark, minor) { - return false - } - return true -} - -const max_number_length = 2 - -// Scan the version number of VERSION-DIRECTIVE. -// -// Scope: -// %YAML 1.1 # a comment \n -// ^ -// %YAML 1.1 # a comment \n -// ^ -func yaml_parser_scan_version_directive_number(parser *yaml_parser_t, start_mark yaml_mark_t, number *int8) bool { - - // Repeat while the next character is digit. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var value, length int8 - for is_digit(parser.buffer, parser.buffer_pos) { - // Check if the number is too long. - length++ - if length > max_number_length { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "found extremely long version number") - } - value = value*10 + int8(as_digit(parser.buffer, parser.buffer_pos)) - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the number was present. - if length == 0 { - return yaml_parser_set_scanner_error(parser, "while scanning a %YAML directive", - start_mark, "did not find expected version number") - } - *number = value - return true -} - -// Scan the value of a TAG-DIRECTIVE token. -// -// Scope: -// %TAG !yaml! tag:yaml.org,2002: \n -// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -// -func yaml_parser_scan_tag_directive_value(parser *yaml_parser_t, start_mark yaml_mark_t, handle, prefix *[]byte) bool { - var handle_value, prefix_value []byte - - // Eat whitespaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a handle. - if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { - return false - } - - // Expect a whitespace. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blank(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace") - return false - } - - // Eat whitespaces. - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Scan a prefix. - if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { - return false - } - - // Expect a whitespace or line break. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a %TAG directive", - start_mark, "did not find expected whitespace or line break") - return false - } - - *handle = handle_value - *prefix = prefix_value - return true -} - -func yaml_parser_scan_anchor(parser *yaml_parser_t, token *yaml_token_t, typ yaml_token_type_t) bool { - var s []byte - - // Eat the indicator character. - start_mark := parser.mark - skip(parser) - - // Consume the value. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - end_mark := parser.mark - - /* - * Check if length of the anchor is greater than 0 and it is followed by - * a whitespace character or one of the indicators: - * - * '?', ':', ',', ']', '}', '%', '@', '`'. - */ - - if len(s) == 0 || - !(is_blankz(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == ',' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '}' || - parser.buffer[parser.buffer_pos] == '%' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '`') { - context := "while scanning an alias" - if typ == yaml_ANCHOR_TOKEN { - context = "while scanning an anchor" - } - yaml_parser_set_scanner_error(parser, context, start_mark, - "did not find expected alphabetic or numeric character") - return false - } - - // Create a token. - *token = yaml_token_t{ - typ: typ, - start_mark: start_mark, - end_mark: end_mark, - value: s, - } - - return true -} - -/* - * Scan a TAG token. - */ - -func yaml_parser_scan_tag(parser *yaml_parser_t, token *yaml_token_t) bool { - var handle, suffix []byte - - start_mark := parser.mark - - // Check if the tag is in the canonical form. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - if parser.buffer[parser.buffer_pos+1] == '<' { - // Keep the handle as '' - - // Eat '!<' - skip(parser) - skip(parser) - - // Consume the tag value. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - - // Check for '>' and eat it. - if parser.buffer[parser.buffer_pos] != '>' { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find the expected '>'") - return false - } - - skip(parser) - } else { - // The tag has either the '!suffix' or the '!handle!suffix' form. - - // First, try to scan a handle. - if !yaml_parser_scan_tag_handle(parser, false, start_mark, &handle) { - return false - } - - // Check if it is, indeed, handle. - if handle[0] == '!' && len(handle) > 1 && handle[len(handle)-1] == '!' { - // Scan the suffix now. - if !yaml_parser_scan_tag_uri(parser, false, nil, start_mark, &suffix) { - return false - } - } else { - // It wasn't a handle after all. Scan the rest of the tag. - if !yaml_parser_scan_tag_uri(parser, false, handle, start_mark, &suffix) { - return false - } - - // Set the handle to '!'. - handle = []byte{'!'} - - // A special case: the '!' tag. Set the handle to '' and the - // suffix to '!'. - if len(suffix) == 0 { - handle, suffix = suffix, handle - } - } - } - - // Check the character which ends the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if !is_blankz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a tag", - start_mark, "did not find expected whitespace or line break") - return false - } - - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_TAG_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: handle, - suffix: suffix, - } - return true -} - -// Scan a tag handle. -func yaml_parser_scan_tag_handle(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, handle *[]byte) bool { - // Check the initial '!' character. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] != '!' { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - - var s []byte - - // Copy the '!' character. - s = read(parser, s) - - // Copy all subsequent alphabetical and numerical characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_alpha(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check if the trailing character is '!' and copy it. - if parser.buffer[parser.buffer_pos] == '!' { - s = read(parser, s) - } else { - // It's either the '!' tag or not really a tag handle. If it's a %TAG - // directive, it's an error. If it's a tag token, it must be a part of URI. - if directive && string(s) != "!" { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected '!'") - return false - } - } - - *handle = s - return true -} - -// Scan a tag. -func yaml_parser_scan_tag_uri(parser *yaml_parser_t, directive bool, head []byte, start_mark yaml_mark_t, uri *[]byte) bool { - //size_t length = head ? strlen((char *)head) : 0 - var s []byte - hasTag := len(head) > 0 - - // Copy the head if needed. - // - // Note that we don't copy the leading '!' character. - if len(head) > 1 { - s = append(s, head[1:]...) - } - - // Scan the tag. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // The set of characters that may appear in URI is as follows: - // - // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', - // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', - // '%'. - // [Go] Convert this into more reasonable logic. - for is_alpha(parser.buffer, parser.buffer_pos) || parser.buffer[parser.buffer_pos] == ';' || - parser.buffer[parser.buffer_pos] == '/' || parser.buffer[parser.buffer_pos] == '?' || - parser.buffer[parser.buffer_pos] == ':' || parser.buffer[parser.buffer_pos] == '@' || - parser.buffer[parser.buffer_pos] == '&' || parser.buffer[parser.buffer_pos] == '=' || - parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '$' || - parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == '.' || - parser.buffer[parser.buffer_pos] == '!' || parser.buffer[parser.buffer_pos] == '~' || - parser.buffer[parser.buffer_pos] == '*' || parser.buffer[parser.buffer_pos] == '\'' || - parser.buffer[parser.buffer_pos] == '(' || parser.buffer[parser.buffer_pos] == ')' || - parser.buffer[parser.buffer_pos] == '[' || parser.buffer[parser.buffer_pos] == ']' || - parser.buffer[parser.buffer_pos] == '%' { - // Check if it is a URI-escape sequence. - if parser.buffer[parser.buffer_pos] == '%' { - if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { - return false - } - } else { - s = read(parser, s) - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - hasTag = true - } - - if !hasTag { - yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find expected tag URI") - return false - } - *uri = s - return true -} - -// Decode an URI-escape sequence corresponding to a single UTF-8 character. -func yaml_parser_scan_uri_escapes(parser *yaml_parser_t, directive bool, start_mark yaml_mark_t, s *[]byte) bool { - - // Decode the required number of characters. - w := 1024 - for w > 0 { - // Check for a URI-escaped octet. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - - if !(parser.buffer[parser.buffer_pos] == '%' && - is_hex(parser.buffer, parser.buffer_pos+1) && - is_hex(parser.buffer, parser.buffer_pos+2)) { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "did not find URI escaped octet") - } - - // Get the octet. - octet := byte((as_hex(parser.buffer, parser.buffer_pos+1) << 4) + as_hex(parser.buffer, parser.buffer_pos+2)) - - // If it is the leading octet, determine the length of the UTF-8 sequence. - if w == 1024 { - w = width(octet) - if w == 0 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect leading UTF-8 octet") - } - } else { - // Check if the trailing octet is correct. - if octet&0xC0 != 0x80 { - return yaml_parser_set_scanner_tag_error(parser, directive, - start_mark, "found an incorrect trailing UTF-8 octet") - } - } - - // Copy the octet and move the pointers. - *s = append(*s, octet) - skip(parser) - skip(parser) - skip(parser) - w-- - } - return true -} - -// Scan a block scalar. -func yaml_parser_scan_block_scalar(parser *yaml_parser_t, token *yaml_token_t, literal bool) bool { - // Eat the indicator '|' or '>'. - start_mark := parser.mark - skip(parser) - - // Scan the additional block scalar indicators. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - // Check for a chomping indicator. - var chomping, increment int - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - // Set the chomping method and eat the indicator. - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - - // Check for an indentation indicator. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if is_digit(parser.buffer, parser.buffer_pos) { - // Check that the indentation is greater than 0. - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - - // Get the indentation level and eat the indicator. - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - } - - } else if is_digit(parser.buffer, parser.buffer_pos) { - // Do the same as above, but in the opposite order. - - if parser.buffer[parser.buffer_pos] == '0' { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found an indentation indicator equal to 0") - return false - } - increment = as_digit(parser.buffer, parser.buffer_pos) - skip(parser) - - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - if parser.buffer[parser.buffer_pos] == '+' || parser.buffer[parser.buffer_pos] == '-' { - if parser.buffer[parser.buffer_pos] == '+' { - chomping = +1 - } else { - chomping = -1 - } - skip(parser) - } - } - - // Eat whitespaces and comments to the end of the line. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for is_blank(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.buffer[parser.buffer_pos] == '#' { - for !is_breakz(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - } - - // Check if we are at the end of the line. - if !is_breakz(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "did not find expected comment or line break") - return false - } - - // Eat a line break. - if is_break(parser.buffer, parser.buffer_pos) { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - skip_line(parser) - } - - end_mark := parser.mark - - // Set the indentation level if it was specified. - var indent int - if increment > 0 { - if parser.indent >= 0 { - indent = parser.indent + increment - } else { - indent = increment - } - } - - // Scan the leading line breaks and determine the indentation level if needed. - var s, leading_break, trailing_breaks []byte - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - - // Scan the block scalar content. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - var leading_blank, trailing_blank bool - for parser.mark.column == indent && !is_z(parser.buffer, parser.buffer_pos) { - // We are at the beginning of a non-empty line. - - // Is it a trailing whitespace? - trailing_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Check if we need to fold the leading line break. - if !literal && !leading_blank && !trailing_blank && len(leading_break) > 0 && leading_break[0] == '\n' { - // Do we need to join the lines by space? - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } - } else { - s = append(s, leading_break...) - } - leading_break = leading_break[:0] - - // Append the remaining line breaks. - s = append(s, trailing_breaks...) - trailing_breaks = trailing_breaks[:0] - - // Is it a leading whitespace? - leading_blank = is_blank(parser.buffer, parser.buffer_pos) - - // Consume the current line. - for !is_breakz(parser.buffer, parser.buffer_pos) { - s = read(parser, s) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - leading_break = read_line(parser, leading_break) - - // Eat the following indentation spaces and line breaks. - if !yaml_parser_scan_block_scalar_breaks(parser, &indent, &trailing_breaks, start_mark, &end_mark) { - return false - } - } - - // Chomp the tail. - if chomping != -1 { - s = append(s, leading_break...) - } - if chomping == 1 { - s = append(s, trailing_breaks...) - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_LITERAL_SCALAR_STYLE, - } - if !literal { - token.style = yaml_FOLDED_SCALAR_STYLE - } - return true -} - -// Scan indentation spaces and line breaks for a block scalar. Determine the -// indentation level if needed. -func yaml_parser_scan_block_scalar_breaks(parser *yaml_parser_t, indent *int, breaks *[]byte, start_mark yaml_mark_t, end_mark *yaml_mark_t) bool { - *end_mark = parser.mark - - // Eat the indentation spaces and line breaks. - max_indent := 0 - for { - // Eat the indentation spaces. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer, parser.buffer_pos) { - skip(parser) - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - if parser.mark.column > max_indent { - max_indent = parser.mark.column - } - - // Check for a tab character messing the indentation. - if (*indent == 0 || parser.mark.column < *indent) && is_tab(parser.buffer, parser.buffer_pos) { - return yaml_parser_set_scanner_error(parser, "while scanning a block scalar", - start_mark, "found a tab character where an indentation space is expected") - } - - // Have we found a non-empty line? - if !is_break(parser.buffer, parser.buffer_pos) { - break - } - - // Consume the line break. - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - // [Go] Should really be returning breaks instead. - *breaks = read_line(parser, *breaks) - *end_mark = parser.mark - } - - // Determine the indentation level if needed. - if *indent == 0 { - *indent = max_indent - if *indent < parser.indent+1 { - *indent = parser.indent + 1 - } - if *indent < 1 { - *indent = 1 - } - } - return true -} - -// Scan a quoted scalar. -func yaml_parser_scan_flow_scalar(parser *yaml_parser_t, token *yaml_token_t, single bool) bool { - // Eat the left quote. - start_mark := parser.mark - skip(parser) - - // Consume the content of the quoted scalar. - var s, leading_break, trailing_breaks, whitespaces []byte - for { - // Check that there are no document indicators at the beginning of the line. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected document indicator") - return false - } - - // Check for EOF. - if is_z(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a quoted scalar", - start_mark, "found unexpected end of stream") - return false - } - - // Consume non-blank characters. - leading_blanks := false - for !is_blankz(parser.buffer, parser.buffer_pos) { - if single && parser.buffer[parser.buffer_pos] == '\'' && parser.buffer[parser.buffer_pos+1] == '\'' { - // Is is an escaped single quote. - s = append(s, '\'') - skip(parser) - skip(parser) - - } else if single && parser.buffer[parser.buffer_pos] == '\'' { - // It is a right single quote. - break - } else if !single && parser.buffer[parser.buffer_pos] == '"' { - // It is a right double quote. - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break(parser.buffer, parser.buffer_pos+1) { - // It is an escaped line break. - if parser.unread < 3 && !yaml_parser_update_buffer(parser, 3) { - return false - } - skip(parser) - skip_line(parser) - leading_blanks = true - break - - } else if !single && parser.buffer[parser.buffer_pos] == '\\' { - // It is an escape sequence. - code_length := 0 - - // Check the escape character. - switch parser.buffer[parser.buffer_pos+1] { - case '0': - s = append(s, 0) - case 'a': - s = append(s, '\x07') - case 'b': - s = append(s, '\x08') - case 't', '\t': - s = append(s, '\x09') - case 'n': - s = append(s, '\x0A') - case 'v': - s = append(s, '\x0B') - case 'f': - s = append(s, '\x0C') - case 'r': - s = append(s, '\x0D') - case 'e': - s = append(s, '\x1B') - case ' ': - s = append(s, '\x20') - case '"': - s = append(s, '"') - case '\'': - s = append(s, '\'') - case '\\': - s = append(s, '\\') - case 'N': // NEL (#x85) - s = append(s, '\xC2') - s = append(s, '\x85') - case '_': // #xA0 - s = append(s, '\xC2') - s = append(s, '\xA0') - case 'L': // LS (#x2028) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA8') - case 'P': // PS (#x2029) - s = append(s, '\xE2') - s = append(s, '\x80') - s = append(s, '\xA9') - case 'x': - code_length = 2 - case 'u': - code_length = 4 - case 'U': - code_length = 8 - default: - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found unknown escape character") - return false - } - - skip(parser) - skip(parser) - - // Consume an arbitrary escape code. - if code_length > 0 { - var value int - - // Scan the character value. - if parser.unread < code_length && !yaml_parser_update_buffer(parser, code_length) { - return false - } - for k := 0; k < code_length; k++ { - if !is_hex(parser.buffer, parser.buffer_pos+k) { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "did not find expected hexdecimal number") - return false - } - value = (value << 4) + as_hex(parser.buffer, parser.buffer_pos+k) - } - - // Check the value and write the character. - if (value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF { - yaml_parser_set_scanner_error(parser, "while parsing a quoted scalar", - start_mark, "found invalid Unicode character escape code") - return false - } - if value <= 0x7F { - s = append(s, byte(value)) - } else if value <= 0x7FF { - s = append(s, byte(0xC0+(value>>6))) - s = append(s, byte(0x80+(value&0x3F))) - } else if value <= 0xFFFF { - s = append(s, byte(0xE0+(value>>12))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } else { - s = append(s, byte(0xF0+(value>>18))) - s = append(s, byte(0x80+((value>>12)&0x3F))) - s = append(s, byte(0x80+((value>>6)&0x3F))) - s = append(s, byte(0x80+(value&0x3F))) - } - - // Advance the pointer. - for k := 0; k < code_length; k++ { - skip(parser) - } - } - } else { - // It is a non-escaped non-blank character. - s = read(parser, s) - } - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Check if we are at the end of the scalar. - if single { - if parser.buffer[parser.buffer_pos] == '\'' { - break - } - } else { - if parser.buffer[parser.buffer_pos] == '"' { - break - } - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Join the whitespaces or fold line breaks. - if leading_blanks { - // Do we need to fold line breaks? - if len(leading_break) > 0 && leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Eat the right quote. - skip(parser) - end_mark := parser.mark - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_SINGLE_QUOTED_SCALAR_STYLE, - } - if !single { - token.style = yaml_DOUBLE_QUOTED_SCALAR_STYLE - } - return true -} - -// Scan a plain scalar. -func yaml_parser_scan_plain_scalar(parser *yaml_parser_t, token *yaml_token_t) bool { - - var s, leading_break, trailing_breaks, whitespaces []byte - var leading_blanks bool - var indent = parser.indent + 1 - - start_mark := parser.mark - end_mark := parser.mark - - // Consume the content of the plain scalar. - for { - // Check for a document indicator. - if parser.unread < 4 && !yaml_parser_update_buffer(parser, 4) { - return false - } - if parser.mark.column == 0 && - ((parser.buffer[parser.buffer_pos+0] == '-' && - parser.buffer[parser.buffer_pos+1] == '-' && - parser.buffer[parser.buffer_pos+2] == '-') || - (parser.buffer[parser.buffer_pos+0] == '.' && - parser.buffer[parser.buffer_pos+1] == '.' && - parser.buffer[parser.buffer_pos+2] == '.')) && - is_blankz(parser.buffer, parser.buffer_pos+3) { - break - } - - // Check for a comment. - if parser.buffer[parser.buffer_pos] == '#' { - break - } - - // Consume non-blank characters. - for !is_blankz(parser.buffer, parser.buffer_pos) { - - // Check for 'x:x' in the flow context. TODO: Fix the test "spec-08-13". - if parser.flow_level > 0 && - parser.buffer[parser.buffer_pos] == ':' && - !is_blankz(parser.buffer, parser.buffer_pos+1) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found unexpected ':'") - return false - } - - // Check for indicators that may end a plain scalar. - if (parser.buffer[parser.buffer_pos] == ':' && is_blankz(parser.buffer, parser.buffer_pos+1)) || - (parser.flow_level > 0 && - (parser.buffer[parser.buffer_pos] == ',' || parser.buffer[parser.buffer_pos] == ':' || - parser.buffer[parser.buffer_pos] == '?' || parser.buffer[parser.buffer_pos] == '[' || - parser.buffer[parser.buffer_pos] == ']' || parser.buffer[parser.buffer_pos] == '{' || - parser.buffer[parser.buffer_pos] == '}')) { - break - } - - // Check if we need to join whitespaces and breaks. - if leading_blanks || len(whitespaces) > 0 { - if leading_blanks { - // Do we need to fold line breaks? - if leading_break[0] == '\n' { - if len(trailing_breaks) == 0 { - s = append(s, ' ') - } else { - s = append(s, trailing_breaks...) - } - } else { - s = append(s, leading_break...) - s = append(s, trailing_breaks...) - } - trailing_breaks = trailing_breaks[:0] - leading_break = leading_break[:0] - leading_blanks = false - } else { - s = append(s, whitespaces...) - whitespaces = whitespaces[:0] - } - } - - // Copy the character. - s = read(parser, s) - - end_mark = parser.mark - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - } - - // Is it the end? - if !(is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos)) { - break - } - - // Consume blank characters. - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - - for is_blank(parser.buffer, parser.buffer_pos) || is_break(parser.buffer, parser.buffer_pos) { - if is_blank(parser.buffer, parser.buffer_pos) { - - // Check for tab character that abuse indentation. - if leading_blanks && parser.mark.column < indent && is_tab(parser.buffer, parser.buffer_pos) { - yaml_parser_set_scanner_error(parser, "while scanning a plain scalar", - start_mark, "found a tab character that violate indentation") - return false - } - - // Consume a space or a tab character. - if !leading_blanks { - whitespaces = read(parser, whitespaces) - } else { - skip(parser) - } - } else { - if parser.unread < 2 && !yaml_parser_update_buffer(parser, 2) { - return false - } - - // Check if it is a first line break. - if !leading_blanks { - whitespaces = whitespaces[:0] - leading_break = read_line(parser, leading_break) - leading_blanks = true - } else { - trailing_breaks = read_line(parser, trailing_breaks) - } - } - if parser.unread < 1 && !yaml_parser_update_buffer(parser, 1) { - return false - } - } - - // Check indentation level. - if parser.flow_level == 0 && parser.mark.column < indent { - break - } - } - - // Create a token. - *token = yaml_token_t{ - typ: yaml_SCALAR_TOKEN, - start_mark: start_mark, - end_mark: end_mark, - value: s, - style: yaml_PLAIN_SCALAR_STYLE, - } - - // Note that we change the 'simple_key_allowed' flag. - if leading_blanks { - parser.simple_key_allowed = true - } - return true -} diff --git a/vendor/github.com/sanathkr/go-yaml/sorter.go b/vendor/github.com/sanathkr/go-yaml/sorter.go deleted file mode 100644 index 5958822f9c..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/sorter.go +++ /dev/null @@ -1,104 +0,0 @@ -package yaml - -import ( - "reflect" - "unicode" -) - -type keyList []reflect.Value - -func (l keyList) Len() int { return len(l) } -func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l keyList) Less(i, j int) bool { - a := l[i] - b := l[j] - ak := a.Kind() - bk := b.Kind() - for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() { - a = a.Elem() - ak = a.Kind() - } - for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() { - b = b.Elem() - bk = b.Kind() - } - af, aok := keyFloat(a) - bf, bok := keyFloat(b) - if aok && bok { - if af != bf { - return af < bf - } - if ak != bk { - return ak < bk - } - return numLess(a, b) - } - if ak != reflect.String || bk != reflect.String { - return ak < bk - } - ar, br := []rune(a.String()), []rune(b.String()) - for i := 0; i < len(ar) && i < len(br); i++ { - if ar[i] == br[i] { - continue - } - al := unicode.IsLetter(ar[i]) - bl := unicode.IsLetter(br[i]) - if al && bl { - return ar[i] < br[i] - } - if al || bl { - return bl - } - var ai, bi int - var an, bn int64 - for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ { - an = an*10 + int64(ar[ai]-'0') - } - for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ { - bn = bn*10 + int64(br[bi]-'0') - } - if an != bn { - return an < bn - } - if ai != bi { - return ai < bi - } - return ar[i] < br[i] - } - return len(ar) < len(br) -} - -// keyFloat returns a float value for v if it is a number/bool -// and whether it is a number/bool or not. -func keyFloat(v reflect.Value) (f float64, ok bool) { - switch v.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return float64(v.Int()), true - case reflect.Float32, reflect.Float64: - return v.Float(), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return float64(v.Uint()), true - case reflect.Bool: - if v.Bool() { - return 1, true - } - return 0, true - } - return 0, false -} - -// numLess returns whether a < b. -// a and b must necessarily have the same kind. -func numLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return a.Int() < b.Int() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Bool: - return !a.Bool() && b.Bool() - } - panic("not a number") -} diff --git a/vendor/github.com/sanathkr/go-yaml/writerc.go b/vendor/github.com/sanathkr/go-yaml/writerc.go deleted file mode 100644 index 190362f25d..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/writerc.go +++ /dev/null @@ -1,89 +0,0 @@ -package yaml - -// Set the writer error and return false. -func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool { - emitter.error = yaml_WRITER_ERROR - emitter.problem = problem - return false -} - -// Flush the output buffer. -func yaml_emitter_flush(emitter *yaml_emitter_t) bool { - if emitter.write_handler == nil { - panic("write handler not set") - } - - // Check if the buffer is empty. - if emitter.buffer_pos == 0 { - return true - } - - // If the output encoding is UTF-8, we don't need to recode the buffer. - if emitter.encoding == yaml_UTF8_ENCODING { - if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - return true - } - - // Recode the buffer into the raw buffer. - var low, high int - if emitter.encoding == yaml_UTF16LE_ENCODING { - low, high = 0, 1 - } else { - high, low = 1, 0 - } - - pos := 0 - for pos < emitter.buffer_pos { - // See the "reader.c" code for more details on UTF-8 encoding. Note - // that we assume that the buffer contains a valid UTF-8 sequence. - - // Read the next UTF-8 character. - octet := emitter.buffer[pos] - - var w int - var value rune - switch { - case octet&0x80 == 0x00: - w, value = 1, rune(octet&0x7F) - case octet&0xE0 == 0xC0: - w, value = 2, rune(octet&0x1F) - case octet&0xF0 == 0xE0: - w, value = 3, rune(octet&0x0F) - case octet&0xF8 == 0xF0: - w, value = 4, rune(octet&0x07) - } - for k := 1; k < w; k++ { - octet = emitter.buffer[pos+k] - value = (value << 6) + (rune(octet) & 0x3F) - } - pos += w - - // Write the character. - if value < 0x10000 { - var b [2]byte - b[high] = byte(value >> 8) - b[low] = byte(value & 0xFF) - emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1]) - } else { - // Write the character using a surrogate pair (check "reader.c"). - var b [4]byte - value -= 0x10000 - b[high] = byte(0xD8 + (value >> 18)) - b[low] = byte((value >> 10) & 0xFF) - b[high+2] = byte(0xDC + ((value >> 8) & 0xFF)) - b[low+2] = byte(value & 0xFF) - emitter.raw_buffer = append(emitter.raw_buffer, b[0], b[1], b[2], b[3]) - } - } - - // Write the raw buffer. - if err := emitter.write_handler(emitter, emitter.raw_buffer); err != nil { - return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error()) - } - emitter.buffer_pos = 0 - emitter.raw_buffer = emitter.raw_buffer[:0] - return true -} diff --git a/vendor/github.com/sanathkr/go-yaml/yaml.go b/vendor/github.com/sanathkr/go-yaml/yaml.go deleted file mode 100644 index ed487525cf..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/yaml.go +++ /dev/null @@ -1,374 +0,0 @@ -// Package yaml implements YAML support for the Go language. -// -// Source code and other details for the project are available at GitHub: -// -// https://github.com/go-yaml/yaml -// -package yaml - -import ( - "errors" - "fmt" - "reflect" - "strings" - "sync" -) - -// MapSlice encodes and decodes as a YAML map. -// The order of keys is preserved when encoding and decoding. -type MapSlice []MapItem - -// MapItem is an item in a MapSlice. -type MapItem struct { - Key, Value interface{} -} - -// The Unmarshaler interface may be implemented by types to customize their -// behavior when being unmarshaled from a YAML document. The UnmarshalYAML -// method receives a function that may be called to unmarshal the original -// YAML value into a field or variable. It is safe to call the unmarshal -// function parameter more than once if necessary. -type Unmarshaler interface { - UnmarshalYAML(unmarshal func(interface{}) error) error -} - -type TagUnmarshallerDecoder struct { - d *decoder -} - -// The Tag Unmarshaler interface -type TagUnmarshaler interface { - UnmarshalYAMLTag(tag string, out reflect.Value) reflect.Value -} - -// The Marshaler interface may be implemented by types to customize their -// behavior when being marshaled into a YAML document. The returned value -// is marshaled in place of the original value implementing Marshaler. -// -// If an error is returned by MarshalYAML, the marshaling procedure stops -// and returns with the provided error. -type Marshaler interface { - MarshalYAML() (interface{}, error) -} - -// Unmarshal decodes the first document found within the in byte slice -// and assigns decoded values into the out value. -// -// Maps and pointers (to a struct, string, int, etc) are accepted as out -// values. If an internal pointer within a struct is not initialized, -// the yaml package will initialize it if necessary for unmarshalling -// the provided data. The out parameter must not be nil. -// -// The type of the decoded values should be compatible with the respective -// values in out. If one or more values cannot be decoded due to a type -// mismatches, decoding continues partially until the end of the YAML -// content, and a *yaml.TypeError is returned with details for all -// missed values. -// -// Struct fields are only unmarshalled if they are exported (have an -// upper case first letter), and are unmarshalled using the field name -// lowercased as the default key. Custom keys may be defined via the -// "yaml" name in the field tag: the content preceding the first comma -// is used as the key, and the following comma-separated options are -// used to tweak the marshalling process (see Marshal). -// Conflicting names result in a runtime error. -// -// For example: -// -// type T struct { -// F int `yaml:"a,omitempty"` -// B int -// } -// var t T -// yaml.Unmarshal([]byte("a: 1\nb: 2"), &t) -// -// See the documentation of Marshal for the format of tags and a list of -// supported tag options. -// -func Unmarshal(in []byte, out interface{}) (err error) { - return unmarshal(in, out, false) -} - -// UnmarshalStrict is like Unmarshal except that any fields that are found -// in the data that do not have corresponding struct members will result in -// an error. -func UnmarshalStrict(in []byte, out interface{}) (err error) { - return unmarshal(in, out, true) -} - -func unmarshal(in []byte, out interface{}, strict bool) (err error) { - defer handleErr(&err) - d := newDecoder(strict) - p := newParser(in) - defer p.destroy() - node := p.parse() - if node != nil { - v := reflect.ValueOf(out) - if v.Kind() == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - d.unmarshal(node, v) - } - if len(d.terrors) > 0 { - return &TypeError{d.terrors} - } - return nil -} - -// Marshal serializes the value provided into a YAML document. The structure -// of the generated document will reflect the structure of the value itself. -// Maps and pointers (to struct, string, int, etc) are accepted as the in value. -// -// Struct fields are only unmarshalled if they are exported (have an upper case -// first letter), and are unmarshalled using the field name lowercased as the -// default key. Custom keys may be defined via the "yaml" name in the field -// tag: the content preceding the first comma is used as the key, and the -// following comma-separated options are used to tweak the marshalling process. -// Conflicting names result in a runtime error. -// -// The field tag format accepted is: -// -// `(...) yaml:"[][,[,]]" (...)` -// -// The following flags are currently supported: -// -// omitempty Only include the field if it's not set to the zero -// value for the type or to empty slices or maps. -// Does not apply to zero valued structs. -// -// flow Marshal using a flow style (useful for structs, -// sequences and maps). -// -// inline Inline the field, which must be a struct or a map, -// causing all of its fields or keys to be processed as if -// they were part of the outer struct. For maps, keys must -// not conflict with the yaml keys of other struct fields. -// -// In addition, if the key is "-", the field is ignored. -// -// For example: -// -// type T struct { -// F int "a,omitempty" -// B int -// } -// yaml.Marshal(&T{B: 2}) // Returns "b: 2\n" -// yaml.Marshal(&T{F: 1}} // Returns "a: 1\nb: 0\n" -// -func Marshal(in interface{}) (out []byte, err error) { - defer handleErr(&err) - e := newEncoder() - defer e.destroy() - e.marshal("", reflect.ValueOf(in)) - e.finish() - out = e.out - return -} - -func RegisterTagUnmarshaler(tag string, unmarshaler TagUnmarshaler) { - registerCustomTagUnmarshaler(tag, unmarshaler) -} - -func UnRegisterTagUnmarshaler(tag string) { - unregisterCustomTagUnmarshaler(tag) -} - -func handleErr(err *error) { - if v := recover(); v != nil { - if e, ok := v.(yamlError); ok { - *err = e.err - } else { - panic(v) - } - } -} - -type yamlError struct { - err error -} - -func fail(err error) { - panic(yamlError{err}) -} - -func failf(format string, args ...interface{}) { - panic(yamlError{fmt.Errorf("yaml: "+format, args...)}) -} - -// A TypeError is returned by Unmarshal when one or more fields in -// the YAML document cannot be properly decoded into the requested -// types. When this error is returned, the value is still -// unmarshaled partially. -type TypeError struct { - Errors []string -} - -func (e *TypeError) Error() string { - return fmt.Sprintf("yaml: unmarshal errors:\n %s", strings.Join(e.Errors, "\n ")) -} - -// -------------------------------------------------------------------------- -// Maintain a mapping of keys to structure field indexes - -// The code in this section was copied from mgo/bson. - -// structInfo holds details for the serialization of fields of -// a given struct. -type structInfo struct { - FieldsMap map[string]fieldInfo - FieldsList []fieldInfo - - // InlineMap is the number of the field in the struct that - // contains an ,inline map, or -1 if there's none. - InlineMap int -} - -type fieldInfo struct { - Key string - Num int - OmitEmpty bool - Flow bool - - // Inline holds the field index if the field is part of an inlined struct. - Inline []int -} - -var structMap = make(map[reflect.Type]*structInfo) -var fieldMapMutex sync.RWMutex - -func getStructInfo(st reflect.Type) (*structInfo, error) { - fieldMapMutex.RLock() - sinfo, found := structMap[st] - fieldMapMutex.RUnlock() - if found { - return sinfo, nil - } - - n := st.NumField() - fieldsMap := make(map[string]fieldInfo) - fieldsList := make([]fieldInfo, 0, n) - inlineMap := -1 - for i := 0; i != n; i++ { - field := st.Field(i) - if field.PkgPath != "" && !field.Anonymous { - continue // Private field - } - - info := fieldInfo{Num: i} - - tag := field.Tag.Get("yaml") - if tag == "" && strings.Index(string(field.Tag), ":") < 0 { - tag = string(field.Tag) - } - if tag == "-" { - continue - } - - inline := false - fields := strings.Split(tag, ",") - if len(fields) > 1 { - for _, flag := range fields[1:] { - switch flag { - case "omitempty": - info.OmitEmpty = true - case "flow": - info.Flow = true - case "inline": - inline = true - default: - return nil, errors.New(fmt.Sprintf("Unsupported flag %q in tag %q of type %s", flag, tag, st)) - } - } - tag = fields[0] - } - - if inline { - switch field.Type.Kind() { - case reflect.Map: - if inlineMap >= 0 { - return nil, errors.New("Multiple ,inline maps in struct " + st.String()) - } - if field.Type.Key() != reflect.TypeOf("") { - return nil, errors.New("Option ,inline needs a map with string keys in struct " + st.String()) - } - inlineMap = info.Num - case reflect.Struct: - sinfo, err := getStructInfo(field.Type) - if err != nil { - return nil, err - } - for _, finfo := range sinfo.FieldsList { - if _, found := fieldsMap[finfo.Key]; found { - msg := "Duplicated key '" + finfo.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - if finfo.Inline == nil { - finfo.Inline = []int{i, finfo.Num} - } else { - finfo.Inline = append([]int{i}, finfo.Inline...) - } - fieldsMap[finfo.Key] = finfo - fieldsList = append(fieldsList, finfo) - } - default: - //return nil, errors.New("Option ,inline needs a struct value or map field") - return nil, errors.New("Option ,inline needs a struct value field") - } - continue - } - - if tag != "" { - info.Key = tag - } else { - info.Key = strings.ToLower(field.Name) - } - - if _, found = fieldsMap[info.Key]; found { - msg := "Duplicated key '" + info.Key + "' in struct " + st.String() - return nil, errors.New(msg) - } - - fieldsList = append(fieldsList, info) - fieldsMap[info.Key] = info - } - - sinfo = &structInfo{fieldsMap, fieldsList, inlineMap} - - fieldMapMutex.Lock() - structMap[st] = sinfo - fieldMapMutex.Unlock() - return sinfo, nil -} - -func isZero(v reflect.Value) bool { - switch v.Kind() { - case reflect.String: - return len(v.String()) == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflect.Slice: - return v.Len() == 0 - case reflect.Map: - return v.Len() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Struct: - vt := v.Type() - for i := v.NumField() - 1; i >= 0; i-- { - if vt.Field(i).PkgPath != "" { - continue // Private field - } - if !isZero(v.Field(i)) { - return false - } - } - return true - } - return false -} diff --git a/vendor/github.com/sanathkr/go-yaml/yamlh.go b/vendor/github.com/sanathkr/go-yaml/yamlh.go deleted file mode 100644 index 3caeca0491..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/yamlh.go +++ /dev/null @@ -1,716 +0,0 @@ -package yaml - -import ( - "io" -) - -// The version directive data. -type yaml_version_directive_t struct { - major int8 // The major version number. - minor int8 // The minor version number. -} - -// The tag directive data. -type yaml_tag_directive_t struct { - handle []byte // The tag handle. - prefix []byte // The tag prefix. -} - -type yaml_encoding_t int - -// The stream encoding. -const ( - // Let the parser choose the encoding. - yaml_ANY_ENCODING yaml_encoding_t = iota - - yaml_UTF8_ENCODING // The default UTF-8 encoding. - yaml_UTF16LE_ENCODING // The UTF-16-LE encoding with BOM. - yaml_UTF16BE_ENCODING // The UTF-16-BE encoding with BOM. -) - -type yaml_break_t int - -// Line break types. -const ( - // Let the parser choose the break type. - yaml_ANY_BREAK yaml_break_t = iota - - yaml_CR_BREAK // Use CR for line breaks (Mac style). - yaml_LN_BREAK // Use LN for line breaks (Unix style). - yaml_CRLN_BREAK // Use CR LN for line breaks (DOS style). -) - -type yaml_error_type_t int - -// Many bad things could happen with the parser and emitter. -const ( - // No error is produced. - yaml_NO_ERROR yaml_error_type_t = iota - - yaml_MEMORY_ERROR // Cannot allocate or reallocate a block of memory. - yaml_READER_ERROR // Cannot read or decode the input stream. - yaml_SCANNER_ERROR // Cannot scan the input stream. - yaml_PARSER_ERROR // Cannot parse the input stream. - yaml_COMPOSER_ERROR // Cannot compose a YAML document. - yaml_WRITER_ERROR // Cannot write to the output stream. - yaml_EMITTER_ERROR // Cannot emit a YAML stream. -) - -// The pointer position. -type yaml_mark_t struct { - index int // The position index. - line int // The position line. - column int // The position column. -} - -// Node Styles - -type yaml_style_t int8 - -type yaml_scalar_style_t yaml_style_t - -// Scalar styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota - - yaml_PLAIN_SCALAR_STYLE // The plain scalar style. - yaml_SINGLE_QUOTED_SCALAR_STYLE // The single-quoted scalar style. - yaml_DOUBLE_QUOTED_SCALAR_STYLE // The double-quoted scalar style. - yaml_LITERAL_SCALAR_STYLE // The literal scalar style. - yaml_FOLDED_SCALAR_STYLE // The folded scalar style. -) - -type yaml_sequence_style_t yaml_style_t - -// Sequence styles. -const ( - // Let the emitter choose the style. - yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota - - yaml_BLOCK_SEQUENCE_STYLE // The block sequence style. - yaml_FLOW_SEQUENCE_STYLE // The flow sequence style. -) - -type yaml_mapping_style_t yaml_style_t - -// Mapping styles. -const ( - // Let the emitter choose the style. - yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota - - yaml_BLOCK_MAPPING_STYLE // The block mapping style. - yaml_FLOW_MAPPING_STYLE // The flow mapping style. -) - -// Tokens - -type yaml_token_type_t int - -// Token types. -const ( - // An empty token. - yaml_NO_TOKEN yaml_token_type_t = iota - - yaml_STREAM_START_TOKEN // A STREAM-START token. - yaml_STREAM_END_TOKEN // A STREAM-END token. - - yaml_VERSION_DIRECTIVE_TOKEN // A VERSION-DIRECTIVE token. - yaml_TAG_DIRECTIVE_TOKEN // A TAG-DIRECTIVE token. - yaml_DOCUMENT_START_TOKEN // A DOCUMENT-START token. - yaml_DOCUMENT_END_TOKEN // A DOCUMENT-END token. - - yaml_BLOCK_SEQUENCE_START_TOKEN // A BLOCK-SEQUENCE-START token. - yaml_BLOCK_MAPPING_START_TOKEN // A BLOCK-SEQUENCE-END token. - yaml_BLOCK_END_TOKEN // A BLOCK-END token. - - yaml_FLOW_SEQUENCE_START_TOKEN // A FLOW-SEQUENCE-START token. - yaml_FLOW_SEQUENCE_END_TOKEN // A FLOW-SEQUENCE-END token. - yaml_FLOW_MAPPING_START_TOKEN // A FLOW-MAPPING-START token. - yaml_FLOW_MAPPING_END_TOKEN // A FLOW-MAPPING-END token. - - yaml_BLOCK_ENTRY_TOKEN // A BLOCK-ENTRY token. - yaml_FLOW_ENTRY_TOKEN // A FLOW-ENTRY token. - yaml_KEY_TOKEN // A KEY token. - yaml_VALUE_TOKEN // A VALUE token. - - yaml_ALIAS_TOKEN // An ALIAS token. - yaml_ANCHOR_TOKEN // An ANCHOR token. - yaml_TAG_TOKEN // A TAG token. - yaml_SCALAR_TOKEN // A SCALAR token. -) - -func (tt yaml_token_type_t) String() string { - switch tt { - case yaml_NO_TOKEN: - return "yaml_NO_TOKEN" - case yaml_STREAM_START_TOKEN: - return "yaml_STREAM_START_TOKEN" - case yaml_STREAM_END_TOKEN: - return "yaml_STREAM_END_TOKEN" - case yaml_VERSION_DIRECTIVE_TOKEN: - return "yaml_VERSION_DIRECTIVE_TOKEN" - case yaml_TAG_DIRECTIVE_TOKEN: - return "yaml_TAG_DIRECTIVE_TOKEN" - case yaml_DOCUMENT_START_TOKEN: - return "yaml_DOCUMENT_START_TOKEN" - case yaml_DOCUMENT_END_TOKEN: - return "yaml_DOCUMENT_END_TOKEN" - case yaml_BLOCK_SEQUENCE_START_TOKEN: - return "yaml_BLOCK_SEQUENCE_START_TOKEN" - case yaml_BLOCK_MAPPING_START_TOKEN: - return "yaml_BLOCK_MAPPING_START_TOKEN" - case yaml_BLOCK_END_TOKEN: - return "yaml_BLOCK_END_TOKEN" - case yaml_FLOW_SEQUENCE_START_TOKEN: - return "yaml_FLOW_SEQUENCE_START_TOKEN" - case yaml_FLOW_SEQUENCE_END_TOKEN: - return "yaml_FLOW_SEQUENCE_END_TOKEN" - case yaml_FLOW_MAPPING_START_TOKEN: - return "yaml_FLOW_MAPPING_START_TOKEN" - case yaml_FLOW_MAPPING_END_TOKEN: - return "yaml_FLOW_MAPPING_END_TOKEN" - case yaml_BLOCK_ENTRY_TOKEN: - return "yaml_BLOCK_ENTRY_TOKEN" - case yaml_FLOW_ENTRY_TOKEN: - return "yaml_FLOW_ENTRY_TOKEN" - case yaml_KEY_TOKEN: - return "yaml_KEY_TOKEN" - case yaml_VALUE_TOKEN: - return "yaml_VALUE_TOKEN" - case yaml_ALIAS_TOKEN: - return "yaml_ALIAS_TOKEN" - case yaml_ANCHOR_TOKEN: - return "yaml_ANCHOR_TOKEN" - case yaml_TAG_TOKEN: - return "yaml_TAG_TOKEN" - case yaml_SCALAR_TOKEN: - return "yaml_SCALAR_TOKEN" - } - return "" -} - -// The token structure. -type yaml_token_t struct { - // The token type. - typ yaml_token_type_t - - // The start/end of the token. - start_mark, end_mark yaml_mark_t - - // The stream encoding (for yaml_STREAM_START_TOKEN). - encoding yaml_encoding_t - - // The alias/anchor/scalar value or tag/tag directive handle - // (for yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN, yaml_TAG_TOKEN, yaml_TAG_DIRECTIVE_TOKEN). - value []byte - - // The tag suffix (for yaml_TAG_TOKEN). - suffix []byte - - // The tag directive prefix (for yaml_TAG_DIRECTIVE_TOKEN). - prefix []byte - - // The scalar style (for yaml_SCALAR_TOKEN). - style yaml_scalar_style_t - - // The version directive major/minor (for yaml_VERSION_DIRECTIVE_TOKEN). - major, minor int8 -} - -// Events - -type yaml_event_type_t int8 - -// Event types. -const ( - // An empty event. - yaml_NO_EVENT yaml_event_type_t = iota - - yaml_STREAM_START_EVENT // A STREAM-START event. - yaml_STREAM_END_EVENT // A STREAM-END event. - yaml_DOCUMENT_START_EVENT // A DOCUMENT-START event. - yaml_DOCUMENT_END_EVENT // A DOCUMENT-END event. - yaml_ALIAS_EVENT // An ALIAS event. - yaml_SCALAR_EVENT // A SCALAR event. - yaml_SEQUENCE_START_EVENT // A SEQUENCE-START event. - yaml_SEQUENCE_END_EVENT // A SEQUENCE-END event. - yaml_MAPPING_START_EVENT // A MAPPING-START event. - yaml_MAPPING_END_EVENT // A MAPPING-END event. -) - -// The event structure. -type yaml_event_t struct { - - // The event type. - typ yaml_event_type_t - - // The start and end of the event. - start_mark, end_mark yaml_mark_t - - // The document encoding (for yaml_STREAM_START_EVENT). - encoding yaml_encoding_t - - // The version directive (for yaml_DOCUMENT_START_EVENT). - version_directive *yaml_version_directive_t - - // The list of tag directives (for yaml_DOCUMENT_START_EVENT). - tag_directives []yaml_tag_directive_t - - // The anchor (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_ALIAS_EVENT). - anchor []byte - - // The tag (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - tag []byte - - // The scalar value (for yaml_SCALAR_EVENT). - value []byte - - // Is the document start/end indicator implicit, or the tag optional? - // (for yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT, yaml_SCALAR_EVENT). - implicit bool - - // Is the tag optional for any non-plain style? (for yaml_SCALAR_EVENT). - quoted_implicit bool - - // The style (for yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). - style yaml_style_t -} - -func (e *yaml_event_t) scalar_style() yaml_scalar_style_t { return yaml_scalar_style_t(e.style) } -func (e *yaml_event_t) sequence_style() yaml_sequence_style_t { return yaml_sequence_style_t(e.style) } -func (e *yaml_event_t) mapping_style() yaml_mapping_style_t { return yaml_mapping_style_t(e.style) } - -// Nodes - -const ( - yaml_NULL_TAG = "tag:yaml.org,2002:null" // The tag !!null with the only possible value: null. - yaml_BOOL_TAG = "tag:yaml.org,2002:bool" // The tag !!bool with the values: true and false. - yaml_STR_TAG = "tag:yaml.org,2002:str" // The tag !!str for string values. - yaml_INT_TAG = "tag:yaml.org,2002:int" // The tag !!int for integer values. - yaml_FLOAT_TAG = "tag:yaml.org,2002:float" // The tag !!float for float values. - yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" // The tag !!timestamp for date and time values. - - yaml_SEQ_TAG = "tag:yaml.org,2002:seq" // The tag !!seq is used to denote sequences. - yaml_MAP_TAG = "tag:yaml.org,2002:map" // The tag !!map is used to denote mapping. - - // Not in original libyaml. - yaml_BINARY_TAG = "tag:yaml.org,2002:binary" - yaml_MERGE_TAG = "tag:yaml.org,2002:merge" - - yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG // The default scalar tag is !!str. - yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG // The default sequence tag is !!seq. - yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG // The default mapping tag is !!map. -) - -type yaml_node_type_t int - -// Node types. -const ( - // An empty node. - yaml_NO_NODE yaml_node_type_t = iota - - yaml_SCALAR_NODE // A scalar node. - yaml_SEQUENCE_NODE // A sequence node. - yaml_MAPPING_NODE // A mapping node. -) - -// An element of a sequence node. -type yaml_node_item_t int - -// An element of a mapping node. -type yaml_node_pair_t struct { - key int // The key of the element. - value int // The value of the element. -} - -// The node structure. -type yaml_node_t struct { - typ yaml_node_type_t // The node type. - tag []byte // The node tag. - - // The node data. - - // The scalar parameters (for yaml_SCALAR_NODE). - scalar struct { - value []byte // The scalar value. - length int // The length of the scalar value. - style yaml_scalar_style_t // The scalar style. - } - - // The sequence parameters (for YAML_SEQUENCE_NODE). - sequence struct { - items_data []yaml_node_item_t // The stack of sequence items. - style yaml_sequence_style_t // The sequence style. - } - - // The mapping parameters (for yaml_MAPPING_NODE). - mapping struct { - pairs_data []yaml_node_pair_t // The stack of mapping pairs (key, value). - pairs_start *yaml_node_pair_t // The beginning of the stack. - pairs_end *yaml_node_pair_t // The end of the stack. - pairs_top *yaml_node_pair_t // The top of the stack. - style yaml_mapping_style_t // The mapping style. - } - - start_mark yaml_mark_t // The beginning of the node. - end_mark yaml_mark_t // The end of the node. - -} - -// The document structure. -type yaml_document_t struct { - - // The document nodes. - nodes []yaml_node_t - - // The version directive. - version_directive *yaml_version_directive_t - - // The list of tag directives. - tag_directives_data []yaml_tag_directive_t - tag_directives_start int // The beginning of the tag directives list. - tag_directives_end int // The end of the tag directives list. - - start_implicit int // Is the document start indicator implicit? - end_implicit int // Is the document end indicator implicit? - - // The start/end of the document. - start_mark, end_mark yaml_mark_t -} - -// The prototype of a read handler. -// -// The read handler is called when the parser needs to read more bytes from the -// source. The handler should write not more than size bytes to the buffer. -// The number of written bytes should be set to the size_read variable. -// -// [in,out] data A pointer to an application data specified by -// yaml_parser_set_input(). -// [out] buffer The buffer to write the data from the source. -// [in] size The size of the buffer. -// [out] size_read The actual number of bytes read from the source. -// -// On success, the handler should return 1. If the handler failed, -// the returned value should be 0. On EOF, the handler should set the -// size_read to 0 and return 1. -type yaml_read_handler_t func(parser *yaml_parser_t, buffer []byte) (n int, err error) - -// This structure holds information about a potential simple key. -type yaml_simple_key_t struct { - possible bool // Is a simple key possible? - required bool // Is a simple key required? - token_number int // The number of the token. - mark yaml_mark_t // The position mark. -} - -// The states of the parser. -type yaml_parser_state_t int - -const ( - yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota - - yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE // Expect the beginning of an implicit document. - yaml_PARSE_DOCUMENT_START_STATE // Expect DOCUMENT-START. - yaml_PARSE_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_PARSE_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_PARSE_BLOCK_NODE_STATE // Expect a block node. - yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE // Expect a block node or indentless sequence. - yaml_PARSE_FLOW_NODE_STATE // Expect a flow node. - yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a block sequence. - yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE // Expect an entry of a block sequence. - yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE // Expect an entry of an indentless sequence. - yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_PARSE_BLOCK_MAPPING_KEY_STATE // Expect a block mapping key. - yaml_PARSE_BLOCK_MAPPING_VALUE_STATE // Expect a block mapping value. - yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE // Expect the first entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE // Expect an entry of a flow sequence. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE // Expect a key of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE // Expect a value of an ordered mapping. - yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE // Expect the and of an ordered mapping entry. - yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_PARSE_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE // Expect an empty value of a flow mapping. - yaml_PARSE_END_STATE // Expect nothing. -) - -func (ps yaml_parser_state_t) String() string { - switch ps { - case yaml_PARSE_STREAM_START_STATE: - return "yaml_PARSE_STREAM_START_STATE" - case yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE: - return "yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_START_STATE: - return "yaml_PARSE_DOCUMENT_START_STATE" - case yaml_PARSE_DOCUMENT_CONTENT_STATE: - return "yaml_PARSE_DOCUMENT_CONTENT_STATE" - case yaml_PARSE_DOCUMENT_END_STATE: - return "yaml_PARSE_DOCUMENT_END_STATE" - case yaml_PARSE_BLOCK_NODE_STATE: - return "yaml_PARSE_BLOCK_NODE_STATE" - case yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE: - return "yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE" - case yaml_PARSE_FLOW_NODE_STATE: - return "yaml_PARSE_FLOW_NODE_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_KEY_STATE: - return "yaml_PARSE_BLOCK_MAPPING_KEY_STATE" - case yaml_PARSE_BLOCK_MAPPING_VALUE_STATE: - return "yaml_PARSE_BLOCK_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE: - return "yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE" - case yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_KEY_STATE: - return "yaml_PARSE_FLOW_MAPPING_KEY_STATE" - case yaml_PARSE_FLOW_MAPPING_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_VALUE_STATE" - case yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE: - return "yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE" - case yaml_PARSE_END_STATE: - return "yaml_PARSE_END_STATE" - } - return "" -} - -// This structure holds aliases data. -type yaml_alias_data_t struct { - anchor []byte // The anchor. - index int // The node id. - mark yaml_mark_t // The anchor mark. -} - -// The parser structure. -// -// All members are internal. Manage the structure using the -// yaml_parser_ family of functions. -type yaml_parser_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - - problem string // Error description. - - // The byte about which the problem occurred. - problem_offset int - problem_value int - problem_mark yaml_mark_t - - // The error context. - context string - context_mark yaml_mark_t - - // Reader stuff - - read_handler yaml_read_handler_t // Read handler. - - input_file io.Reader // File input data. - input []byte // String input data. - input_pos int - - eof bool // EOF flag - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - unread int // The number of unread characters in the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The input encoding. - - offset int // The offset of the current position (in bytes). - mark yaml_mark_t // The mark of the current position. - - // Scanner stuff - - stream_start_produced bool // Have we started to scan the input stream? - stream_end_produced bool // Have we reached the end of the input stream? - - flow_level int // The number of unclosed '[' and '{' indicators. - - tokens []yaml_token_t // The tokens queue. - tokens_head int // The head of the tokens queue. - tokens_parsed int // The number of tokens fetched from the queue. - token_available bool // Does the tokens queue contain a token ready for dequeueing. - - indent int // The current indentation level. - indents []int // The indentation levels stack. - - simple_key_allowed bool // May a simple key occur at the current position? - simple_keys []yaml_simple_key_t // The stack of simple keys. - - // Parser stuff - - state yaml_parser_state_t // The current parser state. - states []yaml_parser_state_t // The parser states stack. - marks []yaml_mark_t // The stack of marks. - tag_directives []yaml_tag_directive_t // The list of TAG directives. - - // Dumper stuff - - aliases []yaml_alias_data_t // The alias data. - - document *yaml_document_t // The currently parsed document. -} - -// Emitter Definitions - -// The prototype of a write handler. -// -// The write handler is called when the emitter needs to flush the accumulated -// characters to the output. The handler should write @a size bytes of the -// @a buffer to the output. -// -// @param[in,out] data A pointer to an application data specified by -// yaml_emitter_set_output(). -// @param[in] buffer The buffer with bytes to be written. -// @param[in] size The size of the buffer. -// -// @returns On success, the handler should return @c 1. If the handler failed, -// the returned value should be @c 0. -// -type yaml_write_handler_t func(emitter *yaml_emitter_t, buffer []byte) error - -type yaml_emitter_state_t int - -// The emitter states. -const ( - // Expect STREAM-START. - yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota - - yaml_EMIT_FIRST_DOCUMENT_START_STATE // Expect the first DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_START_STATE // Expect DOCUMENT-START or STREAM-END. - yaml_EMIT_DOCUMENT_CONTENT_STATE // Expect the content of a document. - yaml_EMIT_DOCUMENT_END_STATE // Expect DOCUMENT-END. - yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a flow sequence. - yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE // Expect an item of a flow sequence. - yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE // Expect the first key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_KEY_STATE // Expect a key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a flow mapping. - yaml_EMIT_FLOW_MAPPING_VALUE_STATE // Expect a value of a flow mapping. - yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE // Expect the first item of a block sequence. - yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE // Expect an item of a block sequence. - yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE // Expect the first key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_KEY_STATE // Expect the key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE // Expect a value for a simple key of a block mapping. - yaml_EMIT_BLOCK_MAPPING_VALUE_STATE // Expect a value of a block mapping. - yaml_EMIT_END_STATE // Expect nothing. -) - -// The emitter structure. -// -// All members are internal. Manage the structure using the @c yaml_emitter_ -// family of functions. -type yaml_emitter_t struct { - - // Error handling - - error yaml_error_type_t // Error type. - problem string // Error description. - - // Writer stuff - - write_handler yaml_write_handler_t // Write handler. - - output_buffer *[]byte // String output data. - output_file io.Writer // File output data. - - buffer []byte // The working buffer. - buffer_pos int // The current position of the buffer. - - raw_buffer []byte // The raw buffer. - raw_buffer_pos int // The current position of the buffer. - - encoding yaml_encoding_t // The stream encoding. - - // Emitter stuff - - canonical bool // If the output is in the canonical style? - best_indent int // The number of indentation spaces. - best_width int // The preferred width of the output lines. - unicode bool // Allow unescaped non-ASCII characters? - line_break yaml_break_t // The preferred line break. - - state yaml_emitter_state_t // The current emitter state. - states []yaml_emitter_state_t // The stack of states. - - events []yaml_event_t // The event queue. - events_head int // The head of the event queue. - - indents []int // The stack of indentation levels. - - tag_directives []yaml_tag_directive_t // The list of tag directives. - - indent int // The current indentation level. - - flow_level int // The current flow level. - - root_context bool // Is it the document root context? - sequence_context bool // Is it a sequence context? - mapping_context bool // Is it a mapping context? - simple_key_context bool // Is it a simple mapping key context? - - line int // The current line. - column int // The current column. - whitespace bool // If the last character was a whitespace? - indention bool // If the last character was an indentation character (' ', '-', '?', ':')? - open_ended bool // If an explicit document end is required? - - // Anchor analysis. - anchor_data struct { - anchor []byte // The anchor value. - alias bool // Is it an alias? - } - - // Tag analysis. - tag_data struct { - handle []byte // The tag handle. - suffix []byte // The tag suffix. - } - - // Scalar analysis. - scalar_data struct { - value []byte // The scalar value. - multiline bool // Does the scalar contain line breaks? - flow_plain_allowed bool // Can the scalar be expessed in the flow plain style? - block_plain_allowed bool // Can the scalar be expressed in the block plain style? - single_quoted_allowed bool // Can the scalar be expressed in the single quoted style? - block_allowed bool // Can the scalar be expressed in the literal or folded styles? - style yaml_scalar_style_t // The output style. - } - - // Dumper stuff - - opened bool // If the stream was already opened? - closed bool // If the stream was already closed? - - // The information associated with the document nodes. - anchors *struct { - references int // The number of references. - anchor int // The anchor id. - serialized bool // If the node has been emitted? - } - - last_anchor_id int // The last assigned anchor id. - - document *yaml_document_t // The currently emitted document. -} diff --git a/vendor/github.com/sanathkr/go-yaml/yamlprivateh.go b/vendor/github.com/sanathkr/go-yaml/yamlprivateh.go deleted file mode 100644 index 8110ce3c37..0000000000 --- a/vendor/github.com/sanathkr/go-yaml/yamlprivateh.go +++ /dev/null @@ -1,173 +0,0 @@ -package yaml - -const ( - // The size of the input raw buffer. - input_raw_buffer_size = 512 - - // The size of the input buffer. - // It should be possible to decode the whole raw buffer. - input_buffer_size = input_raw_buffer_size * 3 - - // The size of the output buffer. - output_buffer_size = 128 - - // The size of the output raw buffer. - // It should be possible to encode the whole output buffer. - output_raw_buffer_size = (output_buffer_size*2 + 2) - - // The size of other stacks and queues. - initial_stack_size = 16 - initial_queue_size = 16 - initial_string_size = 16 -) - -// Check if the character at the specified position is an alphabetical -// character, a digit, '_', or '-'. -func is_alpha(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-' -} - -// Check if the character at the specified position is a digit. -func is_digit(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' -} - -// Get the value of a digit. -func as_digit(b []byte, i int) int { - return int(b[i]) - '0' -} - -// Check if the character at the specified position is a hex-digit. -func is_hex(b []byte, i int) bool { - return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f' -} - -// Get the value of a hex-digit. -func as_hex(b []byte, i int) int { - bi := b[i] - if bi >= 'A' && bi <= 'F' { - return int(bi) - 'A' + 10 - } - if bi >= 'a' && bi <= 'f' { - return int(bi) - 'a' + 10 - } - return int(bi) - '0' -} - -// Check if the character is ASCII. -func is_ascii(b []byte, i int) bool { - return b[i] <= 0x7F -} - -// Check if the character at the start of the buffer can be printed unescaped. -func is_printable(b []byte, i int) bool { - return ((b[i] == 0x0A) || // . == #x0A - (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E - (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF - (b[i] > 0xC2 && b[i] < 0xED) || - (b[i] == 0xED && b[i+1] < 0xA0) || - (b[i] == 0xEE) || - (b[i] == 0xEF && // #xE000 <= . <= #xFFFD - !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF - !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) -} - -// Check if the character at the specified position is NUL. -func is_z(b []byte, i int) bool { - return b[i] == 0x00 -} - -// Check if the beginning of the buffer is a BOM. -func is_bom(b []byte, i int) bool { - return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF -} - -// Check if the character at the specified position is space. -func is_space(b []byte, i int) bool { - return b[i] == ' ' -} - -// Check if the character at the specified position is tab. -func is_tab(b []byte, i int) bool { - return b[i] == '\t' -} - -// Check if the character at the specified position is blank (space or tab). -func is_blank(b []byte, i int) bool { - //return is_space(b, i) || is_tab(b, i) - return b[i] == ' ' || b[i] == '\t' -} - -// Check if the character at the specified position is a line break. -func is_break(b []byte, i int) bool { - return (b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029) -} - -func is_crlf(b []byte, i int) bool { - return b[i] == '\r' && b[i+1] == '\n' -} - -// Check if the character is a line break or NUL. -func is_breakz(b []byte, i int) bool { - //return is_break(b, i) || is_z(b, i) - return ( // is_break: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - // is_z: - b[i] == 0) -} - -// Check if the character is a line break, space, or NUL. -func is_spacez(b []byte, i int) bool { - //return is_space(b, i) || is_breakz(b, i) - return ( // is_space: - b[i] == ' ' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Check if the character is a line break, space, tab, or NUL. -func is_blankz(b []byte, i int) bool { - //return is_blank(b, i) || is_breakz(b, i) - return ( // is_blank: - b[i] == ' ' || b[i] == '\t' || - // is_breakz: - b[i] == '\r' || // CR (#xD) - b[i] == '\n' || // LF (#xA) - b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028) - b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029) - b[i] == 0) -} - -// Determine the width of the character. -func width(b byte) int { - // Don't replace these by a switch without first - // confirming that it is being inlined. - if b&0x80 == 0x00 { - return 1 - } - if b&0xE0 == 0xC0 { - return 2 - } - if b&0xF0 == 0xE0 { - return 3 - } - if b&0xF8 == 0xF0 { - return 4 - } - return 0 - -} diff --git a/vendor/github.com/sanathkr/yaml/LICENSE b/vendor/github.com/sanathkr/yaml/LICENSE deleted file mode 100644 index 7805d36de7..0000000000 --- a/vendor/github.com/sanathkr/yaml/LICENSE +++ /dev/null @@ -1,50 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Sam Ghods - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - -Copyright (c) 2012 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/sanathkr/yaml/README.md b/vendor/github.com/sanathkr/yaml/README.md deleted file mode 100644 index 0200f75b4d..0000000000 --- a/vendor/github.com/sanathkr/yaml/README.md +++ /dev/null @@ -1,121 +0,0 @@ -# YAML marshaling and unmarshaling support for Go - -[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) - -## Introduction - -A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs. - -In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). - -## Compatibility - -This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility). - -## Caveats - -**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: - -``` -BAD: - exampleKey: !!binary gIGC - -GOOD: - exampleKey: gIGC -... and decode the base64 data in your code. -``` - -**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. - -## Installation and usage - -To install, run: - -``` -$ go get github.com/ghodss/yaml -``` - -And import using: - -``` -import "github.com/ghodss/yaml" -``` - -Usage is very similar to the JSON library: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -type Person struct { - Name string `json:"name"` // Affects YAML field names too. - Age int `json:"age"` -} - -func main() { - // Marshal a Person struct to YAML. - p := Person{"John", 30} - y, err := yaml.Marshal(p) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - age: 30 - name: John - */ - - // Unmarshal the YAML back into a Person struct. - var p2 Person - err = yaml.Unmarshal(y, &p2) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(p2) - /* Output: - {John 30} - */ -} -``` - -`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: - -```go -package main - -import ( - "fmt" - - "github.com/ghodss/yaml" -) - -func main() { - j := []byte(`{"name": "John", "age": 30}`) - y, err := yaml.JSONToYAML(j) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(y)) - /* Output: - name: John - age: 30 - */ - j2, err := yaml.YAMLToJSON(y) - if err != nil { - fmt.Printf("err: %v\n", err) - return - } - fmt.Println(string(j2)) - /* Output: - {"age":30,"name":"John"} - */ -} -``` diff --git a/vendor/github.com/sanathkr/yaml/fields.go b/vendor/github.com/sanathkr/yaml/fields.go deleted file mode 100644 index 5860074026..0000000000 --- a/vendor/github.com/sanathkr/yaml/fields.go +++ /dev/null @@ -1,501 +0,0 @@ -// 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 yaml - -import ( - "bytes" - "encoding" - "encoding/json" - "reflect" - "sort" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - if v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } else { - v = reflect.New(v.Type().Elem()) - } - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(json.Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// A field represents a single field found in a struct. -type field struct { - name string - nameBytes []byte // []byte(name) - equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent - - tag bool - index []int - typ reflect.Type - omitEmpty bool - quoted bool -} - -func fillField(f field) field { - f.nameBytes = []byte(f.name) - f.equalFold = foldFunc(f.nameBytes) - return f -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from json tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that JSON should recognize for the given type. -// The algorithm is breadth-first search over the set of structs to include - the top struct -// and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - tag := sf.Tag.Get("json") - if tag == "-" { - continue - } - name, opts := parseTag(tag) - if !isValidTag(name) { - name = "" - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, fillField(field{ - name: name, - tag: tagged, - index: index, - typ: ft, - omitEmpty: opts.Contains("omitempty"), - quoted: opts.Contains("string"), - })) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft})) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with JSON tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// JSON tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} - -func isValidTag(s string) bool { - if s == "" { - return false - } - for _, c := range s { - switch { - case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c): - // Backslash and quote chars are reserved, but - // otherwise any punctuation chars are allowed - // in a tag name. - default: - if !unicode.IsLetter(c) && !unicode.IsDigit(c) { - return false - } - } - } - return true -} - -const ( - caseMask = ^byte(0x20) // Mask to ignore case in ASCII. - kelvin = '\u212a' - smallLongEss = '\u017f' -) - -// foldFunc returns one of four different case folding equivalence -// functions, from most general (and slow) to fastest: -// -// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 -// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') -// 3) asciiEqualFold, no special, but includes non-letters (including _) -// 4) simpleLetterEqualFold, no specials, no non-letters. -// -// The letters S and K are special because they map to 3 runes, not just 2: -// * S maps to s and to U+017F 'ſ' Latin small letter long s -// * k maps to K and to U+212A 'K' Kelvin sign -// See http://play.golang.org/p/tTxjOc0OGo -// -// The returned function is specialized for matching against s and -// should only be given s. It's not curried for performance reasons. -func foldFunc(s []byte) func(s, t []byte) bool { - nonLetter := false - special := false // special letter - for _, b := range s { - if b >= utf8.RuneSelf { - return bytes.EqualFold - } - upper := b & caseMask - if upper < 'A' || upper > 'Z' { - nonLetter = true - } else if upper == 'K' || upper == 'S' { - // See above for why these letters are special. - special = true - } - } - if special { - return equalFoldRight - } - if nonLetter { - return asciiEqualFold - } - return simpleLetterEqualFold -} - -// equalFoldRight is a specialization of bytes.EqualFold when s is -// known to be all ASCII (including punctuation), but contains an 's', -// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. -// See comments on foldFunc. -func equalFoldRight(s, t []byte) bool { - for _, sb := range s { - if len(t) == 0 { - return false - } - tb := t[0] - if tb < utf8.RuneSelf { - if sb != tb { - sbUpper := sb & caseMask - if 'A' <= sbUpper && sbUpper <= 'Z' { - if sbUpper != tb&caseMask { - return false - } - } else { - return false - } - } - t = t[1:] - continue - } - // sb is ASCII and t is not. t must be either kelvin - // sign or long s; sb must be s, S, k, or K. - tr, size := utf8.DecodeRune(t) - switch sb { - case 's', 'S': - if tr != smallLongEss { - return false - } - case 'k', 'K': - if tr != kelvin { - return false - } - default: - return false - } - t = t[size:] - - } - if len(t) > 0 { - return false - } - return true -} - -// asciiEqualFold is a specialization of bytes.EqualFold for use when -// s is all ASCII (but may contain non-letters) and contains no -// special-folding letters. -// See comments on foldFunc. -func asciiEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, sb := range s { - tb := t[i] - if sb == tb { - continue - } - if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { - if sb&caseMask != tb&caseMask { - return false - } - } else { - return false - } - } - return true -} - -// simpleLetterEqualFold is a specialization of bytes.EqualFold for -// use when s is all ASCII letters (no underscores, etc) and also -// doesn't contain 'k', 'K', 's', or 'S'. -// See comments on foldFunc. -func simpleLetterEqualFold(s, t []byte) bool { - if len(s) != len(t) { - return false - } - for i, b := range s { - if b&caseMask != t[i]&caseMask { - return false - } - } - return true -} - -// tagOptions is the string following a comma in a struct field's "json" -// tag, or the empty string. It does not include the leading comma. -type tagOptions string - -// parseTag splits a struct field's json tag into its name and -// comma-separated options. -func parseTag(tag string) (string, tagOptions) { - if idx := strings.Index(tag, ","); idx != -1 { - return tag[:idx], tagOptions(tag[idx+1:]) - } - return tag, tagOptions("") -} - -// Contains reports whether a comma-separated list of options -// contains a particular substr flag. substr must be surrounded by a -// string boundary or commas. -func (o tagOptions) Contains(optionName string) bool { - if len(o) == 0 { - return false - } - s := string(o) - for s != "" { - var next string - i := strings.Index(s, ",") - if i >= 0 { - s, next = s[:i], s[i+1:] - } - if s == optionName { - return true - } - s = next - } - return false -} diff --git a/vendor/github.com/sanathkr/yaml/yaml.go b/vendor/github.com/sanathkr/yaml/yaml.go deleted file mode 100644 index 132a8fe88f..0000000000 --- a/vendor/github.com/sanathkr/yaml/yaml.go +++ /dev/null @@ -1,277 +0,0 @@ -package yaml - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" - "strconv" - - "github.com/sanathkr/go-yaml" -) - -// Marshals the object into JSON then converts JSON to YAML and returns the -// YAML. -func Marshal(o interface{}) ([]byte, error) { - j, err := json.Marshal(o) - if err != nil { - return nil, fmt.Errorf("error marshaling into JSON: %v", err) - } - - y, err := JSONToYAML(j) - if err != nil { - return nil, fmt.Errorf("error converting JSON to YAML: %v", err) - } - - return y, nil -} - -// Converts YAML to JSON then uses JSON to unmarshal into an object. -func Unmarshal(y []byte, o interface{}) error { - vo := reflect.ValueOf(o) - j, err := yamlToJSON(y, &vo) - if err != nil { - return fmt.Errorf("error converting YAML to JSON: %v", err) - } - - err = json.Unmarshal(j, o) - if err != nil { - return fmt.Errorf("error unmarshaling JSON: %v", err) - } - - return nil -} - -// Convert JSON to YAML. -func JSONToYAML(j []byte) ([]byte, error) { - // Convert the JSON to an object. - var jsonObj interface{} - // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the - // Go JSON library doesn't try to pick the right number type (int, float, - // etc.) when unmarshalling to interface{}, it just picks float64 - // universally. go-yaml does go through the effort of picking the right - // number type, so we can preserve number type throughout this process. - err := yaml.Unmarshal(j, &jsonObj) - if err != nil { - return nil, err - } - - // Marshal this object into YAML. - return yaml.Marshal(jsonObj) -} - -// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through -// this method should be a no-op. -// -// Things YAML can do that are not supported by JSON: -// * In YAML you can have binary and null keys in your maps. These are invalid -// in JSON. (int and float keys are converted to strings.) -// * Binary data in YAML with the !!binary tag is not supported. If you want to -// use binary data with this library, encode the data as base64 as usual but do -// not use the !!binary tag in your YAML. This will ensure the original base64 -// encoded data makes it all the way through to the JSON. -func YAMLToJSON(y []byte) ([]byte, error) { - return yamlToJSON(y, nil) -} - -func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { - // Convert the YAML to an object. - var yamlObj interface{} - err := yaml.Unmarshal(y, &yamlObj) - if err != nil { - return nil, err - } - - // YAML objects are not completely compatible with JSON objects (e.g. you - // can have non-string keys in YAML). So, convert the YAML-compatible object - // to a JSON-compatible object, failing with an error if irrecoverable - // incompatibilties happen along the way. - jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) - if err != nil { - return nil, err - } - - // Convert this object to JSON and return the data. - return json.Marshal(jsonObj) -} - -func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { - var err error - - // Resolve jsonTarget to a concrete value (i.e. not a pointer or an - // interface). We pass decodingNull as false because we're not actually - // decoding into the value, we're just checking if the ultimate target is a - // string. - if jsonTarget != nil { - ju, tu, pv := indirect(*jsonTarget, false) - // We have a JSON or Text Umarshaler at this level, so we can't be trying - // to decode into a string. - if ju != nil || tu != nil { - jsonTarget = nil - } else { - jsonTarget = &pv - } - } - - // If yamlObj is a number or a boolean, check if jsonTarget is a string - - // if so, coerce. Else return normal. - // If yamlObj is a map or array, find the field that each key is - // unmarshaling to, and when you recurse pass the reflect.Value for that - // field back into this function. - switch typedYAMLObj := yamlObj.(type) { - case map[interface{}]interface{}: - // JSON does not support arbitrary keys in a map, so we must convert - // these keys to strings. - // - // From my reading of go-yaml v2 (specifically the resolve function), - // keys can only have the types string, int, int64, float64, binary - // (unsupported), or null (unsupported). - strMap := make(map[string]interface{}) - for k, v := range typedYAMLObj { - // Resolve the key to a string first. - var keyString string - switch typedKey := k.(type) { - case string: - keyString = typedKey - case int: - keyString = strconv.Itoa(typedKey) - case int64: - // go-yaml will only return an int64 as a key if the system - // architecture is 32-bit and the key's value is between 32-bit - // and 64-bit. Otherwise the key type will simply be int. - keyString = strconv.FormatInt(typedKey, 10) - case float64: - // Stolen from go-yaml to use the same conversion to string as - // the go-yaml library uses to convert float to string when - // Marshaling. - s := strconv.FormatFloat(typedKey, 'g', -1, 32) - switch s { - case "+Inf": - s = ".inf" - case "-Inf": - s = "-.inf" - case "NaN": - s = ".nan" - } - keyString = s - case bool: - if typedKey { - keyString = "true" - } else { - keyString = "false" - } - default: - return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", - reflect.TypeOf(k), k, v) - } - - // jsonTarget should be a struct or a map. If it's a struct, find - // the field it's going to map to and pass its reflect.Value. If - // it's a map, find the element type of the map and pass the - // reflect.Value created from that type. If it's neither, just pass - // nil - JSON conversion will error for us if it's a real issue. - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Struct { - keyBytes := []byte(keyString) - // Find the field that the JSON library would use. - var f *field - fields := cachedTypeFields(t.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, keyBytes) { - f = ff - break - } - // Do case-insensitive comparison. - if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { - f = ff - } - } - if f != nil { - // Find the reflect.Value of the most preferential - // struct field. - jtf := t.Field(f.index[0]) - strMap[keyString], err = convertToJSONableObject(v, &jtf) - if err != nil { - return nil, err - } - continue - } - } else if t.Kind() == reflect.Map { - // Create a zero value of the map's element type to use as - // the JSON target. - jtv := reflect.Zero(t.Type().Elem()) - strMap[keyString], err = convertToJSONableObject(v, &jtv) - if err != nil { - return nil, err - } - continue - } - } - strMap[keyString], err = convertToJSONableObject(v, nil) - if err != nil { - return nil, err - } - } - return strMap, nil - case []interface{}: - // We need to recurse into arrays in case there are any - // map[interface{}]interface{}'s inside and to convert any - // numbers to strings. - - // If jsonTarget is a slice (which it really should be), find the - // thing it's going to map to. If it's not a slice, just pass nil - // - JSON conversion will error for us if it's a real issue. - var jsonSliceElemValue *reflect.Value - if jsonTarget != nil { - t := *jsonTarget - if t.Kind() == reflect.Slice { - // By default slices point to nil, but we need a reflect.Value - // pointing to a value of the slice type, so we create one here. - ev := reflect.Indirect(reflect.New(t.Type().Elem())) - jsonSliceElemValue = &ev - } - } - - // Make and use a new array. - arr := make([]interface{}, len(typedYAMLObj)) - for i, v := range typedYAMLObj { - arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) - if err != nil { - return nil, err - } - } - return arr, nil - default: - // If the target type is a string and the YAML type is a number, - // convert the YAML type to a string. - if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { - // Based on my reading of go-yaml, it may return int, int64, - // float64, or uint64. - var s string - switch typedVal := typedYAMLObj.(type) { - case int: - s = strconv.FormatInt(int64(typedVal), 10) - case int64: - s = strconv.FormatInt(typedVal, 10) - case float64: - s = strconv.FormatFloat(typedVal, 'g', -1, 32) - case uint64: - s = strconv.FormatUint(typedVal, 10) - case bool: - if typedVal { - s = "true" - } else { - s = "false" - } - } - if len(s) > 0 { - yamlObj = interface{}(s) - } - } - return yamlObj, nil - } - - return nil, nil -} diff --git a/vendor/github.com/yvasiyarov/swagger/LICENSE b/vendor/github.com/yvasiyarov/swagger/LICENSE deleted file mode 100644 index e8b1c40752..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014, Yuriy Vasiyarov -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of the {organization} nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/yvasiyarov/swagger/README.md b/vendor/github.com/yvasiyarov/swagger/README.md deleted file mode 100644 index 8a71a68b86..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/README.md +++ /dev/null @@ -1,58 +0,0 @@ - -![alt text]( https://s3.amazonaws.com/tw-chat/attach/579528d6e2f2c2aebfe7f957e4572ca0/1.png "Logo Title Text 1") - - -##Swagger UI Generator for Go - - - -###About - -This is a utility for automatically generating API documentation from annotations in Go code. It generates the documentation as JSON, according to the [Swagger Spec](https://github.com/wordnik/swagger-spec), and then displays it using [Swagger UI](https://github.com/swagger-api/swagger-ui). - -This tool was inspired by [Beego](http://beego.me/docs/advantage/docs.md), and follows the same annotation standards set by Beego. -The main difference between this tool and Beego is that this generator doesn't depend on the Beego framework. You can use any framework to implement your API (or don't use a framework at all). You just add declarative comments to your API controllers, then run this generator and your documentation is ready! For an example of what such documentation looks like when presented via Swagger UI, see the Swagger [pet store example](http://petstore.swagger.wordnik.com/). - -
- - -####Project Status : [Alpha](https://github.com/yvasiyarov/swagger/wiki/Declarative-Comments-Format) -####Declarative Comments Format : [Read more ](https://github.com/yvasiyarov/swagger/wiki/Declarative-Comments-Format) -####Technical Notes : [Read More ](https://github.com/yvasiyarov/swagger/wiki/Technical-Notes) -####Known Limitations : [Read More ](https://github.com/yvasiyarov/swagger/wiki/Known-Limitations) - -
-#### Quick Start Guide - - -1. Add comments to your API source code, [see Declarative Comments Format ](https://github.com/yvasiyarov/swagger/wiki/Declarative-Comments-Format) - -2. Download Swagger for Go by using ````go get github.com/yvasiyarov/swagger```` - -3. Or, compile the Swagger generator from sources. - `go install` - - This will create a binary in your $GOPATH/bin folder called swagger (Mac/Unix) or swagger.exe (Windows). - -3. Run the Swagger generator. - Be in the folder with your annotated API source code and run the swagger binary: - - `./$GOPATH/bin/swagger -apiPackage="my_cool_api" -mainApiFile="my_cool_api/web/main.go"` - - Command line switches are: - * **-apiPackage** - package with API controllers implementation - * **-mainApiFile** - main API file. We will look for "General API info" in this file. If the mainApiFile command-line switch is left blank, then main.go is assumed (in the location specified by apiPackage). - * **-format** - One of: go|swagger|asciidoc|markdown|confluence. Default is -format="go". See below. - * **-output** - Output specification. Default varies according to -format. See below. - * **-controllerClass** - Speed up parsing by specifying which receiver objects have the controller methods. The default is to search all methods. The argument can be a regular expression. For example, `-controllerClass="(Context|Controller)$"` means the receiver name must end in Context or Controller. - * **-contentsTable** - Generate 'Table of Contents' section, default value is true, if set '-contentsTable=false' it will not generate the section. - * **-models** - Generate 'Models' section, default value is true, if set '-models=false' it will not generate the section. - * **-vendoringPath** - Specify the vendoring directory instead of using current working directory - - [**You can Generate different formats** ](https://github.com/yvasiyarov/swagger/wiki/Generate-Different-Formats) - -
- -4. To run the generated swagger UI (assuming you used -format="go"), copy/move the generated docs.go file to a new folder under GOPATH/src. Also bring in the web.go-example file, renaming it to web.go. Then: **go run web.go docs.go** - -5. Enjoy it :-) diff --git a/vendor/github.com/yvasiyarov/swagger/generate_markdown_doc.sh b/vendor/github.com/yvasiyarov/swagger/generate_markdown_doc.sh deleted file mode 100644 index 9b05439789..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/generate_markdown_doc.sh +++ /dev/null @@ -1 +0,0 @@ -$GOPATH/bin/swagger -apiPackage="github.com/yvasiyarov/swagger/example" -mainApiFile="github.com/yvasiyarov/swagger/example/web/main.go" -format="markdown" -output="API.md" -basePath="http://127.0.0.1:8080" diff --git a/vendor/github.com/yvasiyarov/swagger/generate_swagger_doc.sh b/vendor/github.com/yvasiyarov/swagger/generate_swagger_doc.sh deleted file mode 100755 index 5dbddca951..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/generate_swagger_doc.sh +++ /dev/null @@ -1 +0,0 @@ -go run generator.go -apiPackage="github.com/yvasiyarov/swagger/example" -mainApiFile="github.com/yvasiyarov/swagger/example/web/main.go" -format="swagger" diff --git a/vendor/github.com/yvasiyarov/swagger/generator/generator.go b/vendor/github.com/yvasiyarov/swagger/generator/generator.go deleted file mode 100644 index 4c8e16ef83..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/generator/generator.go +++ /dev/null @@ -1,214 +0,0 @@ -package generator - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "go/ast" - "log" - "os" - "path" - "regexp" - "runtime" - "strings" - - "github.com/yvasiyarov/swagger/markup" - "github.com/yvasiyarov/swagger/parser" -) - -const ( - AVAILABLE_FORMATS = "go|gopkg|swagger|asciidoc|markdown|confluence" -) - -var generatedFileTemplate = ` -package main -//This file is generated automatically. Do not try to edit it manually. - -var resourceListingJson = {{resourceListing}} -var apiDescriptionsJson = {{apiDescriptions}} -` - -var generatedPkgTemplate = ` -package {{packageName}} -//This file is generated automatically. Do not try to edit it manually. - -var ResourceListingJson = {{resourceListing}} -var ApiDescriptionsJson = {{apiDescriptions}} -` - -// It must return true if funcDeclaration is controller. We will try to parse only comments before controllers -func IsController(funcDeclaration *ast.FuncDecl, controllerClass string) bool { - if len(controllerClass) == 0 { - // Search every method - return true - } - if funcDeclaration.Recv != nil && len(funcDeclaration.Recv.List) > 0 { - if starExpression, ok := funcDeclaration.Recv.List[0].Type.(*ast.StarExpr); ok { - receiverName := fmt.Sprint(starExpression.X) - matched, err := regexp.MatchString(string(controllerClass), receiverName) - if err != nil { - log.Fatalf("The -controllerClass argument is not a valid regular expression: %v\n", err) - } - return matched - } - } - return false -} - -func generateSwaggerDocs(parser *parser.Parser, outputSpec string, pkg bool) error { - fd, err := os.Create(path.Join(outputSpec, "docs.go")) - if err != nil { - return fmt.Errorf("Can not create document file: %v\n", err) - } - defer fd.Close() - - var apiDescriptions bytes.Buffer - for apiKey, apiDescription := range parser.TopLevelApis { - apiDescriptions.WriteString("\"" + apiKey + "\":") - - apiDescriptions.WriteString("`") - json, err := json.MarshalIndent(apiDescription, "", " ") - if err != nil { - return fmt.Errorf("Can not serialise []ApiDescription to JSON: %v\n", err) - } - apiDescriptions.Write(json) - apiDescriptions.WriteString("`,") - } - - var doc string - if pkg { - doc = strings.Replace(generatedPkgTemplate, "{{resourceListing}}", "`"+string(parser.GetResourceListingJson())+"`", -1) - doc = strings.Replace(doc, "{{apiDescriptions}}", "map[string]string{"+apiDescriptions.String()+"}", -1) - packageName := strings.Split(outputSpec, "/") - doc = strings.Replace(doc, "{{packageName}}", packageName[len(packageName)-1], -1) - } else { - doc = strings.Replace(generatedFileTemplate, "{{resourceListing}}", "`"+string(parser.GetResourceListingJson())+"`", -1) - doc = strings.Replace(doc, "{{apiDescriptions}}", "map[string]string{"+apiDescriptions.String()+"}", -1) - } - - fd.WriteString(doc) - - return nil -} - -func generateSwaggerUiFiles(parser *parser.Parser, outputSpec string) error { - fd, err := os.Create(path.Join(outputSpec, "index.json")) - if err != nil { - return fmt.Errorf("Can not create the master index.json file: %v\n", err) - } - defer fd.Close() - fd.WriteString(string(parser.GetResourceListingJson())) - - for apiKey, apiDescription := range parser.TopLevelApis { - err = os.MkdirAll(path.Join(outputSpec, apiKey), 0777) - if err != nil { - return err - } - - fd, err = os.Create(path.Join(outputSpec, apiKey, "index.json")) - if err != nil { - return fmt.Errorf("Can not create the %s/index.json file: %v\n", apiKey, err) - } - defer fd.Close() - - json, err := json.MarshalIndent(apiDescription, "", " ") - if err != nil { - return fmt.Errorf("Can not serialise []ApiDescription to JSON: %v\n", err) - } - - fd.Write(json) - log.Printf("Wrote %v/index.json", apiKey) - } - - return nil -} - -func InitParser(controllerClass, ignore string) *parser.Parser { - parser := parser.NewParser() - - parser.ControllerClass = controllerClass - parser.IsController = IsController - parser.Ignore = ignore - - parser.TypesImplementingMarshalInterface["NullString"] = "string" - parser.TypesImplementingMarshalInterface["NullInt64"] = "int" - parser.TypesImplementingMarshalInterface["NullFloat64"] = "float" - parser.TypesImplementingMarshalInterface["NullBool"] = "bool" - - return parser -} - -type Params struct { - ApiPackage, MainApiFile, OutputFormat, OutputSpec, ControllerClass, Ignore, VendoringPath string - ContentsTable, Models bool -} - -func Run(params Params) error { - parser := InitParser(params.ControllerClass, params.Ignore) - gopath := os.Getenv("GOPATH") - if gopath == "" { - return errors.New("Please, set $GOPATH environment variable\n") - } - - log.Println("Start parsing") - - //Support gopaths with multiple directories - dirs := strings.Split(gopath, ":") - if runtime.GOOS == "windows" { - dirs = strings.Split(gopath, ";") - } - found := false - for _, d := range dirs { - apifile := path.Join(d, "src", params.MainApiFile) - if _, err := os.Stat(apifile); err == nil { - parser.ParseGeneralApiInfo(apifile) - found = true - break // file found, exit the loop - } - } - if found == false { - if _, err := os.Stat(params.MainApiFile); err == nil { - parser.ParseGeneralApiInfo(params.MainApiFile) - } else { - apifile := path.Join(gopath, "src", params.MainApiFile) - return fmt.Errorf("Could not find apifile %s to parse\n", apifile) - } - } - - parser.ParseApi(params.ApiPackage, params.VendoringPath) - log.Println("Finish parsing") - - var err error - confirmMsg := "" - format := strings.ToLower(params.OutputFormat) - switch format { - case "go": - err = generateSwaggerDocs(parser, params.OutputSpec, false) - confirmMsg = "Doc file generated" - case "gopkg": - err = generateSwaggerDocs(parser, params.OutputSpec, true) - confirmMsg = "Doc package generated" - case "asciidoc": - err = markup.GenerateMarkup(parser, new(markup.MarkupAsciiDoc), ¶ms.OutputSpec, ".adoc", params.ContentsTable, params.Models) - confirmMsg = "AsciiDoc file generated" - case "markdown": - err = markup.GenerateMarkup(parser, new(markup.MarkupMarkDown), ¶ms.OutputSpec, ".md", params.ContentsTable, params.Models) - confirmMsg = "MarkDown file generated" - case "confluence": - err = markup.GenerateMarkup(parser, new(markup.MarkupConfluence), ¶ms.OutputSpec, ".confluence", params.ContentsTable, params.Models) - confirmMsg = "Confluence file generated" - case "swagger": - err = generateSwaggerUiFiles(parser, params.OutputSpec) - confirmMsg = "Swagger UI files generated" - default: - err = fmt.Errorf("Invalid -format specified. Must be one of %v.", AVAILABLE_FORMATS) - } - - if err != nil { - return err - } - log.Println(confirmMsg) - - return nil -} diff --git a/vendor/github.com/yvasiyarov/swagger/main.go b/vendor/github.com/yvasiyarov/swagger/main.go deleted file mode 100644 index ad394da3e7..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/main.go +++ /dev/null @@ -1,48 +0,0 @@ -package main - -import ( - "flag" - "log" - - "github.com/yvasiyarov/swagger/generator" -) - -var apiPackage = flag.String("apiPackage", "", "The package that implements the API controllers, relative to $GOPATH/src") -var mainApiFile = flag.String("mainApiFile", "", "The file that contains the general API annotations, relative to $GOPATH/src") -var outputFormat = flag.String("format", "go", "Output format type for the generated files: "+generator.AVAILABLE_FORMATS) -var outputSpec = flag.String("output", "", "Output (path) for the generated file(s)") -var controllerClass = flag.String("controllerClass", "", "Speed up parsing by specifying which receiver objects have the controller methods") -var ignore = flag.String("ignore", "^$", "Ignore packages that satisfy this match") -var contentsTable = flag.Bool("contentsTable", true, "Generate the section Table of Contents") -var models = flag.Bool("models", true, "Generate the section models if any defined") -var vendoringPath = flag.String("vendoringPath", "", "Directory of vendoring if used") - -func main() { - flag.Parse() - - if *mainApiFile == "" { - *mainApiFile = *apiPackage + "/main.go" - } - - if *apiPackage == "" { - flag.PrintDefaults() - return - } - - params := generator.Params{ - ApiPackage: *apiPackage, - MainApiFile: *mainApiFile, - OutputFormat: *outputFormat, - OutputSpec: *outputSpec, - ControllerClass: *controllerClass, - Ignore: *ignore, - ContentsTable: *contentsTable, - Models: *models, - VendoringPath: *vendoringPath, - } - - err := generator.Run(params) - if err != nil { - log.Fatal(err.Error()) - } -} diff --git a/vendor/github.com/yvasiyarov/swagger/markup/markup.go b/vendor/github.com/yvasiyarov/swagger/markup/markup.go deleted file mode 100644 index 9b05a66588..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/markup/markup.go +++ /dev/null @@ -1,250 +0,0 @@ -package markup - -import ( - "bytes" - "fmt" - "os" - "path" - "sort" - "strings" - - "github.com/yvasiyarov/swagger/parser" -) - -const ( - color_NORMAL_TEXT = "black" - color_API_SECTION_HEADER_TEXT = "red" - color_MODEL_TEXT = "orange" - color_NORMAL_BACKGROUND = "white" - color_GET = "cyan" - color_POST = "green" - color_PUT = "orange" - color_DELETE = "cyan" - color_PATCH = "purple" - color_DEFAULT = "yellow" -) - -type Markup interface { - sectionHeader(level int, text string) string - bulletedItem(level int, text string) string - numberedItem(level int, text string) string - anchor(anchorName string) string - link(anchorName, linkText string) string - tableHeader(tableTitle string) string - tableHeaderRow(args ...string) string - tableRow(args ...string) string - tableFooter() string - colorSpan(content, foregroundColor, backgroundColor string) string -} - -func GenerateMarkup(parser *parser.Parser, markup Markup, outputSpec *string, defaultFileExtension string, tableContents bool, models bool) error { - var filename string - if *outputSpec == "" { - filename = path.Join("./", "API") + defaultFileExtension - } else { - filename = path.Join(*outputSpec) - } - fd, err := os.Create(filename) - if err != nil { - return fmt.Errorf("Can not create document file: %v\n", err) - } - defer fd.Close() - - var buf bytes.Buffer - - /*************************************************************** - * Overall API - ***************************************************************/ - buf.WriteString(markup.sectionHeader(1, parser.Listing.Infos.Title)) - buf.WriteString(fmt.Sprintf("%s\n\n", parser.Listing.Infos.Description)) - - /*************************************************************** - * Table of Contents (List of Sub-APIs) - ***************************************************************/ - if tableContents { - buf.WriteString("Table of Contents\n\n") - subApiKeys, subApiKeyIndex := alphabeticalKeysOfSubApis(parser.Listing.Apis) - for _, subApiKey := range subApiKeys { - buf.WriteString(markup.numberedItem(1, markup.link(subApiKey, parser.Listing.Apis[subApiKeyIndex[subApiKey]].Description))) - } - buf.WriteString("\n") - } - - for _, apiKey := range alphabeticalKeysOfApiDeclaration(parser.TopLevelApis) { - - apiDescription := parser.TopLevelApis[apiKey] - /*************************************************************** - * Sub-API Specifications - ***************************************************************/ - if tableContents { - buf.WriteString(markup.anchor(apiKey)) - } - buf.WriteString(markup.sectionHeader(2, markup.colorSpan(apiKey, color_API_SECTION_HEADER_TEXT, color_NORMAL_BACKGROUND))) - - buf.WriteString(markup.tableHeader("")) - buf.WriteString(markup.tableHeaderRow("Specification", "Value")) - buf.WriteString(markup.tableRow("Resource Path", apiDescription.ResourcePath)) - buf.WriteString(markup.tableRow("API Version", apiDescription.ApiVersion)) - buf.WriteString(markup.tableRow("BasePath for the API", apiDescription.BasePath)) - buf.WriteString(markup.tableRow("Consumes", strings.Join(apiDescription.Consumes, ", "))) - buf.WriteString(markup.tableRow("Produces", strings.Join(apiDescription.Produces, ", "))) - buf.WriteString(markup.tableFooter()) - - /*************************************************************** - * Sub-API Operations (Summary) - ***************************************************************/ - buf.WriteString("\n") - buf.WriteString(markup.sectionHeader(3, "Operations")) - buf.WriteString("\n") - - buf.WriteString(markup.tableHeader("")) - buf.WriteString(markup.tableHeaderRow("Resource Path", "Operation", "Description")) - for _, subapi := range apiDescription.Apis { - for _, op := range subapi.Operations { - pathString := strings.Replace(strings.Replace(subapi.Path, "{", "\\{", -1), "}", "\\}", -1) - buf.WriteString(markup.tableRow(pathString, markup.link(op.Nickname, op.HttpMethod), op.Summary)) - } - } - buf.WriteString(markup.tableFooter()) - buf.WriteString("\n") - - /*************************************************************** - * Sub-API Operations (Details) - ***************************************************************/ - for _, subapi := range apiDescription.Apis { - for _, op := range subapi.Operations { - buf.WriteString("\n") - operationString := fmt.Sprintf("%s (%s)", strings.Replace(strings.Replace(subapi.Path, "{", "\\{", -1), "}", "\\}", -1), op.HttpMethod) - if tableContents { - buf.WriteString(markup.anchor(op.Nickname)) - } - buf.WriteString(markup.sectionHeader(4, markup.colorSpan("API: "+operationString, color_NORMAL_TEXT, operationColor(op.HttpMethod)))) - buf.WriteString("\n\n" + op.Summary + "\n\n\n") - - if len(op.Parameters) > 0 { - buf.WriteString(markup.tableHeader("")) - buf.WriteString(markup.tableHeaderRow("Param Name", "Param Type", "Data Type", "Description", "Required?")) - for _, param := range op.Parameters { - isRequired := "" - if param.Required { - isRequired = "Yes" - } - buf.WriteString(markup.tableRow(param.Name, param.ParamType, modelText(markup, param.DataType), param.Description, isRequired)) - } - buf.WriteString(markup.tableFooter()) - } - - if len(op.ResponseMessages) > 0 { - buf.WriteString(markup.tableHeader("")) - buf.WriteString(markup.tableHeaderRow("Code", "Type", "Model", "Message")) - for _, msg := range op.ResponseMessages { - buf.WriteString(markup.tableRow(fmt.Sprintf("%v", msg.Code), msg.ResponseType, modelText(markup, msg.ResponseModel), msg.Message)) - } - buf.WriteString(markup.tableFooter()) - } - } - } - buf.WriteString("\n") - - /*************************************************************** - * Models - ***************************************************************/ - if len(apiDescription.Models) > 0 && models { - buf.WriteString("\n") - buf.WriteString(markup.sectionHeader(3, "Models")) - buf.WriteString("\n") - for _, modelKey := range alphabeticalKeysOfModels(apiDescription.Models) { - model := apiDescription.Models[modelKey] - if tableContents { - buf.WriteString(markup.anchor(modelKey)) - } - buf.WriteString(markup.sectionHeader(4, markup.colorSpan(shortModelName(modelKey), color_MODEL_TEXT, color_NORMAL_BACKGROUND))) - buf.WriteString(markup.tableHeader("")) - buf.WriteString(markup.tableHeaderRow("Field Name (alphabetical)", "Field Type", "Description")) - for _, fieldName := range alphabeticalKeysOfFields(model.Properties) { - fieldProps := model.Properties[fieldName] - buf.WriteString(markup.tableRow(fieldName, fieldProps.Type, fieldProps.Description)) - } - buf.WriteString(markup.tableFooter()) - } - buf.WriteString("\n") - } - } - - fd.WriteString(buf.String()) - - return nil -} - -func shortModelName(longModelName string) string { - parts := strings.Split(longModelName, ".") - return parts[len(parts)-1] -} - -func modelText(markup Markup, fullyQualifiedModelName string) string { - shortName := shortModelName(fullyQualifiedModelName) - result := shortName - if fullyQualifiedModelName != shortName { - result = markup.link(fullyQualifiedModelName, shortName) - } - return result -} - -func alphabeticalKeysOfSubApis(refs []*parser.ApiRef) ([]string, map[string]int) { - index := map[string]int{} - keys := make([]string, len(refs)) - for i, ref := range refs { - subApiKey := ref.Path[1:] - keys[i] = subApiKey - index[subApiKey] = i - } - sort.Strings(keys) - return keys, index -} -func alphabeticalKeysOfApiDeclaration(m map[string]*parser.ApiDeclaration) []string { - keys := make([]string, len(m)) - i := 0 - for key, _ := range m { - keys[i] = key - i++ - } - sort.Strings(keys) - return keys -} -func alphabeticalKeysOfModels(m map[string]*parser.Model) []string { - keys := make([]string, len(m)) - i := 0 - for key, _ := range m { - keys[i] = key - i++ - } - sort.Strings(keys) - return keys -} -func alphabeticalKeysOfFields(m map[string]*parser.ModelProperty) []string { - keys := make([]string, len(m)) - i := 0 - for key, _ := range m { - keys[i] = key - i++ - } - sort.Strings(keys) - return keys -} - -func operationColor(methodName string) string { - switch methodName { - case "GET": - return color_GET - case "POST": - return color_POST - case "PUT": - return color_PUT - case "DELETE": - return color_DELETE - case "PATCH": - return color_PATCH - default: - return color_DEFAULT - } -} diff --git a/vendor/github.com/yvasiyarov/swagger/markup/markup_asciidoc.go b/vendor/github.com/yvasiyarov/swagger/markup/markup_asciidoc.go deleted file mode 100644 index ad31ef1f2a..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/markup/markup_asciidoc.go +++ /dev/null @@ -1,73 +0,0 @@ -package markup - -import ( - "fmt" - "strings" -) - -type MarkupAsciiDoc struct { -} - -// anchor renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupAsciiDoc) anchor(anchorName string) string { - return fmt.Sprintf("[[%s]]\n", anchorName) -} - -// sectionHeader renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupAsciiDoc) sectionHeader(level int, text string) string { - return fmt.Sprintf("%s %s\n", strings.Repeat("=", level), text) -} - -// bullet renders a bulleted item at the given level -func (this *MarkupAsciiDoc) numberedItem(level int, text string) string { - return fmt.Sprintf("%s %s\n", strings.Repeat(".", level), text) -} - -// bullet renders a bulleted item at the given level -func (this *MarkupAsciiDoc) bulletedItem(level int, text string) string { - return fmt.Sprintf("%s %s\n", strings.Repeat("*", level), text) -} - -// link renders the linkText as a link to the specified anchorName. If linktext is "", then anchorName is used as the linkText. -func (this *MarkupAsciiDoc) link(anchorName, linkText string) string { - if linkText == "" { - return fmt.Sprintf("<<%s,%s>>", anchorName, anchorName) - } - return fmt.Sprintf("<<%s,%s>>", anchorName, linkText) -} - -// tableHeader starts a table -func (this *MarkupAsciiDoc) tableHeader(tableTitle string) string { - retval := "\n" - if tableTitle != "" { - retval += fmt.Sprintf(".%s\n", tableTitle) - } - return retval + "[width=\"60%\",options=\"header\"]\n|==========\n" -} - -// tableHeader ends a table -func (this *MarkupAsciiDoc) tableFooter() string { - return "|==========\n\n" -} - -// tableRow issues a table header row -func (this *MarkupAsciiDoc) tableHeaderRow(args ...string) string { - var retval string - for _, arg := range args { - retval += fmt.Sprintf("|%s ", arg) - } - return retval + "\n" -} - -// tableRow issues a single table data row -func (this *MarkupAsciiDoc) tableRow(args ...string) string { - var retval string - for _, arg := range args { - retval += fmt.Sprintf("|%s ", arg) - } - return retval + "\n" -} - -func (this *MarkupAsciiDoc) colorSpan(content, foregroundColor, backgroundColor string) string { - return fmt.Sprintf("[%s,%s-background]#%s#", foregroundColor, backgroundColor, content) -} diff --git a/vendor/github.com/yvasiyarov/swagger/markup/markup_confluence.go b/vendor/github.com/yvasiyarov/swagger/markup/markup_confluence.go deleted file mode 100644 index 54fa7a9c90..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/markup/markup_confluence.go +++ /dev/null @@ -1,79 +0,0 @@ -package markup - -import ( - "fmt" - "strings" -) - -type MarkupConfluence struct { -} - -// anchor renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupConfluence) anchor(anchorName string) string { - return fmt.Sprintf("{anchor:%s}\n", anchorName) -} - -// sectionHeader renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupConfluence) sectionHeader(level int, text string) string { - return fmt.Sprintf("\nh%v. %s\n", level, text) -} - -// bullet renders a bulleted item at the given level -func (this *MarkupConfluence) numberedItem(level int, text string) string { - return fmt.Sprintf("%s %s\n", strings.Repeat("#", level), text) -} - -// bullet renders a bulleted item at the given level -func (this *MarkupConfluence) bulletedItem(level int, text string) string { - return fmt.Sprintf("%s %s\n", strings.Repeat("*", level), text) -} - -// link renders the linkText as a link to the specified anchorName. If linktext is "", then anchorName is used as the linkText. -func (this *MarkupConfluence) link(anchorName, linkText string) string { - if linkText == "" { - return fmt.Sprintf("[#%s]", anchorName) - } - return fmt.Sprintf("[%s|#%s]", linkText, anchorName) -} - -// tableHeader starts a table -func (this *MarkupConfluence) tableHeader(tableTitle string) string { - return "\n" -} - -// tableHeader ends a table -func (this *MarkupConfluence) tableFooter() string { - return "\n" -} - -// tableRow issues a table header row -func (this *MarkupConfluence) tableHeaderRow(args ...string) string { - var retval string = "" - for _, arg := range args { - retval += fmt.Sprintf("||%s ", arg) - } - return retval + "||\n" -} - -// tableRow issues a single table data row -func (this *MarkupConfluence) tableRow(args ...string) string { - var retval string = "" - for _, arg := range args { - retval += fmt.Sprintf("|%s ", arg) - } - return retval + "|\n" -} - -func (this *MarkupConfluence) colorSpan(content, foregroundColor, backgroundColor string) string { - if foregroundColor == "black" && backgroundColor == "white" { - return content - } - if foregroundColor == "black" { - return fmt.Sprintf("{bgcolor:%s}%s{bgcolor}", backgroundColor, content) - } - if backgroundColor == "white" { - return fmt.Sprintf("{color:%s}%s{color}", foregroundColor, content) - } - return fmt.Sprintf("{color:%s}{bgcolor:%s}%s{bgcolor}{color}", foregroundColor, backgroundColor, content) - -} diff --git a/vendor/github.com/yvasiyarov/swagger/markup/markup_markdown.go b/vendor/github.com/yvasiyarov/swagger/markup/markup_markdown.go deleted file mode 100644 index 927184d533..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/markup/markup_markdown.go +++ /dev/null @@ -1,72 +0,0 @@ -package markup - -import ( - "fmt" - "strings" -) - -type MarkupMarkDown struct { -} - -// sectionHeader renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupMarkDown) sectionHeader(level int, text string) string { - return fmt.Sprintf("\n%s %s\n", strings.Repeat("#", level), text) -} - -// numberedItem renders a bulleted item at the given level -func (this *MarkupMarkDown) numberedItem(level int, text string) string { - return fmt.Sprintf("%s1. %s\n", strings.Repeat(" ", level-1), text) -} - -// bulletedItem renders a bulleted item at the given level -func (this *MarkupMarkDown) bulletedItem(level int, text string) string { - return fmt.Sprintf("%s* %s\n", strings.Repeat(" ", level-1), text) -} - -// anchor renders a title (level 1) or subtitle (level 2..5) -func (this *MarkupMarkDown) anchor(anchorName string) string { - return fmt.Sprintf("\n", anchorName) -} - -// link renders the linkText as a link to the specified anchorName. If linktext is "", then anchorName is used as the linkText. -func (this *MarkupMarkDown) link(anchorName, linkText string) string { - if linkText == "" { - return fmt.Sprintf("[%s](#%s)", anchorName, anchorName) - } - return fmt.Sprintf("[%s](#%s)", linkText, anchorName) -} - -// tableHeader starts a table -func (this *MarkupMarkDown) tableHeader(tableTitle string) string { - return "\n" -} - -// tableHeaderRow issues a table header row -func (this *MarkupMarkDown) tableHeaderRow(args ...string) string { - var retval string = "" - var separator string = "" - for _, arg := range args { - retval += fmt.Sprintf("| %s ", arg) - separator += "|-----" - } - return retval + "|\n" + separator + "|\n" -} - -// tableRow issues a single table data row -func (this *MarkupMarkDown) tableRow(args ...string) string { - var retval string = "" - for _, arg := range args { - retval += fmt.Sprintf("| %s ", arg) - } - return retval + "|\n" -} - -// tableFooter ends a table -func (this *MarkupMarkDown) tableFooter() string { - return "\n" -} - -// Note: Github flavored markdown does not support colorization -func (this *MarkupMarkDown) colorSpan(content, foregroundColor, backgroundColor string) string { - return content -} diff --git a/vendor/github.com/yvasiyarov/swagger/parser/api_declaration.go b/vendor/github.com/yvasiyarov/swagger/parser/api_declaration.go deleted file mode 100644 index 7429e7e652..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/parser/api_declaration.go +++ /dev/null @@ -1,86 +0,0 @@ -package parser - -// https://github.com/wordnik/swagger-core/blob/scala_2.10-1.3-RC3/schemas/api-declaration-schema.json -type ApiDeclaration struct { - ApiVersion string `json:"apiVersion"` - SwaggerVersion string `json:"swaggerVersion"` - BasePath string `json:"basePath"` - ResourcePath string `json:"resourcePath"` // must start with / - Consumes []string `json:"-"` - Produces []string `json:"produces,omitempty"` - Apis []*Api `json:"apis,omitempty"` - Models map[string]*Model `json:"models,omitempty"` -} - -func NewApiDeclaration() *ApiDeclaration { - return &ApiDeclaration{ - Apis: make([]*Api, 0), - Models: make(map[string]*Model), - Consumes: make([]string, 0), - Produces: make([]string, 0), - } -} - -func (api *ApiDeclaration) AddConsumedTypes(op *Operation) { - for _, contextType := range op.Consumes { - isExists := false - for _, existType := range api.Consumes { - if existType == contextType { - isExists = true - break - } - } - if !isExists { - api.Consumes = append(api.Consumes, contextType) - } - } -} - -func (api *ApiDeclaration) AddProducesTypes(op *Operation) { - for _, contextType := range op.Produces { - isExists := false - for _, existType := range api.Produces { - if existType == contextType { - isExists = true - break - } - } - if !isExists { - api.Produces = append(api.Produces, contextType) - } - } -} -func (api *ApiDeclaration) AddModels(op *Operation) { - for _, m := range op.Models { - if m != nil { - if _, ok := api.Models[m.Id]; !ok { - api.Models[m.Id] = m - } - } - } -} - -func (api *ApiDeclaration) AddSubApi(op *Operation) { - var subApi *Api - for _, existsSubApi := range api.Apis { - if existsSubApi.Path == op.Path { - subApi = existsSubApi - break - } - } - if subApi == nil { - subApi = NewApi() - subApi.Path = op.Path - subApi.Description = op.Summary - - api.Apis = append(api.Apis, subApi) - } - subApi.Operations = append(subApi.Operations, op) -} - -func (api *ApiDeclaration) AddOperation(op *Operation) { - api.AddProducesTypes(op) - api.AddConsumedTypes(op) - api.AddModels(op) - api.AddSubApi(op) -} diff --git a/vendor/github.com/yvasiyarov/swagger/parser/model.go b/vendor/github.com/yvasiyarov/swagger/parser/model.go deleted file mode 100644 index f6f1582e18..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/parser/model.go +++ /dev/null @@ -1,290 +0,0 @@ -package parser - -import ( - "fmt" - "go/ast" - "log" - "reflect" - "regexp" - "strings" -) - -type Model struct { - Id string `json:"id"` - Required []string `json:"required,omitempty"` - Properties map[string]*ModelProperty `json:"properties"` - parser *Parser -} - -func NewModel(p *Parser) *Model { - return &Model{ - parser: p, - } -} - -// modelName is something like package.subpackage.SomeModel or just "subpackage.SomeModel" -func (m *Model) ParseModel(modelName string, currentPackage string, knownModelNames map[string]bool) (error, []*Model) { - knownModelNames[modelName] = true - //log.Printf("Before parse model |%s|, package: |%s|\n", modelName, currentPackage) - - astTypeSpec, modelPackage := m.parser.FindModelDefinition(modelName, currentPackage) - - modelNameParts := strings.Split(modelName, ".") - m.Id = strings.Join(append(strings.Split(modelPackage, "/"), modelNameParts[len(modelNameParts)-1]), ".") - - var innerModelList []*Model - if astTypeDef, ok := astTypeSpec.Type.(*ast.Ident); ok { - typeDefTranslations[astTypeSpec.Name.String()] = astTypeDef.Name - } else if astStructType, ok := astTypeSpec.Type.(*ast.StructType); ok { - m.ParseFieldList(astStructType.Fields.List, modelPackage) - usedTypes := make(map[string]bool) - - for _, property := range m.Properties { - typeName := property.Type - if typeName == "array" { - if property.Items.Type != "" { - typeName = property.Items.Type - } else { - typeName = property.Items.Ref - } - } - if translation, ok := typeDefTranslations[typeName]; ok { - typeName = translation - } - if IsBasicType(typeName) || m.parser.IsImplementMarshalInterface(typeName) { - continue - } - if _, exists := knownModelNames[typeName]; exists { - continue - } - - usedTypes[typeName] = true - } - - //log.Printf("Before parse inner model list: %#v\n (%s)", usedTypes, modelName) - innerModelList = make([]*Model, 0, len(usedTypes)) - - for typeName, _ := range usedTypes { - typeModel := NewModel(m.parser) - if err, typeInnerModels := typeModel.ParseModel(typeName, modelPackage, knownModelNames); err != nil { - //log.Printf("Parse Inner Model error %#v \n", err) - return err, nil - } else { - for _, property := range m.Properties { - if property.Type == "array" { - if property.Items.Ref == typeName { - property.Items.Ref = typeModel.Id - } - } else { - if property.Type == typeName { - property.Type = typeModel.Id - } - } - } - //log.Printf("Inner model %v parsed, parsing %s \n", typeName, modelName) - if typeModel != nil { - innerModelList = append(innerModelList, typeModel) - } - if typeInnerModels != nil && len(typeInnerModels) > 0 { - innerModelList = append(innerModelList, typeInnerModels...) - } - //log.Printf("innerModelList: %#v\n, typeInnerModels: %#v, usedTypes: %#v \n", innerModelList, typeInnerModels, usedTypes) - } - } - //log.Printf("After parse inner model list: %#v\n (%s)", usedTypes, modelName) - // log.Fatalf("Inner model list: %#v\n", innerModelList) - - } - - //log.Printf("ParseModel finished %s \n", modelName) - return nil, innerModelList -} - -func (m *Model) ParseFieldList(fieldList []*ast.Field, modelPackage string) { - if fieldList == nil { - return - } - //log.Printf("ParseFieldList\n") - - m.Properties = make(map[string]*ModelProperty) - for _, field := range fieldList { - m.ParseModelProperty(field, modelPackage) - } -} - -func (m *Model) ParseModelProperty(field *ast.Field, modelPackage string) { - var name string - var innerModel *Model - - property := NewModelProperty() - - typeAsString := property.GetTypeAsString(field.Type) - //log.Printf("Get type as string %s \n", typeAsString) - - // Sometimes reflection reports an object as "&{foo Bar}" rather than just "foo.Bar" - // The next 2 lines of code normalize them to foo.Bar - reInternalRepresentation := regexp.MustCompile("&\\{(\\w*) (\\w*)\\}") - typeAsString = string(reInternalRepresentation.ReplaceAll([]byte(typeAsString), []byte("$1.$2"))) - - if strings.HasPrefix(typeAsString, "[]") { - property.Type = "array" - property.SetItemType(typeAsString[2:]) - } else if typeAsString == "time.Time" { - property.Type = "Time" - } else { - property.Type = typeAsString - } - - if len(field.Names) == 0 { - - if astSelectorExpr, ok := field.Type.(*ast.SelectorExpr); ok { - packageName := modelPackage - if astTypeIdent, ok := astSelectorExpr.X.(*ast.Ident); ok { - packageName = astTypeIdent.Name - } - - name = packageName + "." + strings.TrimPrefix(astSelectorExpr.Sel.Name, "*") - } else if astTypeIdent, ok := field.Type.(*ast.Ident); ok { - name = astTypeIdent.Name - } else if astStarExpr, ok := field.Type.(*ast.StarExpr); ok { - if astIdent, ok := astStarExpr.X.(*ast.Ident); ok { - name = astIdent.Name - } - } else { - log.Fatalf("Something goes wrong: %#v", field.Type) - } - innerModel = NewModel(m.parser) - //log.Printf("Try to parse embeded type %s \n", name) - //log.Fatalf("DEBUG: field: %#v\n, selector.X: %#v\n selector.Sel: %#v\n", field, astSelectorExpr.X, astSelectorExpr.Sel) - knownModelNames := map[string]bool{} - innerModel.ParseModel(name, modelPackage, knownModelNames) - - for innerFieldName, innerField := range innerModel.Properties { - m.Properties[innerFieldName] = innerField - } - - //log.Fatalf("Here %#v\n", field.Type) - return - } else { - name = field.Names[0].Name - } - - //log.Printf("ParseModelProperty: %s, CurrentPackage %s, type: %s \n", name, modelPackage, property.Type) - //Analyse struct fields annotations - if field.Tag != nil { - structTag := reflect.StructTag(strings.Trim(field.Tag.Value, "`")) - var tagText string - if thriftTag := structTag.Get("thrift"); thriftTag != "" { - tagText = thriftTag - } - if tag := structTag.Get("json"); tag != "" { - tagText = tag - } - - tagValues := strings.Split(tagText, ",") - var isRequired = false - - for _, v := range tagValues { - if v != "" && v != "required" && v != "omitempty" { - name = v - } - if v == "required" { - isRequired = true - } - // We will not document at all any fields with a json tag of "-" - if v == "-" { - return - } - } - if required := structTag.Get("required"); required != "" || isRequired { - m.Required = append(m.Required, name) - } - if desc := structTag.Get("description"); desc != "" { - property.Description = desc - } - } - m.Properties[name] = property -} - -type ModelProperty struct { - Type string `json:"type"` - Description string `json:"description"` - Items ModelPropertyItems `json:"items,omitempty"` - Format string `json:"format"` -} -type ModelPropertyItems struct { - Ref string `json:"$ref,omitempty"` - Type string `json:"type,omitempty"` -} - -func NewModelProperty() *ModelProperty { - return &ModelProperty{} -} - -// refer to builtin.go -var basicTypes = map[string]bool{ - "bool": true, - "uint": true, - "uint8": true, - "uint16": true, - "uint32": true, - "uint64": true, - "int": true, - "int8": true, - "int16": true, - "int32": true, - "int64": true, - "float32": true, - "float64": true, - "string": true, - "complex64": true, - "complex128": true, - "byte": true, - "rune": true, - "uintptr": true, - "error": true, - "Time": true, - "file": true, -} - -var typeDefTranslations = map[string]string{} - -func IsBasicType(typeName string) bool { - _, ok := basicTypes[typeName] - return ok || strings.Contains(typeName, "interface") -} - -func (p *ModelProperty) SetItemType(itemType string) { - p.Items = ModelPropertyItems{} - if IsBasicType(itemType) { - p.Items.Type = itemType - } else { - p.Items.Ref = itemType - } -} -func (p *ModelProperty) GetTypeAsString(fieldType interface{}) string { - var realType string - if astArrayType, ok := fieldType.(*ast.ArrayType); ok { - // log.Printf("arrayType: %#v\n", astArrayType) - realType = fmt.Sprintf("[]%v", p.GetTypeAsString(astArrayType.Elt)) - } else if astMapType, ok := fieldType.(*ast.MapType); ok { - // log.Printf("arrayType: %#v\n", astArrayType) - realType = fmt.Sprintf("[]%v", p.GetTypeAsString(astMapType.Value)) - } else if _, ok := fieldType.(*ast.InterfaceType); ok { - realType = "interface" - } else { - if astStarExpr, ok := fieldType.(*ast.StarExpr); ok { - realType = fmt.Sprint(astStarExpr.X) - // log.Printf("Get type as string (star expression)! %#v, type: %s\n", astStarExpr.X, fmt.Sprint(astStarExpr.X)) - } else if astSelectorExpr, ok := fieldType.(*ast.SelectorExpr); ok { - packageNameIdent, _ := astSelectorExpr.X.(*ast.Ident) - realType = packageNameIdent.Name + "." + astSelectorExpr.Sel.Name - - // log.Printf("Get type as string(selector expression)! X: %#v , Sel: %#v, type %s\n", astSelectorExpr.X, astSelectorExpr.Sel, realType) - } else { - // log.Printf("Get type as string(no star expression)! %#v , type: %s\n", fieldType, fmt.Sprint(fieldType)) - realType = fmt.Sprint(fieldType) - } - } - return realType -} diff --git a/vendor/github.com/yvasiyarov/swagger/parser/operation.go b/vendor/github.com/yvasiyarov/swagger/parser/operation.go deleted file mode 100644 index dc4faab180..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/parser/operation.go +++ /dev/null @@ -1,264 +0,0 @@ -package parser - -import ( - "errors" - "fmt" - //"go/ast" - "regexp" - "strconv" - "strings" -) - -type Operation struct { - HttpMethod string `json:"httpMethod"` - Nickname string `json:"nickname"` - Type string `json:"type"` - Items OperationItems `json:"items,omitempty"` - Summary string `json:"summary,omitempty"` - Notes string `json:"notes,omitempty"` - Parameters []Parameter `json:"parameters,omitempty"` - ResponseMessages []ResponseMessage `json:"responseMessages,omitempty"` - Consumes []string `json:"-"` - Produces []string `json:"produces,omitempty"` - Authorizations []Authorization `json:"authorizations,omitempty"` - Protocols []Protocol `json:"protocols,omitempty"` - Path string `json:"-"` - ForceResource string `json:"-"` - parser *Parser - Models []*Model `json:"-"` - packageName string -} -type OperationItems struct { - Ref string `json:"$ref,omitempty"` - Type string `json:"type,omitempty"` -} - -func NewOperation(p *Parser, packageName string) *Operation { - return &Operation{ - parser: p, - Models: make([]*Model, 0), - packageName: packageName, - } -} - -func (operation *Operation) SetItemsType(itemsType string) { - operation.Items = OperationItems{} - if IsBasicType(itemsType) { - operation.Items.Type = itemsType - } else { - operation.Items.Ref = itemsType - } -} - -func (operation *Operation) ParseComment(comment string) error { - commentLine := strings.TrimSpace(strings.TrimLeft(comment, "//")) - if len(commentLine) == 0 { - return nil - } - attribute := strings.Fields(commentLine)[0] - switch strings.ToLower(attribute) { - case "@router": - if err := operation.ParseRouterComment(commentLine); err != nil { - return err - } - case "@resource": - resource := strings.TrimSpace(commentLine[len(attribute):]) - if resource[0:1] == "/" { - resource = resource[1:] - } - operation.ForceResource = resource - case "@title": - operation.Nickname = strings.TrimSpace(commentLine[len(attribute):]) - case "@description": - operation.Summary = strings.TrimSpace(commentLine[len(attribute):]) - case "@success", "@failure": - if err := operation.ParseResponseComment(strings.TrimSpace(commentLine[len(attribute):])); err != nil { - return err - } - case "@param": - if err := operation.ParseParamComment(strings.TrimSpace(commentLine[len(attribute):])); err != nil { - return err - } - case "@accept", "@consume": - if err := operation.ParseAcceptComment(strings.TrimSpace(commentLine[len(attribute):])); err != nil { - return err - } - case "@produce": - if err := operation.ParseProduceComment(strings.TrimSpace(commentLine[len(attribute):])); err != nil { - return err - } - } - - operation.Models = operation.getUniqueModels() - - return nil -} - -func (operation *Operation) getUniqueModels() []*Model { - - uniqueModels := make([]*Model, 0, len(operation.Models)) - modelIds := map[string]bool{} - - for _, model := range operation.Models { - if _, exists := modelIds[model.Id]; exists { - continue - } - uniqueModels = append(uniqueModels, model) - modelIds[model.Id] = true - } - - return uniqueModels -} - -func (operation *Operation) registerType(typeName string) (string, error) { - registerType := "" - - if translation, ok := typeDefTranslations[typeName]; ok { - registerType = translation - } else if IsBasicType(typeName) { - registerType = typeName - } else { - model := NewModel(operation.parser) - knownModelNames := map[string]bool{} - - err, innerModels := model.ParseModel(typeName, operation.parser.CurrentPackage, knownModelNames) - if err != nil { - return registerType, err - } - if translation, ok := typeDefTranslations[typeName]; ok { - registerType = translation - } else { - registerType = model.Id - - operation.Models = append(operation.Models, model) - operation.Models = append(operation.Models, innerModels...) - } - } - - return registerType, nil -} - -// Parse params return []string of param properties -// @Param queryText form string true "The email for login" -// [param name] [param type] [data type] [is mandatory?] [Comment] -func (operation *Operation) ParseParamComment(commentLine string) error { - swaggerParameter := Parameter{} - paramString := commentLine - - re := regexp.MustCompile(`([-\w]+)[\s]+([\w]+)[\s]+([\S.]+)[\s]+([\w]+)[\s]+"([^"]+)"`) - - if matches := re.FindStringSubmatch(paramString); len(matches) != 6 { - return fmt.Errorf("Can not parse param comment \"%s\", skipped.", paramString) - } else { - typeName, err := operation.registerType(matches[3]) - if err != nil { - return err - } - - swaggerParameter.Name = matches[1] - swaggerParameter.ParamType = matches[2] - swaggerParameter.Type = typeName - swaggerParameter.DataType = typeName - requiredText := strings.ToLower(matches[4]) - swaggerParameter.Required = (requiredText == "true" || requiredText == "required") - swaggerParameter.Description = matches[5] - - operation.Parameters = append(operation.Parameters, swaggerParameter) - } - - return nil -} - -// @Accept json -func (operation *Operation) ParseAcceptComment(commentLine string) error { - accepts := strings.Split(commentLine, ",") - for _, a := range accepts { - switch a { - case "json", "application/json": - operation.Consumes = append(operation.Consumes, ContentTypeJson) - case "xml", "text/xml": - operation.Consumes = append(operation.Consumes, ContentTypeXml) - case "plain", "text/plain": - operation.Consumes = append(operation.Consumes, ContentTypePlain) - case "html", "text/html": - operation.Consumes = append(operation.Consumes, ContentTypeHtml) - case "mpfd", "multipart/form-data": - operation.Consumes = append(operation.Consumes, ContentTypeMultiPartFormData) - } - } - return nil -} - -// @Produce json -func (operation *Operation) ParseProduceComment(commentLine string) error { - produces := strings.Split(commentLine, ",") - for _, a := range produces { - switch a { - case "json", "application/json": - operation.Produces = append(operation.Produces, ContentTypeJson) - case "xml", "text/xml": - operation.Produces = append(operation.Produces, ContentTypeXml) - case "plain", "text/plain": - operation.Produces = append(operation.Produces, ContentTypePlain) - case "html", "text/html": - operation.Produces = append(operation.Produces, ContentTypeHtml) - case "mpfd", "multipart/form-data": - operation.Produces = append(operation.Produces, ContentTypeMultiPartFormData) - } - } - return nil -} - -// @Router /customer/get-wishlist/{wishlist_id} [get] -func (operation *Operation) ParseRouterComment(commentLine string) error { - sourceString := strings.TrimSpace(commentLine[len("@Router"):]) - - re := regexp.MustCompile(`([\w\.\/\-{}]+)[^\[]+\[([^\]]+)`) - var matches []string - - if matches = re.FindStringSubmatch(sourceString); len(matches) != 3 { - return fmt.Errorf("Can not parse router comment \"%s\", skipped.", commentLine) - } - - operation.Path = matches[1] - operation.HttpMethod = strings.ToUpper(matches[2]) - return nil -} - -// @Success 200 {object} model.OrderRow "Error message, if code != 200" -func (operation *Operation) ParseResponseComment(commentLine string) error { - re := regexp.MustCompile(`([\d]+)[\s]+([\w\{\}]+)[\s]+([\w\-\.\/]+)[^"]*(.*)?`) - var matches []string - - if matches = re.FindStringSubmatch(commentLine); len(matches) != 5 { - return fmt.Errorf("Can not parse response comment \"%s\", skipped.", commentLine) - } - - response := ResponseMessage{} - if code, err := strconv.Atoi(matches[1]); err != nil { - return errors.New("Success http code must be int") - } else { - response.Code = code - } - response.Message = strings.Trim(matches[4], "\"") - - typeName, err := operation.registerType(matches[3]) - if err != nil { - return err - } - - response.ResponseType = strings.Trim(matches[2], "{}") - - response.ResponseModel = typeName - if response.Code == 200 { - if matches[2] == "{array}" { - operation.SetItemsType(typeName) - operation.Type = "array" - } else { - operation.Type = typeName - } - } - - operation.ResponseMessages = append(operation.ResponseMessages, response) - return nil -} diff --git a/vendor/github.com/yvasiyarov/swagger/parser/parser.go b/vendor/github.com/yvasiyarov/swagger/parser/parser.go deleted file mode 100644 index f75ef8f95e..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/parser/parser.go +++ /dev/null @@ -1,519 +0,0 @@ -package parser - -import ( - "encoding/json" - "go/ast" - goparser "go/parser" - "go/token" - "log" - "os" - "path/filepath" - "regexp" - "runtime" - "strings" - "fmt" -) - -var vendoringPath string - -type Parser struct { - Listing *ResourceListing - TopLevelApis map[string]*ApiDeclaration - PackagesCache map[string]map[string]*ast.Package - CurrentPackage string - TypeDefinitions map[string]map[string]*ast.TypeSpec - PackagePathCache map[string]string - PackageImports map[string]map[string][]string - BasePath, ControllerClass, Ignore string - IsController func(*ast.FuncDecl, string) bool - TypesImplementingMarshalInterface map[string]string -} - -func NewParser() *Parser { - return &Parser{ - Listing: &ResourceListing{ - Infos: Infomation{}, - Apis: make([]*ApiRef, 0), - }, - PackagesCache: make(map[string]map[string]*ast.Package), - TopLevelApis: make(map[string]*ApiDeclaration), - TypeDefinitions: make(map[string]map[string]*ast.TypeSpec), - PackagePathCache: make(map[string]string), - PackageImports: make(map[string]map[string][]string), - TypesImplementingMarshalInterface: make(map[string]string), - } -} - -func (parser *Parser) IsImplementMarshalInterface(typeName string) bool { - _, ok := parser.TypesImplementingMarshalInterface[typeName] - return ok -} - -//Read web/main.go to get General info -func (parser *Parser) ParseGeneralApiInfo(mainApiFile string) { - - fileSet := token.NewFileSet() - fileTree, err := goparser.ParseFile(fileSet, mainApiFile, nil, goparser.ParseComments) - if err != nil { - log.Fatalf("Can not parse general API information: %v\n", err) - } - - parser.Listing.BasePath = "{{.}}" - parser.Listing.SwaggerVersion = SwaggerVersion - if fileTree.Comments != nil { - for _, comment := range fileTree.Comments { - for _, commentLine := range strings.Split(comment.Text(), "\n") { - attribute := strings.ToLower(strings.Split(commentLine, " ")[0]) - switch attribute { - case "@apiversion": - parser.Listing.ApiVersion = strings.TrimSpace(commentLine[len(attribute):]) - case "@apititle": - parser.Listing.Infos.Title = strings.TrimSpace(commentLine[len(attribute):]) - case "@apidescription": - parser.Listing.Infos.Description = strings.TrimSpace(commentLine[len(attribute):]) - case "@termsofserviceurl": - parser.Listing.Infos.TermsOfServiceUrl = strings.TrimSpace(commentLine[len(attribute):]) - case "@contact": - parser.Listing.Infos.Contact = strings.TrimSpace(commentLine[len(attribute):]) - case "@licenseurl": - parser.Listing.Infos.LicenseUrl = strings.TrimSpace(commentLine[len(attribute):]) - case "@license": - parser.Listing.Infos.License = strings.TrimSpace(commentLine[len(attribute):]) - case "@basepath": - parser.Listing.BasePath = strings.TrimSpace(commentLine[len(attribute):]) - } - } - } - } -} - -func (parser *Parser) GetResourceListingJson() []byte { - json, err := json.MarshalIndent(parser.Listing, "", " ") - if err != nil { - log.Fatalf("Can not serialise ResourceListing to JSON: %v\n", err) - } - return json -} - -func (parser *Parser) GetApiDescriptionJson() []byte { - json, err := json.MarshalIndent(parser.TopLevelApis, "", " ") - if err != nil { - log.Fatalf("Can not serialise []ApiDescription to JSON: %v\n", err) - } - return json -} - -func (parser *Parser) CheckRealPackagePath(packagePath string) string { - packagePath = strings.Trim(packagePath, "\"") - - if cachedResult, ok := parser.PackagePathCache[packagePath]; ok { - return cachedResult - } - - // Hack vendoring of 'golang.org/x' by the standard library - if strings.HasPrefix(packagePath, "golang_org/x/") { - packagePath = filepath.Join("vendor", packagePath) - } - - pkgRealpath := "" - goVersion := runtime.Version() - // check if vendor is enabled for version GO 1.5 or 1.6 - vendorEnable := true - if goVersion == "go1.5" || goVersion == "go1.6" { - if os.Getenv("GO15VENDOREXPERIMENT") == "0" { - vendorEnable = false - } - } - - - // first check vendor folder, vendoring in GO 1.7 and greater is officially supported - // evaluate if the user specified a different vendor directory rather - // than using current working directory to find vendor - if vendorEnable { - var vendorPath string - if vendoringPath == "" { - vendorPath = filepath.Join("vendor", packagePath) - } else { - vendorPath = fmt.Sprintf("%s/%s", vendoringPath, packagePath) - } - - if evalutedPath, err := filepath.EvalSymlinks(vendorPath); err == nil { - if _, err := os.Stat(evalutedPath); err == nil { - pkgRealpath = evalutedPath - } - } - } - - // next, check GOPATH - if pkgRealpath == "" { - gopath := os.Getenv("GOPATH") - if gopath == "" { - log.Fatalf("Please, set $GOPATH environment variable\n") - } - - gopathsList := filepath.SplitList(gopath) - for _, path := range gopathsList { - if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(path, "src", packagePath)); err == nil { - if _, err := os.Stat(evalutedPath); err == nil { - pkgRealpath = evalutedPath - break - } - } - } - } - - // next, check GOROOT (/src) - if pkgRealpath == "" { - goroot := filepath.Clean(runtime.GOROOT()) - if goroot == "" { - log.Fatalf("Please, set $GOROOT environment variable\n") - } - if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(goroot, "src", packagePath)); err == nil { - if _, err := os.Stat(evalutedPath); err == nil { - pkgRealpath = evalutedPath - } - } - - // next, check GOROOT (/src/pkg) (for golang < v1.4) - if pkgRealpath == "" { - if evalutedPath, err := filepath.EvalSymlinks(filepath.Join(goroot, "src", "pkg", packagePath)); err == nil { - if _, err := os.Stat(evalutedPath); err == nil { - pkgRealpath = evalutedPath - } - } - } - } - - parser.PackagePathCache[packagePath] = pkgRealpath - return pkgRealpath -} - -func (parser *Parser) GetRealPackagePath(packagePath string) string { - pkgRealpath := parser.CheckRealPackagePath(packagePath) - if pkgRealpath == "" { - log.Fatalf("Can not find package %s \n", packagePath) - } - - return pkgRealpath -} - -func (parser *Parser) GetPackageAst(packagePath string) map[string]*ast.Package { - //log.Printf("Parse %s package\n", packagePath) - if cache, ok := parser.PackagesCache[packagePath]; ok { - return cache - } else { - fileSet := token.NewFileSet() - - astPackages, err := goparser.ParseDir(fileSet, packagePath, ParserFileFilter, goparser.ParseComments) - if err != nil { - log.Fatalf("Parse of %s pkg cause error: %s\n", packagePath, err) - } - parser.PackagesCache[packagePath] = astPackages - return astPackages - } -} - -func (parser *Parser) AddOperation(op *Operation) { - path := []string{} - for _, pathPart := range strings.Split(op.Path, "/") { - if pathPart = strings.TrimSpace(pathPart); pathPart != "" { - path = append(path, pathPart) - } - } - - resource := path[0] - if op.ForceResource != "" { - resource = op.ForceResource - } - - api, ok := parser.TopLevelApis[resource] - if !ok { - api = NewApiDeclaration() - - api.ApiVersion = parser.Listing.ApiVersion - api.SwaggerVersion = SwaggerVersion - api.ResourcePath = "/" + resource - api.BasePath = parser.Listing.BasePath - - parser.TopLevelApis[resource] = api - } - - found := false - for _, apiRef := range parser.Listing.Apis { - if apiRef.Path == api.ResourcePath { - found = true - } - } - if !found { - apiRef := &ApiRef{ - Path: api.ResourcePath, - Description: op.Summary, - } - parser.Listing.Apis = append(parser.Listing.Apis, apiRef) - } - - api.AddOperation(op) -} - -func (parser *Parser) ParseApi(packageNames, vendorPath string) { - vendoringPath = vendorPath - packages := parser.ScanPackages(strings.Split(packageNames, ",")) - for _, packageName := range packages { - parser.ParseTypeDefinitions(packageName) - } - for _, packageName := range packages { - parser.ParseApiDescription(packageName) - } -} - -func (parser *Parser) ScanPackages(packages []string) []string { - res := make([]string, len(packages)) - existsPackages := make(map[string]bool) - - for _, packageName := range packages { - if v, ok := existsPackages[packageName]; !ok || v == false { - // Add package - existsPackages[packageName] = true - res = append(res, packageName) - // get it's real path - pkgRealPath := parser.GetRealPackagePath(packageName) - // Then walk - var walker filepath.WalkFunc = func(path string, info os.FileInfo, err error) error { - // avoid listing hidden directories with initial "_" names and vendor dir - if info.IsDir() && !strings.Contains(path, "/_") && !strings.Contains(path, "/vendor") { - if idx := strings.Index(path, packageName); idx != -1 { - pack := path[idx:] - if v, ok := existsPackages[pack]; !ok || v == false { - existsPackages[pack] = true - res = append(res, pack) - } - } - } - return nil - } - filepath.Walk(pkgRealPath, walker) - } - } - return res -} - -func (parser *Parser) ParseTypeDefinitions(packageName string) { - parser.CurrentPackage = packageName - pkgRealPath := parser.GetRealPackagePath(packageName) - // log.Printf("Parse type definition of %#v\n", packageName) - - if _, ok := parser.TypeDefinitions[pkgRealPath]; !ok { - parser.TypeDefinitions[pkgRealPath] = make(map[string]*ast.TypeSpec) - } - - astPackages := parser.GetPackageAst(pkgRealPath) - for _, astPackage := range astPackages { - for _, astFile := range astPackage.Files { - for _, astDeclaration := range astFile.Decls { - if generalDeclaration, ok := astDeclaration.(*ast.GenDecl); ok && generalDeclaration.Tok == token.TYPE { - for _, astSpec := range generalDeclaration.Specs { - if typeSpec, ok := astSpec.(*ast.TypeSpec); ok { - parser.TypeDefinitions[pkgRealPath][typeSpec.Name.String()] = typeSpec - } - } - } - } - } - } - - //log.Fatalf("Type definition parsed %#v\n", parser.ParseImportStatements(packageName)) - - for importedPackage, _ := range parser.ParseImportStatements(packageName) { - //log.Printf("Import: %v, %v\n", importedPackage, v) - parser.ParseTypeDefinitions(importedPackage) - } -} - -func (parser *Parser) ParseImportStatements(packageName string) map[string]bool { - - parser.CurrentPackage = packageName - pkgRealPath := parser.GetRealPackagePath(packageName) - - imports := make(map[string]bool) - astPackages := parser.GetPackageAst(pkgRealPath) - - parser.PackageImports[pkgRealPath] = make(map[string][]string) - for _, astPackage := range astPackages { - for _, astFile := range astPackage.Files { - for _, astImport := range astFile.Imports { - importedPackageName := strings.Trim(astImport.Path.Value, "\"") - if !parser.isIgnoredPackage(importedPackageName) { - realPath := parser.GetRealPackagePath(importedPackageName) - //log.Printf("path: %#v, original path: %#v", realPath, astImport.Path.Value) - if _, ok := parser.TypeDefinitions[realPath]; !ok { - imports[importedPackageName] = true - //log.Printf("Parse %s, Add new import definition:%s\n", packageName, astImport.Path.Value) - } - - var importedPackageAlias string - if astImport.Name != nil && astImport.Name.Name != "." && astImport.Name.Name != "_" { - importedPackageAlias = astImport.Name.Name - } else { - importPath := strings.Split(importedPackageName, "/") - importedPackageAlias = importPath[len(importPath)-1] - } - - isExists := false - for _, v := range parser.PackageImports[pkgRealPath][importedPackageAlias] { - if v == importedPackageName { - isExists = true - } - } - - if !isExists { - parser.PackageImports[pkgRealPath][importedPackageAlias] = append(parser.PackageImports[pkgRealPath][importedPackageAlias], importedPackageName) - } - } - } - } - } - return imports -} - -func (parser *Parser) GetModelDefinition(model string, packageName string) *ast.TypeSpec { - pkgRealPath := parser.CheckRealPackagePath(packageName) - if pkgRealPath == "" { - return nil - } - - packageModels, ok := parser.TypeDefinitions[pkgRealPath] - if !ok { - return nil - } - astTypeSpec, _ := packageModels[model] - return astTypeSpec -} - -func (parser *Parser) FindModelDefinition(modelName string, currentPackage string) (*ast.TypeSpec, string) { - var model *ast.TypeSpec - var modelPackage string - - modelNameParts := strings.Split(modelName, ".") - - //if no dot in name - it can be only model from current package - if len(modelNameParts) == 1 { - modelPackage = currentPackage - if model = parser.GetModelDefinition(modelName, currentPackage); model == nil { - log.Fatalf("Can not find definition of %s model. Current package %s", modelName, currentPackage) - } - } else { - //first try to assume what name is absolute - absolutePackageName := strings.Join(modelNameParts[:len(modelNameParts)-1], "/") - modelNameFromPath := modelNameParts[len(modelNameParts)-1] - - modelPackage = absolutePackageName - if model = parser.GetModelDefinition(modelNameFromPath, absolutePackageName); model == nil { - - //can not get model by absolute name. - if len(modelNameParts) > 2 { - log.Fatalf("Can not find definition of %s model. Name looks like absolute, but model not found in %s package", modelNameFromPath, absolutePackageName) - } - - // lets try to find it in imported packages - pkgRealPath := parser.CheckRealPackagePath(currentPackage) - if imports, ok := parser.PackageImports[pkgRealPath]; !ok { - log.Fatalf("Can not find definition of %s model. Package %s dont import anything", modelNameFromPath, pkgRealPath) - } else if relativePackage, ok := imports[modelNameParts[0]]; !ok { - log.Fatalf("Package %s is not imported to %s, Imported: %#v\n", modelNameParts[0], currentPackage, imports) - } else { - var modelFound bool - - for _, packageName := range relativePackage { - if model = parser.GetModelDefinition(modelNameFromPath, packageName); model != nil { - modelPackage = packageName - modelFound = true - - break - } - } - - if !modelFound { - log.Fatalf("Can not find definition of %s model in package %s", modelNameFromPath, relativePackage) - } - } - } - } - return model, modelPackage -} - -func (parser *Parser) ParseApiDescription(packageName string) { - parser.CurrentPackage = packageName - pkgRealPath := parser.GetRealPackagePath(packageName) - - astPackages := parser.GetPackageAst(pkgRealPath) - for _, astPackage := range astPackages { - for _, astFile := range astPackage.Files { - for _, astDescription := range astFile.Decls { - switch astDeclaration := astDescription.(type) { - case *ast.FuncDecl: - if parser.IsController(astDeclaration, parser.ControllerClass) { - operation := NewOperation(parser, packageName) - if astDeclaration.Doc != nil && astDeclaration.Doc.List != nil { - for _, comment := range astDeclaration.Doc.List { - if err := operation.ParseComment(comment.Text); err != nil { - log.Printf("Can not parse comment for function: %v, package: %v, got error: %v\n", astDeclaration.Name.String(), packageName, err) - } - } - } - if operation.Path != "" { - parser.AddOperation(operation) - } - } - } - } - for _, astComment := range astFile.Comments { - for _, commentLine := range strings.Split(astComment.Text(), "\n") { - parser.ParseSubApiDescription(commentLine) - } - } - } - } -} - -// Parse sub api declaration -// @SubApi Very fancy API [/fancy-api] -func (parser *Parser) ParseSubApiDescription(commentLine string) { - if !strings.HasPrefix(commentLine, "@SubApi") { - return - } else { - commentLine = strings.TrimSpace(commentLine[len("@SubApi"):]) - } - re := regexp.MustCompile(`([^\[]+)\[{1}([\w\_\-/]+)`) - - if matches := re.FindStringSubmatch(commentLine); len(matches) != 3 { - log.Printf("Can not parse sub api description %s, skipped", commentLine) - } else { - found := false - for _, ref := range parser.Listing.Apis { - if ref.Path == matches[2] { - found = true - ref.Description = strings.TrimSpace(matches[1]) - } - } - if !found { - subApi := &ApiRef{Path: matches[2], - Description: strings.TrimSpace(matches[1]), - } - parser.Listing.Apis = append(parser.Listing.Apis, subApi) - } - } -} - -func (parser *Parser) isIgnoredPackage(packageName string) bool { - r, _ := regexp.Compile("appengine+") - matched, err := regexp.MatchString(parser.Ignore, packageName) - if err != nil { - log.Fatalf("The -ignore argument is not a valid regular expression: %v\n", err) - } - return packageName == "C" || r.MatchString(packageName) || matched -} - -func ParserFileFilter(info os.FileInfo) bool { - name := info.Name() - return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go") -} diff --git a/vendor/github.com/yvasiyarov/swagger/parser/structs.go b/vendor/github.com/yvasiyarov/swagger/parser/structs.go deleted file mode 100644 index 079a07d05e..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/parser/structs.go +++ /dev/null @@ -1,113 +0,0 @@ -package parser - -import ( - "errors" -) - -const SwaggerVersion = "1.2" -const ( - ContentTypeJson = "application/json" - ContentTypeXml = "application/xml" - ContentTypePlain = "text/plain" - ContentTypeHtml = "text/html" - ContentTypeMultiPartFormData = "multipart/form-data" -) - -var CommentIsEmptyError = errors.New("Comment is empty") - -type ResourceListing struct { - ApiVersion string `json:"apiVersion"` - SwaggerVersion string `json:"swaggerVersion"` - BasePath string `json:"basePath,omitempty"` - Apis []*ApiRef `json:"apis"` - Infos Infomation `json:"info"` -} - -type ApiRef struct { - Path string `json:"path"` // relative or absolute, must start with / - Description string `json:"description"` -} - -type Infomation struct { - Title string `json:"title,omitempty"` - Description string `json:"description,omitempty"` - Contact string `json:"contact,omitempty"` - TermsOfServiceUrl string `json:"termsOfServiceUrl,omitempty"` - License string `json:"license,omitempty"` - LicenseUrl string `json:"licenseUrl,omitempty"` -} - -type Api struct { - Path string `json:"path"` // relative or absolute, must start with / - Description string `json:"description"` - Operations []*Operation `json:"operations,omitempty"` -} - -func NewApi() *Api { - return &Api{ - Operations: make([]*Operation, 0), - } -} - -type Protocol struct { -} - -type ResponseMessage struct { - Code int `json:"code"` - Message string `json:"message"` - ResponseType string `json:"responseType"` - ResponseModel string `json:"responseModel"` -} - -type Parameter struct { - ParamType string `json:"paramType"` // path,query,body,header,form - Name string `json:"name"` - Description string `json:"description"` - DataType string `json:"dataType"` // 1.2 needed? - Type string `json:"type"` // integer - Format string `json:"format"` // int64 - AllowMultiple bool `json:"allowMultiple"` - Required bool `json:"required"` - Minimum int `json:"minimum"` - Maximum int `json:"maximum"` -} - -type ErrorResponse struct { - Code int `json:"code"` - Reason string `json:"reason"` -} - -// https://github.com/wordnik/swagger-core/wiki/authorizations -type Authorization struct { - LocalOAuth OAuth `json:"local-oauth"` - ApiKey ApiKey `json:"apiKey"` -} - -// https://github.com/wordnik/swagger-core/wiki/authorizations -type OAuth struct { - Type string `json:"type"` // e.g. oauth2 - Scopes []string `json:"scopes"` // e.g. PUBLIC - GrantTypes map[string]GrantType `json:"grantTypes"` -} - -// https://github.com/wordnik/swagger-core/wiki/authorizations -type GrantType struct { - LoginEndpoint Endpoint `json:"loginEndpoint"` - TokenName string `json:"tokenName"` // e.g. access_code - TokenRequestEndpoint Endpoint `json:"tokenRequestEndpoint"` - TokenEndpoint Endpoint `json:"tokenEndpoint"` -} - -// https://github.com/wordnik/swagger-core/wiki/authorizations -type Endpoint struct { - Url string `json:"url"` - ClientIdName string `json:"clientIdName"` - ClientSecretName string `json:"clientSecretName"` - TokenName string `json:"tokenName"` -} - -// https://github.com/wordnik/swagger-core/wiki/authorizations -type ApiKey struct { - Type string `json:"type"` // e.g. apiKey - PassAs string `json:"passAs"` // e.g. header -} diff --git a/vendor/github.com/yvasiyarov/swagger/web.go-example b/vendor/github.com/yvasiyarov/swagger/web.go-example deleted file mode 100644 index 2ca9a43d74..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/web.go-example +++ /dev/null @@ -1,75 +0,0 @@ -package main - -import ( - "flag" - "os" - "net/http" - "strings" - "text/template" - - "github.com/fvbock/endless" - log "github.com/mgutz/logxi/v1" -) - -var host = flag.String("host", "0.0.0.0", "Host") -var port = flag.String("port", "8080", "Port") -var staticContent = flag.String("staticPath", "./swagger-ui", "Path to folder with Swagger UI") -var apiurl = flag.String("api", "http://127.0.0.1", "The base path URI of the API service") - -func IndexHandler(w http.ResponseWriter, r *http.Request) { - isJsonRequest := false - - if acceptHeaders, ok := r.Header["Accept"]; ok { - for _, acceptHeader := range acceptHeaders { - if strings.Contains(acceptHeader, "json") { - isJsonRequest = true - break - } - } - } - - if isJsonRequest { - w.Write([]byte(resourceListingJson)) - } else { - http.Redirect(w, r, "/swagger-ui/", http.StatusFound) - } -} - -func ApiDescriptionHandler(w http.ResponseWriter, r *http.Request) { - apiKey := strings.Trim(r.RequestURI, "/") - - if json, ok := apiDescriptionsJson[apiKey]; ok { - t, e := template.New("desc").Parse(json) - if e != nil { - w.WriteHeader(http.StatusInternalServerError) - return - } - t.Execute(w, *apiurl) - } else { - w.WriteHeader(http.StatusNotFound) - } -} - -func main() { - flag.Parse() - - // To serve a directory on disk (/tmp) under an alternate URL - // path (/tmpfiles/), use StripPrefix to modify the request - // URL's path before the FileServer sees it: - http.HandleFunc("/", IndexHandler) - http.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui/", http.FileServer(http.Dir(*staticContent)))) - - for apiKey, _ := range apiDescriptionsJson { - http.HandleFunc("/"+apiKey+"/", ApiDescriptionHandler) - } - - listenTo := *host + ":" + *port - log.Info("Star listen to %s", listenTo) - - err := endless.ListenAndServe(listenTo, http.DefaultServeMux) - if err != nil { - log.Error(err.Error()) - } - log.Info("Server on %s stopped", listenTo) - os.Exit(0) -} diff --git a/vendor/github.com/yvasiyarov/swagger/web.go-example-cors b/vendor/github.com/yvasiyarov/swagger/web.go-example-cors deleted file mode 100644 index 0059652a2c..0000000000 --- a/vendor/github.com/yvasiyarov/swagger/web.go-example-cors +++ /dev/null @@ -1,68 +0,0 @@ -package main - -import ( - "flag" - // "fmt" - "log" - "net/http" - "strings" - "github.com/rs/cors" -) - -var host = flag.String("host", "0.0.0.0", "Host") -var port = flag.String("port", "8080", "Port") -var staticContent = flag.String("staticPath", "./swagger-ui", "Path to folder with Swagger UI") - -func IndexHandler(w http.ResponseWriter, r *http.Request) { - isJsonRequest := false - - if acceptHeaders, ok := r.Header["Accept"]; ok { - for _, acceptHeader := range acceptHeaders { - if strings.Contains(acceptHeader, "json") { - isJsonRequest = true - break - } - } - } - - if isJsonRequest { - w.Write([]byte(resourceListingJson)) - } else { - http.Redirect(w, r, "/swagger-ui/", http.StatusFound) - } -} - -func ApiDescriptionHandler(w http.ResponseWriter, r *http.Request) { - apiKey := strings.Trim(r.RequestURI, "/") - - if json, ok := apiDescriptionsJson[apiKey]; ok { - w.Write([]byte(json)) - } else { - w.WriteHeader(http.StatusNotFound) - } -} - -func main() { - flag.Parse() - - //Add the url orgins to access from - c := cors.New(cors.Options{ - AllowedOrigins: []string{"http://www.example.com/"}, - }) - // To serve a directory on disk (/tmp) under an alternate URL - // path (/tmpfiles/), use StripPrefix to modify the request - // URL's path before the FileServer sees it: - http.HandleFunc("/", IndexHandler) - http.Handle("/swagger-ui/", http.StripPrefix("/swagger-ui/", http.FileServer(http.Dir(*staticContent)))) - - for apiKey, _ := range apiDescriptionsJson { - http.HandleFunc("/"+apiKey+"/", ApiDescriptionHandler) - } - - listenTo := *host + ":" + *port - log.Printf("Star listen to %s", listenTo) - - http.ListenAndServe(listenTo, http.DefaultServeMux) - //http.ListenAndServe(listenTo, c.Handler(http.DefaultServeMux)) Allows cors to be used. - //http.ListenAndServe(":8080", http.StripPrefix("/swagger-ui/", http.FileServer(http.Dir("./swagger-ui")) ) -} diff --git a/vendor/golang.org/x/net/LICENSE b/vendor/golang.org/x/net/LICENSE deleted file mode 100644 index 6a66aea5ea..0000000000 --- a/vendor/golang.org/x/net/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/golang.org/x/net/PATENTS b/vendor/golang.org/x/net/PATENTS deleted file mode 100644 index 733099041f..0000000000 --- a/vendor/golang.org/x/net/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/vendor/golang.org/x/net/context/context.go b/vendor/golang.org/x/net/context/context.go deleted file mode 100644 index f143ed6a1e..0000000000 --- a/vendor/golang.org/x/net/context/context.go +++ /dev/null @@ -1,156 +0,0 @@ -// 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 context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context // import "golang.org/x/net/context" - -import "time" - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out chan<- Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go deleted file mode 100644 index 606cf1f972..0000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ /dev/null @@ -1,74 +0,0 @@ -// 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 ctxhttp provides helper functions for performing context-aware HTTP requests. -package ctxhttp // import "golang.org/x/net/context/ctxhttp" - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -// Do sends an HTTP request with the provided http.Client and returns -// an HTTP response. -// -// If the client is nil, http.DefaultClient is used. -// -// The provided ctx must be non-nil. If it is canceled or times out, -// ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - resp, err := client.Do(req.WithContext(ctx)) - // If we got an error, and the context has been canceled, - // the context's error is probably more useful. - if err != nil { - select { - case <-ctx.Done(): - err = ctx.Err() - default: - } - } - return resp, err -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} diff --git a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go b/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go deleted file mode 100644 index 926870cc23..0000000000 --- a/vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.7 - -package ctxhttp // import "golang.org/x/net/context/ctxhttp" - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -func nop() {} - -var ( - testHookContextDoneBeforeHeaders = nop - testHookDoReturned = nop - testHookDidBodyClose = nop -) - -// Do sends an HTTP request with the provided http.Client and returns an HTTP response. -// If the client is nil, http.DefaultClient is used. -// If the context is canceled or times out, ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - - // TODO(djd): Respect any existing value of req.Cancel. - cancel := make(chan struct{}) - req.Cancel = cancel - - type responseAndError struct { - resp *http.Response - err error - } - result := make(chan responseAndError, 1) - - // Make local copies of test hooks closed over by goroutines below. - // Prevents data races in tests. - testHookDoReturned := testHookDoReturned - testHookDidBodyClose := testHookDidBodyClose - - go func() { - resp, err := client.Do(req) - testHookDoReturned() - result <- responseAndError{resp, err} - }() - - var resp *http.Response - - select { - case <-ctx.Done(): - testHookContextDoneBeforeHeaders() - close(cancel) - // Clean up after the goroutine calling client.Do: - go func() { - if r := <-result; r.resp != nil { - testHookDidBodyClose() - r.resp.Body.Close() - } - }() - return nil, ctx.Err() - case r := <-result: - var err error - resp, err = r.resp, r.err - if err != nil { - return resp, err - } - } - - c := make(chan struct{}) - go func() { - select { - case <-ctx.Done(): - close(cancel) - case <-c: - // The response's Body is closed. - } - }() - resp.Body = ¬ifyingReader{resp.Body, c} - - return resp, nil -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} - -// notifyingReader is an io.ReadCloser that closes the notify channel after -// Close is called or a Read fails on the underlying ReadCloser. -type notifyingReader struct { - io.ReadCloser - notify chan<- struct{} -} - -func (r *notifyingReader) Read(p []byte) (int, error) { - n, err := r.ReadCloser.Read(p) - if err != nil && r.notify != nil { - close(r.notify) - r.notify = nil - } - return n, err -} - -func (r *notifyingReader) Close() error { - err := r.ReadCloser.Close() - if r.notify != nil { - close(r.notify) - r.notify = nil - } - return err -} diff --git a/vendor/golang.org/x/net/context/go17.go b/vendor/golang.org/x/net/context/go17.go deleted file mode 100644 index d20f52b7de..0000000000 --- a/vendor/golang.org/x/net/context/go17.go +++ /dev/null @@ -1,72 +0,0 @@ -// 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 context - -import ( - "context" // standard library's context, as of Go 1.7 - "time" -) - -var ( - todo = context.TODO() - background = context.Background() -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = context.Canceled - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = context.DeadlineExceeded - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - ctx, f := context.WithCancel(parent) - return ctx, CancelFunc(f) -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - ctx, f := context.WithDeadline(parent, deadline) - return ctx, CancelFunc(f) -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return context.WithValue(parent, key, val) -} diff --git a/vendor/golang.org/x/net/context/pre_go17.go b/vendor/golang.org/x/net/context/pre_go17.go deleted file mode 100644 index 0f35592df5..0000000000 --- a/vendor/golang.org/x/net/context/pre_go17.go +++ /dev/null @@ -1,300 +0,0 @@ -// 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. - -// +build !go1.7 - -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, c) - return c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) *cancelCtx { - return &cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - *cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/vendor/golang.org/x/net/html/atom/atom.go b/vendor/golang.org/x/net/html/atom/atom.go deleted file mode 100644 index cd0a8ac154..0000000000 --- a/vendor/golang.org/x/net/html/atom/atom.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package atom provides integer codes (also known as atoms) for a fixed set of -// frequently occurring HTML strings: tag names and attribute keys such as "p" -// and "id". -// -// Sharing an atom's name between all elements with the same tag can result in -// fewer string allocations when tokenizing and parsing HTML. Integer -// comparisons are also generally faster than string comparisons. -// -// The value of an atom's particular code is not guaranteed to stay the same -// between versions of this package. Neither is any ordering guaranteed: -// whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to -// be dense. The only guarantees are that e.g. looking up "div" will yield -// atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. -package atom // import "golang.org/x/net/html/atom" - -// Atom is an integer code for a string. The zero value maps to "". -type Atom uint32 - -// String returns the atom's name. -func (a Atom) String() string { - start := uint32(a >> 8) - n := uint32(a & 0xff) - if start+n > uint32(len(atomText)) { - return "" - } - return atomText[start : start+n] -} - -func (a Atom) string() string { - return atomText[a>>8 : a>>8+a&0xff] -} - -// fnv computes the FNV hash with an arbitrary starting value h. -func fnv(h uint32, s []byte) uint32 { - for i := range s { - h ^= uint32(s[i]) - h *= 16777619 - } - return h -} - -func match(s string, t []byte) bool { - for i, c := range t { - if s[i] != c { - return false - } - } - return true -} - -// Lookup returns the atom whose name is s. It returns zero if there is no -// such atom. The lookup is case sensitive. -func Lookup(s []byte) Atom { - if len(s) == 0 || len(s) > maxAtomLen { - return 0 - } - h := fnv(hash0, s) - if a := table[h&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - if a := table[(h>>16)&uint32(len(table)-1)]; int(a&0xff) == len(s) && match(a.string(), s) { - return a - } - return 0 -} - -// String returns a string whose contents are equal to s. In that sense, it is -// equivalent to string(s) but may be more efficient. -func String(s []byte) string { - if a := Lookup(s); a != 0 { - return a.String() - } - return string(s) -} diff --git a/vendor/golang.org/x/net/html/atom/table.go b/vendor/golang.org/x/net/html/atom/table.go deleted file mode 100644 index 2605ba3102..0000000000 --- a/vendor/golang.org/x/net/html/atom/table.go +++ /dev/null @@ -1,713 +0,0 @@ -// generated by go run gen.go; DO NOT EDIT - -package atom - -const ( - A Atom = 0x1 - Abbr Atom = 0x4 - Accept Atom = 0x2106 - AcceptCharset Atom = 0x210e - Accesskey Atom = 0x3309 - Action Atom = 0x1f606 - Address Atom = 0x4f307 - Align Atom = 0x1105 - Alt Atom = 0x4503 - Annotation Atom = 0x1670a - AnnotationXml Atom = 0x1670e - Applet Atom = 0x2b306 - Area Atom = 0x2fa04 - Article Atom = 0x38807 - Aside Atom = 0x8305 - Async Atom = 0x7b05 - Audio Atom = 0xa605 - Autocomplete Atom = 0x1fc0c - Autofocus Atom = 0xb309 - Autoplay Atom = 0xce08 - B Atom = 0x101 - Base Atom = 0xd604 - Basefont Atom = 0xd608 - Bdi Atom = 0x1a03 - Bdo Atom = 0xe703 - Bgsound Atom = 0x11807 - Big Atom = 0x12403 - Blink Atom = 0x12705 - Blockquote Atom = 0x12c0a - Body Atom = 0x2f04 - Br Atom = 0x202 - Button Atom = 0x13606 - Canvas Atom = 0x7f06 - Caption Atom = 0x1bb07 - Center Atom = 0x5b506 - Challenge Atom = 0x21f09 - Charset Atom = 0x2807 - Checked Atom = 0x32807 - Cite Atom = 0x3c804 - Class Atom = 0x4de05 - Code Atom = 0x14904 - Col Atom = 0x15003 - Colgroup Atom = 0x15008 - Color Atom = 0x15d05 - Cols Atom = 0x16204 - Colspan Atom = 0x16207 - Command Atom = 0x17507 - Content Atom = 0x42307 - Contenteditable Atom = 0x4230f - Contextmenu Atom = 0x3310b - Controls Atom = 0x18808 - Coords Atom = 0x19406 - Crossorigin Atom = 0x19f0b - Data Atom = 0x44a04 - Datalist Atom = 0x44a08 - Datetime Atom = 0x23c08 - Dd Atom = 0x26702 - Default Atom = 0x8607 - Defer Atom = 0x14b05 - Del Atom = 0x3ef03 - Desc Atom = 0x4db04 - Details Atom = 0x4807 - Dfn Atom = 0x6103 - Dialog Atom = 0x1b06 - Dir Atom = 0x6903 - Dirname Atom = 0x6907 - Disabled Atom = 0x10c08 - Div Atom = 0x11303 - Dl Atom = 0x11e02 - Download Atom = 0x40008 - Draggable Atom = 0x17b09 - Dropzone Atom = 0x39108 - Dt Atom = 0x50902 - Em Atom = 0x6502 - Embed Atom = 0x6505 - Enctype Atom = 0x21107 - Face Atom = 0x5b304 - Fieldset Atom = 0x1b008 - Figcaption Atom = 0x1b80a - Figure Atom = 0x1cc06 - Font Atom = 0xda04 - Footer Atom = 0x8d06 - For Atom = 0x1d803 - ForeignObject Atom = 0x1d80d - Foreignobject Atom = 0x1e50d - Form Atom = 0x1f204 - Formaction Atom = 0x1f20a - Formenctype Atom = 0x20d0b - Formmethod Atom = 0x2280a - Formnovalidate Atom = 0x2320e - Formtarget Atom = 0x2470a - Frame Atom = 0x9a05 - Frameset Atom = 0x9a08 - H1 Atom = 0x26e02 - H2 Atom = 0x29402 - H3 Atom = 0x2a702 - H4 Atom = 0x2e902 - H5 Atom = 0x2f302 - H6 Atom = 0x50b02 - Head Atom = 0x2d504 - Header Atom = 0x2d506 - Headers Atom = 0x2d507 - Height Atom = 0x25106 - Hgroup Atom = 0x25906 - Hidden Atom = 0x26506 - High Atom = 0x26b04 - Hr Atom = 0x27002 - Href Atom = 0x27004 - Hreflang Atom = 0x27008 - Html Atom = 0x25504 - HttpEquiv Atom = 0x2780a - I Atom = 0x601 - Icon Atom = 0x42204 - Id Atom = 0x8502 - Iframe Atom = 0x29606 - Image Atom = 0x29c05 - Img Atom = 0x2a103 - Input Atom = 0x3e805 - Inputmode Atom = 0x3e809 - Ins Atom = 0x1a803 - Isindex Atom = 0x2a907 - Ismap Atom = 0x2b005 - Itemid Atom = 0x33c06 - Itemprop Atom = 0x3c908 - Itemref Atom = 0x5ad07 - Itemscope Atom = 0x2b909 - Itemtype Atom = 0x2c308 - Kbd Atom = 0x1903 - Keygen Atom = 0x3906 - Keytype Atom = 0x53707 - Kind Atom = 0x10904 - Label Atom = 0xf005 - Lang Atom = 0x27404 - Legend Atom = 0x18206 - Li Atom = 0x1202 - Link Atom = 0x12804 - List Atom = 0x44e04 - Listing Atom = 0x44e07 - Loop Atom = 0xf404 - Low Atom = 0x11f03 - Malignmark Atom = 0x100a - Manifest Atom = 0x5f108 - Map Atom = 0x2b203 - Mark Atom = 0x1604 - Marquee Atom = 0x2cb07 - Math Atom = 0x2d204 - Max Atom = 0x2e103 - Maxlength Atom = 0x2e109 - Media Atom = 0x6e05 - Mediagroup Atom = 0x6e0a - Menu Atom = 0x33804 - Menuitem Atom = 0x33808 - Meta Atom = 0x45d04 - Meter Atom = 0x24205 - Method Atom = 0x22c06 - Mglyph Atom = 0x2a206 - Mi Atom = 0x2eb02 - Min Atom = 0x2eb03 - Minlength Atom = 0x2eb09 - Mn Atom = 0x23502 - Mo Atom = 0x3ed02 - Ms Atom = 0x2bc02 - Mtext Atom = 0x2f505 - Multiple Atom = 0x30308 - Muted Atom = 0x30b05 - Name Atom = 0x6c04 - Nav Atom = 0x3e03 - Nobr Atom = 0x5704 - Noembed Atom = 0x6307 - Noframes Atom = 0x9808 - Noscript Atom = 0x3d208 - Novalidate Atom = 0x2360a - Object Atom = 0x1ec06 - Ol Atom = 0xc902 - Onabort Atom = 0x13a07 - Onafterprint Atom = 0x1c00c - Onautocomplete Atom = 0x1fa0e - Onautocompleteerror Atom = 0x1fa13 - Onbeforeprint Atom = 0x6040d - Onbeforeunload Atom = 0x4e70e - Onblur Atom = 0xaa06 - Oncancel Atom = 0xe908 - Oncanplay Atom = 0x28509 - Oncanplaythrough Atom = 0x28510 - Onchange Atom = 0x3a708 - Onclick Atom = 0x31007 - Onclose Atom = 0x31707 - Oncontextmenu Atom = 0x32f0d - Oncuechange Atom = 0x3420b - Ondblclick Atom = 0x34d0a - Ondrag Atom = 0x35706 - Ondragend Atom = 0x35709 - Ondragenter Atom = 0x3600b - Ondragleave Atom = 0x36b0b - Ondragover Atom = 0x3760a - Ondragstart Atom = 0x3800b - Ondrop Atom = 0x38f06 - Ondurationchange Atom = 0x39f10 - Onemptied Atom = 0x39609 - Onended Atom = 0x3af07 - Onerror Atom = 0x3b607 - Onfocus Atom = 0x3bd07 - Onhashchange Atom = 0x3da0c - Oninput Atom = 0x3e607 - Oninvalid Atom = 0x3f209 - Onkeydown Atom = 0x3fb09 - Onkeypress Atom = 0x4080a - Onkeyup Atom = 0x41807 - Onlanguagechange Atom = 0x43210 - Onload Atom = 0x44206 - Onloadeddata Atom = 0x4420c - Onloadedmetadata Atom = 0x45510 - Onloadstart Atom = 0x46b0b - Onmessage Atom = 0x47609 - Onmousedown Atom = 0x47f0b - Onmousemove Atom = 0x48a0b - Onmouseout Atom = 0x4950a - Onmouseover Atom = 0x4a20b - Onmouseup Atom = 0x4ad09 - Onmousewheel Atom = 0x4b60c - Onoffline Atom = 0x4c209 - Ononline Atom = 0x4cb08 - Onpagehide Atom = 0x4d30a - Onpageshow Atom = 0x4fe0a - Onpause Atom = 0x50d07 - Onplay Atom = 0x51706 - Onplaying Atom = 0x51709 - Onpopstate Atom = 0x5200a - Onprogress Atom = 0x52a0a - Onratechange Atom = 0x53e0c - Onreset Atom = 0x54a07 - Onresize Atom = 0x55108 - Onscroll Atom = 0x55f08 - Onseeked Atom = 0x56708 - Onseeking Atom = 0x56f09 - Onselect Atom = 0x57808 - Onshow Atom = 0x58206 - Onsort Atom = 0x58b06 - Onstalled Atom = 0x59509 - Onstorage Atom = 0x59e09 - Onsubmit Atom = 0x5a708 - Onsuspend Atom = 0x5bb09 - Ontimeupdate Atom = 0xdb0c - Ontoggle Atom = 0x5c408 - Onunload Atom = 0x5cc08 - Onvolumechange Atom = 0x5d40e - Onwaiting Atom = 0x5e209 - Open Atom = 0x3cf04 - Optgroup Atom = 0xf608 - Optimum Atom = 0x5eb07 - Option Atom = 0x60006 - Output Atom = 0x49c06 - P Atom = 0xc01 - Param Atom = 0xc05 - Pattern Atom = 0x5107 - Ping Atom = 0x7704 - Placeholder Atom = 0xc30b - Plaintext Atom = 0xfd09 - Poster Atom = 0x15706 - Pre Atom = 0x25e03 - Preload Atom = 0x25e07 - Progress Atom = 0x52c08 - Prompt Atom = 0x5fa06 - Public Atom = 0x41e06 - Q Atom = 0x13101 - Radiogroup Atom = 0x30a - Readonly Atom = 0x2fb08 - Rel Atom = 0x25f03 - Required Atom = 0x1d008 - Reversed Atom = 0x5a08 - Rows Atom = 0x9204 - Rowspan Atom = 0x9207 - Rp Atom = 0x1c602 - Rt Atom = 0x13f02 - Ruby Atom = 0xaf04 - S Atom = 0x2c01 - Samp Atom = 0x4e04 - Sandbox Atom = 0xbb07 - Scope Atom = 0x2bd05 - Scoped Atom = 0x2bd06 - Script Atom = 0x3d406 - Seamless Atom = 0x31c08 - Section Atom = 0x4e207 - Select Atom = 0x57a06 - Selected Atom = 0x57a08 - Shape Atom = 0x4f905 - Size Atom = 0x55504 - Sizes Atom = 0x55505 - Small Atom = 0x18f05 - Sortable Atom = 0x58d08 - Sorted Atom = 0x19906 - Source Atom = 0x1aa06 - Spacer Atom = 0x2db06 - Span Atom = 0x9504 - Spellcheck Atom = 0x3230a - Src Atom = 0x3c303 - Srcdoc Atom = 0x3c306 - Srclang Atom = 0x41107 - Start Atom = 0x38605 - Step Atom = 0x5f704 - Strike Atom = 0x53306 - Strong Atom = 0x55906 - Style Atom = 0x61105 - Sub Atom = 0x5a903 - Summary Atom = 0x61607 - Sup Atom = 0x61d03 - Svg Atom = 0x62003 - System Atom = 0x62306 - Tabindex Atom = 0x46308 - Table Atom = 0x42d05 - Target Atom = 0x24b06 - Tbody Atom = 0x2e05 - Td Atom = 0x4702 - Template Atom = 0x62608 - Textarea Atom = 0x2f608 - Tfoot Atom = 0x8c05 - Th Atom = 0x22e02 - Thead Atom = 0x2d405 - Time Atom = 0xdd04 - Title Atom = 0xa105 - Tr Atom = 0x10502 - Track Atom = 0x10505 - Translate Atom = 0x14009 - Tt Atom = 0x5302 - Type Atom = 0x21404 - Typemustmatch Atom = 0x2140d - U Atom = 0xb01 - Ul Atom = 0x8a02 - Usemap Atom = 0x51106 - Value Atom = 0x4005 - Var Atom = 0x11503 - Video Atom = 0x28105 - Wbr Atom = 0x12103 - Width Atom = 0x50705 - Wrap Atom = 0x58704 - Xmp Atom = 0xc103 -) - -const hash0 = 0xc17da63e - -const maxAtomLen = 19 - -var table = [1 << 9]Atom{ - 0x1: 0x48a0b, // onmousemove - 0x2: 0x5e209, // onwaiting - 0x3: 0x1fa13, // onautocompleteerror - 0x4: 0x5fa06, // prompt - 0x7: 0x5eb07, // optimum - 0x8: 0x1604, // mark - 0xa: 0x5ad07, // itemref - 0xb: 0x4fe0a, // onpageshow - 0xc: 0x57a06, // select - 0xd: 0x17b09, // draggable - 0xe: 0x3e03, // nav - 0xf: 0x17507, // command - 0x11: 0xb01, // u - 0x14: 0x2d507, // headers - 0x15: 0x44a08, // datalist - 0x17: 0x4e04, // samp - 0x1a: 0x3fb09, // onkeydown - 0x1b: 0x55f08, // onscroll - 0x1c: 0x15003, // col - 0x20: 0x3c908, // itemprop - 0x21: 0x2780a, // http-equiv - 0x22: 0x61d03, // sup - 0x24: 0x1d008, // required - 0x2b: 0x25e07, // preload - 0x2c: 0x6040d, // onbeforeprint - 0x2d: 0x3600b, // ondragenter - 0x2e: 0x50902, // dt - 0x2f: 0x5a708, // onsubmit - 0x30: 0x27002, // hr - 0x31: 0x32f0d, // oncontextmenu - 0x33: 0x29c05, // image - 0x34: 0x50d07, // onpause - 0x35: 0x25906, // hgroup - 0x36: 0x7704, // ping - 0x37: 0x57808, // onselect - 0x3a: 0x11303, // div - 0x3b: 0x1fa0e, // onautocomplete - 0x40: 0x2eb02, // mi - 0x41: 0x31c08, // seamless - 0x42: 0x2807, // charset - 0x43: 0x8502, // id - 0x44: 0x5200a, // onpopstate - 0x45: 0x3ef03, // del - 0x46: 0x2cb07, // marquee - 0x47: 0x3309, // accesskey - 0x49: 0x8d06, // footer - 0x4a: 0x44e04, // list - 0x4b: 0x2b005, // ismap - 0x51: 0x33804, // menu - 0x52: 0x2f04, // body - 0x55: 0x9a08, // frameset - 0x56: 0x54a07, // onreset - 0x57: 0x12705, // blink - 0x58: 0xa105, // title - 0x59: 0x38807, // article - 0x5b: 0x22e02, // th - 0x5d: 0x13101, // q - 0x5e: 0x3cf04, // open - 0x5f: 0x2fa04, // area - 0x61: 0x44206, // onload - 0x62: 0xda04, // font - 0x63: 0xd604, // base - 0x64: 0x16207, // colspan - 0x65: 0x53707, // keytype - 0x66: 0x11e02, // dl - 0x68: 0x1b008, // fieldset - 0x6a: 0x2eb03, // min - 0x6b: 0x11503, // var - 0x6f: 0x2d506, // header - 0x70: 0x13f02, // rt - 0x71: 0x15008, // colgroup - 0x72: 0x23502, // mn - 0x74: 0x13a07, // onabort - 0x75: 0x3906, // keygen - 0x76: 0x4c209, // onoffline - 0x77: 0x21f09, // challenge - 0x78: 0x2b203, // map - 0x7a: 0x2e902, // h4 - 0x7b: 0x3b607, // onerror - 0x7c: 0x2e109, // maxlength - 0x7d: 0x2f505, // mtext - 0x7e: 0xbb07, // sandbox - 0x7f: 0x58b06, // onsort - 0x80: 0x100a, // malignmark - 0x81: 0x45d04, // meta - 0x82: 0x7b05, // async - 0x83: 0x2a702, // h3 - 0x84: 0x26702, // dd - 0x85: 0x27004, // href - 0x86: 0x6e0a, // mediagroup - 0x87: 0x19406, // coords - 0x88: 0x41107, // srclang - 0x89: 0x34d0a, // ondblclick - 0x8a: 0x4005, // value - 0x8c: 0xe908, // oncancel - 0x8e: 0x3230a, // spellcheck - 0x8f: 0x9a05, // frame - 0x91: 0x12403, // big - 0x94: 0x1f606, // action - 0x95: 0x6903, // dir - 0x97: 0x2fb08, // readonly - 0x99: 0x42d05, // table - 0x9a: 0x61607, // summary - 0x9b: 0x12103, // wbr - 0x9c: 0x30a, // radiogroup - 0x9d: 0x6c04, // name - 0x9f: 0x62306, // system - 0xa1: 0x15d05, // color - 0xa2: 0x7f06, // canvas - 0xa3: 0x25504, // html - 0xa5: 0x56f09, // onseeking - 0xac: 0x4f905, // shape - 0xad: 0x25f03, // rel - 0xae: 0x28510, // oncanplaythrough - 0xaf: 0x3760a, // ondragover - 0xb0: 0x62608, // template - 0xb1: 0x1d80d, // foreignObject - 0xb3: 0x9204, // rows - 0xb6: 0x44e07, // listing - 0xb7: 0x49c06, // output - 0xb9: 0x3310b, // contextmenu - 0xbb: 0x11f03, // low - 0xbc: 0x1c602, // rp - 0xbd: 0x5bb09, // onsuspend - 0xbe: 0x13606, // button - 0xbf: 0x4db04, // desc - 0xc1: 0x4e207, // section - 0xc2: 0x52a0a, // onprogress - 0xc3: 0x59e09, // onstorage - 0xc4: 0x2d204, // math - 0xc5: 0x4503, // alt - 0xc7: 0x8a02, // ul - 0xc8: 0x5107, // pattern - 0xc9: 0x4b60c, // onmousewheel - 0xca: 0x35709, // ondragend - 0xcb: 0xaf04, // ruby - 0xcc: 0xc01, // p - 0xcd: 0x31707, // onclose - 0xce: 0x24205, // meter - 0xcf: 0x11807, // bgsound - 0xd2: 0x25106, // height - 0xd4: 0x101, // b - 0xd5: 0x2c308, // itemtype - 0xd8: 0x1bb07, // caption - 0xd9: 0x10c08, // disabled - 0xdb: 0x33808, // menuitem - 0xdc: 0x62003, // svg - 0xdd: 0x18f05, // small - 0xde: 0x44a04, // data - 0xe0: 0x4cb08, // ononline - 0xe1: 0x2a206, // mglyph - 0xe3: 0x6505, // embed - 0xe4: 0x10502, // tr - 0xe5: 0x46b0b, // onloadstart - 0xe7: 0x3c306, // srcdoc - 0xeb: 0x5c408, // ontoggle - 0xed: 0xe703, // bdo - 0xee: 0x4702, // td - 0xef: 0x8305, // aside - 0xf0: 0x29402, // h2 - 0xf1: 0x52c08, // progress - 0xf2: 0x12c0a, // blockquote - 0xf4: 0xf005, // label - 0xf5: 0x601, // i - 0xf7: 0x9207, // rowspan - 0xfb: 0x51709, // onplaying - 0xfd: 0x2a103, // img - 0xfe: 0xf608, // optgroup - 0xff: 0x42307, // content - 0x101: 0x53e0c, // onratechange - 0x103: 0x3da0c, // onhashchange - 0x104: 0x4807, // details - 0x106: 0x40008, // download - 0x109: 0x14009, // translate - 0x10b: 0x4230f, // contenteditable - 0x10d: 0x36b0b, // ondragleave - 0x10e: 0x2106, // accept - 0x10f: 0x57a08, // selected - 0x112: 0x1f20a, // formaction - 0x113: 0x5b506, // center - 0x115: 0x45510, // onloadedmetadata - 0x116: 0x12804, // link - 0x117: 0xdd04, // time - 0x118: 0x19f0b, // crossorigin - 0x119: 0x3bd07, // onfocus - 0x11a: 0x58704, // wrap - 0x11b: 0x42204, // icon - 0x11d: 0x28105, // video - 0x11e: 0x4de05, // class - 0x121: 0x5d40e, // onvolumechange - 0x122: 0xaa06, // onblur - 0x123: 0x2b909, // itemscope - 0x124: 0x61105, // style - 0x127: 0x41e06, // public - 0x129: 0x2320e, // formnovalidate - 0x12a: 0x58206, // onshow - 0x12c: 0x51706, // onplay - 0x12d: 0x3c804, // cite - 0x12e: 0x2bc02, // ms - 0x12f: 0xdb0c, // ontimeupdate - 0x130: 0x10904, // kind - 0x131: 0x2470a, // formtarget - 0x135: 0x3af07, // onended - 0x136: 0x26506, // hidden - 0x137: 0x2c01, // s - 0x139: 0x2280a, // formmethod - 0x13a: 0x3e805, // input - 0x13c: 0x50b02, // h6 - 0x13d: 0xc902, // ol - 0x13e: 0x3420b, // oncuechange - 0x13f: 0x1e50d, // foreignobject - 0x143: 0x4e70e, // onbeforeunload - 0x144: 0x2bd05, // scope - 0x145: 0x39609, // onemptied - 0x146: 0x14b05, // defer - 0x147: 0xc103, // xmp - 0x148: 0x39f10, // ondurationchange - 0x149: 0x1903, // kbd - 0x14c: 0x47609, // onmessage - 0x14d: 0x60006, // option - 0x14e: 0x2eb09, // minlength - 0x14f: 0x32807, // checked - 0x150: 0xce08, // autoplay - 0x152: 0x202, // br - 0x153: 0x2360a, // novalidate - 0x156: 0x6307, // noembed - 0x159: 0x31007, // onclick - 0x15a: 0x47f0b, // onmousedown - 0x15b: 0x3a708, // onchange - 0x15e: 0x3f209, // oninvalid - 0x15f: 0x2bd06, // scoped - 0x160: 0x18808, // controls - 0x161: 0x30b05, // muted - 0x162: 0x58d08, // sortable - 0x163: 0x51106, // usemap - 0x164: 0x1b80a, // figcaption - 0x165: 0x35706, // ondrag - 0x166: 0x26b04, // high - 0x168: 0x3c303, // src - 0x169: 0x15706, // poster - 0x16b: 0x1670e, // annotation-xml - 0x16c: 0x5f704, // step - 0x16d: 0x4, // abbr - 0x16e: 0x1b06, // dialog - 0x170: 0x1202, // li - 0x172: 0x3ed02, // mo - 0x175: 0x1d803, // for - 0x176: 0x1a803, // ins - 0x178: 0x55504, // size - 0x179: 0x43210, // onlanguagechange - 0x17a: 0x8607, // default - 0x17b: 0x1a03, // bdi - 0x17c: 0x4d30a, // onpagehide - 0x17d: 0x6907, // dirname - 0x17e: 0x21404, // type - 0x17f: 0x1f204, // form - 0x181: 0x28509, // oncanplay - 0x182: 0x6103, // dfn - 0x183: 0x46308, // tabindex - 0x186: 0x6502, // em - 0x187: 0x27404, // lang - 0x189: 0x39108, // dropzone - 0x18a: 0x4080a, // onkeypress - 0x18b: 0x23c08, // datetime - 0x18c: 0x16204, // cols - 0x18d: 0x1, // a - 0x18e: 0x4420c, // onloadeddata - 0x190: 0xa605, // audio - 0x192: 0x2e05, // tbody - 0x193: 0x22c06, // method - 0x195: 0xf404, // loop - 0x196: 0x29606, // iframe - 0x198: 0x2d504, // head - 0x19e: 0x5f108, // manifest - 0x19f: 0xb309, // autofocus - 0x1a0: 0x14904, // code - 0x1a1: 0x55906, // strong - 0x1a2: 0x30308, // multiple - 0x1a3: 0xc05, // param - 0x1a6: 0x21107, // enctype - 0x1a7: 0x5b304, // face - 0x1a8: 0xfd09, // plaintext - 0x1a9: 0x26e02, // h1 - 0x1aa: 0x59509, // onstalled - 0x1ad: 0x3d406, // script - 0x1ae: 0x2db06, // spacer - 0x1af: 0x55108, // onresize - 0x1b0: 0x4a20b, // onmouseover - 0x1b1: 0x5cc08, // onunload - 0x1b2: 0x56708, // onseeked - 0x1b4: 0x2140d, // typemustmatch - 0x1b5: 0x1cc06, // figure - 0x1b6: 0x4950a, // onmouseout - 0x1b7: 0x25e03, // pre - 0x1b8: 0x50705, // width - 0x1b9: 0x19906, // sorted - 0x1bb: 0x5704, // nobr - 0x1be: 0x5302, // tt - 0x1bf: 0x1105, // align - 0x1c0: 0x3e607, // oninput - 0x1c3: 0x41807, // onkeyup - 0x1c6: 0x1c00c, // onafterprint - 0x1c7: 0x210e, // accept-charset - 0x1c8: 0x33c06, // itemid - 0x1c9: 0x3e809, // inputmode - 0x1cb: 0x53306, // strike - 0x1cc: 0x5a903, // sub - 0x1cd: 0x10505, // track - 0x1ce: 0x38605, // start - 0x1d0: 0xd608, // basefont - 0x1d6: 0x1aa06, // source - 0x1d7: 0x18206, // legend - 0x1d8: 0x2d405, // thead - 0x1da: 0x8c05, // tfoot - 0x1dd: 0x1ec06, // object - 0x1de: 0x6e05, // media - 0x1df: 0x1670a, // annotation - 0x1e0: 0x20d0b, // formenctype - 0x1e2: 0x3d208, // noscript - 0x1e4: 0x55505, // sizes - 0x1e5: 0x1fc0c, // autocomplete - 0x1e6: 0x9504, // span - 0x1e7: 0x9808, // noframes - 0x1e8: 0x24b06, // target - 0x1e9: 0x38f06, // ondrop - 0x1ea: 0x2b306, // applet - 0x1ec: 0x5a08, // reversed - 0x1f0: 0x2a907, // isindex - 0x1f3: 0x27008, // hreflang - 0x1f5: 0x2f302, // h5 - 0x1f6: 0x4f307, // address - 0x1fa: 0x2e103, // max - 0x1fb: 0xc30b, // placeholder - 0x1fc: 0x2f608, // textarea - 0x1fe: 0x4ad09, // onmouseup - 0x1ff: 0x3800b, // ondragstart -} - -const atomText = "abbradiogrouparamalignmarkbdialogaccept-charsetbodyaccesskey" + - "genavaluealtdetailsampatternobreversedfnoembedirnamediagroup" + - "ingasyncanvasidefaultfooterowspanoframesetitleaudionblurubya" + - "utofocusandboxmplaceholderautoplaybasefontimeupdatebdoncance" + - "labelooptgrouplaintextrackindisabledivarbgsoundlowbrbigblink" + - "blockquotebuttonabortranslatecodefercolgroupostercolorcolspa" + - "nnotation-xmlcommandraggablegendcontrolsmallcoordsortedcross" + - "originsourcefieldsetfigcaptionafterprintfigurequiredforeignO" + - "bjectforeignobjectformactionautocompleteerrorformenctypemust" + - "matchallengeformmethodformnovalidatetimeterformtargetheightm" + - "lhgroupreloadhiddenhigh1hreflanghttp-equivideoncanplaythroug" + - "h2iframeimageimglyph3isindexismappletitemscopeditemtypemarqu" + - "eematheaderspacermaxlength4minlength5mtextareadonlymultiplem" + - "utedonclickoncloseamlesspellcheckedoncontextmenuitemidoncuec" + - "hangeondblclickondragendondragenterondragleaveondragoverondr" + - "agstarticleondropzonemptiedondurationchangeonendedonerroronf" + - "ocusrcdocitempropenoscriptonhashchangeoninputmodeloninvalido" + - "nkeydownloadonkeypressrclangonkeyupublicontenteditableonlang" + - "uagechangeonloadeddatalistingonloadedmetadatabindexonloadsta" + - "rtonmessageonmousedownonmousemoveonmouseoutputonmouseoveronm" + - "ouseuponmousewheelonofflineononlineonpagehidesclassectionbef" + - "oreunloaddresshapeonpageshowidth6onpausemaponplayingonpopsta" + - "teonprogresstrikeytypeonratechangeonresetonresizestrongonscr" + - "ollonseekedonseekingonselectedonshowraponsortableonstalledon" + - "storageonsubmitemrefacenteronsuspendontoggleonunloadonvolume" + - "changeonwaitingoptimumanifestepromptoptionbeforeprintstylesu" + - "mmarysupsvgsystemplate" diff --git a/vendor/golang.org/x/net/html/charset/charset.go b/vendor/golang.org/x/net/html/charset/charset.go deleted file mode 100644 index 13bed1599f..0000000000 --- a/vendor/golang.org/x/net/html/charset/charset.go +++ /dev/null @@ -1,257 +0,0 @@ -// 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 charset provides common text encodings for HTML documents. -// -// The mapping from encoding labels to encodings is defined at -// https://encoding.spec.whatwg.org/. -package charset // import "golang.org/x/net/html/charset" - -import ( - "bytes" - "fmt" - "io" - "mime" - "strings" - "unicode/utf8" - - "golang.org/x/net/html" - "golang.org/x/text/encoding" - "golang.org/x/text/encoding/charmap" - "golang.org/x/text/encoding/htmlindex" - "golang.org/x/text/transform" -) - -// Lookup returns the encoding with the specified label, and its canonical -// name. It returns nil and the empty string if label is not one of the -// standard encodings for HTML. Matching is case-insensitive and ignores -// leading and trailing whitespace. Encoders will use HTML escape sequences for -// runes that are not supported by the character set. -func Lookup(label string) (e encoding.Encoding, name string) { - e, err := htmlindex.Get(label) - if err != nil { - return nil, "" - } - name, _ = htmlindex.Name(e) - return &htmlEncoding{e}, name -} - -type htmlEncoding struct{ encoding.Encoding } - -func (h *htmlEncoding) NewEncoder() *encoding.Encoder { - // HTML requires a non-terminating legacy encoder. We use HTML escapes to - // substitute unsupported code points. - return encoding.HTMLEscapeUnsupported(h.Encoding.NewEncoder()) -} - -// DetermineEncoding determines the encoding of an HTML document by examining -// up to the first 1024 bytes of content and the declared Content-Type. -// -// See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding -func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool) { - if len(content) > 1024 { - content = content[:1024] - } - - for _, b := range boms { - if bytes.HasPrefix(content, b.bom) { - e, name = Lookup(b.enc) - return e, name, true - } - } - - if _, params, err := mime.ParseMediaType(contentType); err == nil { - if cs, ok := params["charset"]; ok { - if e, name = Lookup(cs); e != nil { - return e, name, true - } - } - } - - if len(content) > 0 { - e, name = prescan(content) - if e != nil { - return e, name, false - } - } - - // Try to detect UTF-8. - // First eliminate any partial rune at the end. - for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { - b := content[i] - if b < 0x80 { - break - } - if utf8.RuneStart(b) { - content = content[:i] - break - } - } - hasHighBit := false - for _, c := range content { - if c >= 0x80 { - hasHighBit = true - break - } - } - if hasHighBit && utf8.Valid(content) { - return encoding.Nop, "utf-8", false - } - - // TODO: change default depending on user's locale? - return charmap.Windows1252, "windows-1252", false -} - -// NewReader returns an io.Reader that converts the content of r to UTF-8. -// It calls DetermineEncoding to find out what r's encoding is. -func NewReader(r io.Reader, contentType string) (io.Reader, error) { - preview := make([]byte, 1024) - n, err := io.ReadFull(r, preview) - switch { - case err == io.ErrUnexpectedEOF: - preview = preview[:n] - r = bytes.NewReader(preview) - case err != nil: - return nil, err - default: - r = io.MultiReader(bytes.NewReader(preview), r) - } - - if e, _, _ := DetermineEncoding(preview, contentType); e != encoding.Nop { - r = transform.NewReader(r, e.NewDecoder()) - } - return r, nil -} - -// NewReaderLabel returns a reader that converts from the specified charset to -// UTF-8. It uses Lookup to find the encoding that corresponds to label, and -// returns an error if Lookup returns nil. It is suitable for use as -// encoding/xml.Decoder's CharsetReader function. -func NewReaderLabel(label string, input io.Reader) (io.Reader, error) { - e, _ := Lookup(label) - if e == nil { - return nil, fmt.Errorf("unsupported charset: %q", label) - } - return transform.NewReader(input, e.NewDecoder()), nil -} - -func prescan(content []byte) (e encoding.Encoding, name string) { - z := html.NewTokenizer(bytes.NewReader(content)) - for { - switch z.Next() { - case html.ErrorToken: - return nil, "" - - case html.StartTagToken, html.SelfClosingTagToken: - tagName, hasAttr := z.TagName() - if !bytes.Equal(tagName, []byte("meta")) { - continue - } - attrList := make(map[string]bool) - gotPragma := false - - const ( - dontKnow = iota - doNeedPragma - doNotNeedPragma - ) - needPragma := dontKnow - - name = "" - e = nil - for hasAttr { - var key, val []byte - key, val, hasAttr = z.TagAttr() - ks := string(key) - if attrList[ks] { - continue - } - attrList[ks] = true - for i, c := range val { - if 'A' <= c && c <= 'Z' { - val[i] = c + 0x20 - } - } - - switch ks { - case "http-equiv": - if bytes.Equal(val, []byte("content-type")) { - gotPragma = true - } - - case "content": - if e == nil { - name = fromMetaElement(string(val)) - if name != "" { - e, name = Lookup(name) - if e != nil { - needPragma = doNeedPragma - } - } - } - - case "charset": - e, name = Lookup(string(val)) - needPragma = doNotNeedPragma - } - } - - if needPragma == dontKnow || needPragma == doNeedPragma && !gotPragma { - continue - } - - if strings.HasPrefix(name, "utf-16") { - name = "utf-8" - e = encoding.Nop - } - - if e != nil { - return e, name - } - } - } -} - -func fromMetaElement(s string) string { - for s != "" { - csLoc := strings.Index(s, "charset") - if csLoc == -1 { - return "" - } - s = s[csLoc+len("charset"):] - s = strings.TrimLeft(s, " \t\n\f\r") - if !strings.HasPrefix(s, "=") { - continue - } - s = s[1:] - s = strings.TrimLeft(s, " \t\n\f\r") - if s == "" { - return "" - } - if q := s[0]; q == '"' || q == '\'' { - s = s[1:] - closeQuote := strings.IndexRune(s, rune(q)) - if closeQuote == -1 { - return "" - } - return s[:closeQuote] - } - - end := strings.IndexAny(s, "; \t\n\f\r") - if end == -1 { - end = len(s) - } - return s[:end] - } - return "" -} - -var boms = []struct { - bom []byte - enc string -}{ - {[]byte{0xfe, 0xff}, "utf-16be"}, - {[]byte{0xff, 0xfe}, "utf-16le"}, - {[]byte{0xef, 0xbb, 0xbf}, "utf-8"}, -} diff --git a/vendor/golang.org/x/net/html/const.go b/vendor/golang.org/x/net/html/const.go deleted file mode 100644 index 52f651ff6d..0000000000 --- a/vendor/golang.org/x/net/html/const.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -// Section 12.2.3.2 of the HTML5 specification says "The following elements -// have varying levels of special parsing rules". -// https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements -var isSpecialElementMap = map[string]bool{ - "address": true, - "applet": true, - "area": true, - "article": true, - "aside": true, - "base": true, - "basefont": true, - "bgsound": true, - "blockquote": true, - "body": true, - "br": true, - "button": true, - "caption": true, - "center": true, - "col": true, - "colgroup": true, - "dd": true, - "details": true, - "dir": true, - "div": true, - "dl": true, - "dt": true, - "embed": true, - "fieldset": true, - "figcaption": true, - "figure": true, - "footer": true, - "form": true, - "frame": true, - "frameset": true, - "h1": true, - "h2": true, - "h3": true, - "h4": true, - "h5": true, - "h6": true, - "head": true, - "header": true, - "hgroup": true, - "hr": true, - "html": true, - "iframe": true, - "img": true, - "input": true, - "isindex": true, - "li": true, - "link": true, - "listing": true, - "marquee": true, - "menu": true, - "meta": true, - "nav": true, - "noembed": true, - "noframes": true, - "noscript": true, - "object": true, - "ol": true, - "p": true, - "param": true, - "plaintext": true, - "pre": true, - "script": true, - "section": true, - "select": true, - "source": true, - "style": true, - "summary": true, - "table": true, - "tbody": true, - "td": true, - "template": true, - "textarea": true, - "tfoot": true, - "th": true, - "thead": true, - "title": true, - "tr": true, - "track": true, - "ul": true, - "wbr": true, - "xmp": true, -} - -func isSpecialElement(element *Node) bool { - switch element.Namespace { - case "", "html": - return isSpecialElementMap[element.Data] - case "svg": - return element.Data == "foreignObject" - } - return false -} diff --git a/vendor/golang.org/x/net/html/doc.go b/vendor/golang.org/x/net/html/doc.go deleted file mode 100644 index 94f496874a..0000000000 --- a/vendor/golang.org/x/net/html/doc.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package html implements an HTML5-compliant tokenizer and parser. - -Tokenization is done by creating a Tokenizer for an io.Reader r. It is the -caller's responsibility to ensure that r provides UTF-8 encoded HTML. - - z := html.NewTokenizer(r) - -Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), -which parses the next token and returns its type, or an error: - - for { - tt := z.Next() - if tt == html.ErrorToken { - // ... - return ... - } - // Process the current token. - } - -There are two APIs for retrieving the current token. The high-level API is to -call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs -allow optionally calling Raw after Next but before Token, Text, TagName, or -TagAttr. In EBNF notation, the valid call sequence per token is: - - Next {Raw} [ Token | Text | TagName {TagAttr} ] - -Token returns an independent data structure that completely describes a token. -Entities (such as "<") are unescaped, tag names and attribute keys are -lower-cased, and attributes are collected into a []Attribute. For example: - - for { - if z.Next() == html.ErrorToken { - // Returning io.EOF indicates success. - return z.Err() - } - emitToken(z.Token()) - } - -The low-level API performs fewer allocations and copies, but the contents of -the []byte values returned by Text, TagName and TagAttr may change on the next -call to Next. For example, to extract an HTML page's anchor text: - - depth := 0 - for { - tt := z.Next() - switch tt { - case ErrorToken: - return z.Err() - case TextToken: - if depth > 0 { - // emitBytes should copy the []byte it receives, - // if it doesn't process it immediately. - emitBytes(z.Text()) - } - case StartTagToken, EndTagToken: - tn, _ := z.TagName() - if len(tn) == 1 && tn[0] == 'a' { - if tt == StartTagToken { - depth++ - } else { - depth-- - } - } - } - } - -Parsing is done by calling Parse with an io.Reader, which returns the root of -the parse tree (the document element) as a *Node. It is the caller's -responsibility to ensure that the Reader provides UTF-8 encoded HTML. For -example, to process each anchor node in depth-first order: - - doc, err := html.Parse(r) - if err != nil { - // ... - } - var f func(*html.Node) - f = func(n *html.Node) { - if n.Type == html.ElementNode && n.Data == "a" { - // Do something with n... - } - for c := n.FirstChild; c != nil; c = c.NextSibling { - f(c) - } - } - f(doc) - -The relevant specifications include: -https://html.spec.whatwg.org/multipage/syntax.html and -https://html.spec.whatwg.org/multipage/syntax.html#tokenization -*/ -package html // import "golang.org/x/net/html" - -// The tokenization algorithm implemented by this package is not a line-by-line -// transliteration of the relatively verbose state-machine in the WHATWG -// specification. A more direct approach is used instead, where the program -// counter implies the state, such as whether it is tokenizing a tag or a text -// node. Specification compliance is verified by checking expected and actual -// outputs over a test suite rather than aiming for algorithmic fidelity. - -// TODO(nigeltao): Does a DOM API belong in this package or a separate one? -// TODO(nigeltao): How does parsing interact with a JavaScript engine? diff --git a/vendor/golang.org/x/net/html/doctype.go b/vendor/golang.org/x/net/html/doctype.go deleted file mode 100644 index c484e5a94f..0000000000 --- a/vendor/golang.org/x/net/html/doctype.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "strings" -) - -// parseDoctype parses the data from a DoctypeToken into a name, -// public identifier, and system identifier. It returns a Node whose Type -// is DoctypeNode, whose Data is the name, and which has attributes -// named "system" and "public" for the two identifiers if they were present. -// quirks is whether the document should be parsed in "quirks mode". -func parseDoctype(s string) (n *Node, quirks bool) { - n = &Node{Type: DoctypeNode} - - // Find the name. - space := strings.IndexAny(s, whitespace) - if space == -1 { - space = len(s) - } - n.Data = s[:space] - // The comparison to "html" is case-sensitive. - if n.Data != "html" { - quirks = true - } - n.Data = strings.ToLower(n.Data) - s = strings.TrimLeft(s[space:], whitespace) - - if len(s) < 6 { - // It can't start with "PUBLIC" or "SYSTEM". - // Ignore the rest of the string. - return n, quirks || s != "" - } - - key := strings.ToLower(s[:6]) - s = s[6:] - for key == "public" || key == "system" { - s = strings.TrimLeft(s, whitespace) - if s == "" { - break - } - quote := s[0] - if quote != '"' && quote != '\'' { - break - } - s = s[1:] - q := strings.IndexRune(s, rune(quote)) - var id string - if q == -1 { - id = s - s = "" - } else { - id = s[:q] - s = s[q+1:] - } - n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) - if key == "public" { - key = "system" - } else { - key = "" - } - } - - if key != "" || s != "" { - quirks = true - } else if len(n.Attr) > 0 { - if n.Attr[0].Key == "public" { - public := strings.ToLower(n.Attr[0].Val) - switch public { - case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": - quirks = true - default: - for _, q := range quirkyIDs { - if strings.HasPrefix(public, q) { - quirks = true - break - } - } - } - // The following two public IDs only cause quirks mode if there is no system ID. - if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || - strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { - quirks = true - } - } - if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && - strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" { - quirks = true - } - } - - return n, quirks -} - -// quirkyIDs is a list of public doctype identifiers that cause a document -// to be interpreted in quirks mode. The identifiers should be in lower case. -var quirkyIDs = []string{ - "+//silmaril//dtd html pro v0r11 19970101//", - "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", - "-//as//dtd html 3.0 aswedit + extensions//", - "-//ietf//dtd html 2.0 level 1//", - "-//ietf//dtd html 2.0 level 2//", - "-//ietf//dtd html 2.0 strict level 1//", - "-//ietf//dtd html 2.0 strict level 2//", - "-//ietf//dtd html 2.0 strict//", - "-//ietf//dtd html 2.0//", - "-//ietf//dtd html 2.1e//", - "-//ietf//dtd html 3.0//", - "-//ietf//dtd html 3.2 final//", - "-//ietf//dtd html 3.2//", - "-//ietf//dtd html 3//", - "-//ietf//dtd html level 0//", - "-//ietf//dtd html level 1//", - "-//ietf//dtd html level 2//", - "-//ietf//dtd html level 3//", - "-//ietf//dtd html strict level 0//", - "-//ietf//dtd html strict level 1//", - "-//ietf//dtd html strict level 2//", - "-//ietf//dtd html strict level 3//", - "-//ietf//dtd html strict//", - "-//ietf//dtd html//", - "-//metrius//dtd metrius presentational//", - "-//microsoft//dtd internet explorer 2.0 html strict//", - "-//microsoft//dtd internet explorer 2.0 html//", - "-//microsoft//dtd internet explorer 2.0 tables//", - "-//microsoft//dtd internet explorer 3.0 html strict//", - "-//microsoft//dtd internet explorer 3.0 html//", - "-//microsoft//dtd internet explorer 3.0 tables//", - "-//netscape comm. corp.//dtd html//", - "-//netscape comm. corp.//dtd strict html//", - "-//o'reilly and associates//dtd html 2.0//", - "-//o'reilly and associates//dtd html extended 1.0//", - "-//o'reilly and associates//dtd html extended relaxed 1.0//", - "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", - "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", - "-//spyglass//dtd html 2.0 extended//", - "-//sq//dtd html 2.0 hotmetal + extensions//", - "-//sun microsystems corp.//dtd hotjava html//", - "-//sun microsystems corp.//dtd hotjava strict html//", - "-//w3c//dtd html 3 1995-03-24//", - "-//w3c//dtd html 3.2 draft//", - "-//w3c//dtd html 3.2 final//", - "-//w3c//dtd html 3.2//", - "-//w3c//dtd html 3.2s draft//", - "-//w3c//dtd html 4.0 frameset//", - "-//w3c//dtd html 4.0 transitional//", - "-//w3c//dtd html experimental 19960712//", - "-//w3c//dtd html experimental 970421//", - "-//w3c//dtd w3 html//", - "-//w3o//dtd w3 html 3.0//", - "-//webtechs//dtd mozilla html 2.0//", - "-//webtechs//dtd mozilla html//", -} diff --git a/vendor/golang.org/x/net/html/entity.go b/vendor/golang.org/x/net/html/entity.go deleted file mode 100644 index a50c04c60e..0000000000 --- a/vendor/golang.org/x/net/html/entity.go +++ /dev/null @@ -1,2253 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -// All entities that do not end with ';' are 6 or fewer bytes long. -const longestEntityWithoutSemicolon = 6 - -// entity is a map from HTML entity names to their values. The semicolon matters: -// https://html.spec.whatwg.org/multipage/syntax.html#named-character-references -// lists both "amp" and "amp;" as two separate entries. -// -// Note that the HTML5 list is larger than the HTML4 list at -// http://www.w3.org/TR/html4/sgml/entities.html -var entity = map[string]rune{ - "AElig;": '\U000000C6', - "AMP;": '\U00000026', - "Aacute;": '\U000000C1', - "Abreve;": '\U00000102', - "Acirc;": '\U000000C2', - "Acy;": '\U00000410', - "Afr;": '\U0001D504', - "Agrave;": '\U000000C0', - "Alpha;": '\U00000391', - "Amacr;": '\U00000100', - "And;": '\U00002A53', - "Aogon;": '\U00000104', - "Aopf;": '\U0001D538', - "ApplyFunction;": '\U00002061', - "Aring;": '\U000000C5', - "Ascr;": '\U0001D49C', - "Assign;": '\U00002254', - "Atilde;": '\U000000C3', - "Auml;": '\U000000C4', - "Backslash;": '\U00002216', - "Barv;": '\U00002AE7', - "Barwed;": '\U00002306', - "Bcy;": '\U00000411', - "Because;": '\U00002235', - "Bernoullis;": '\U0000212C', - "Beta;": '\U00000392', - "Bfr;": '\U0001D505', - "Bopf;": '\U0001D539', - "Breve;": '\U000002D8', - "Bscr;": '\U0000212C', - "Bumpeq;": '\U0000224E', - "CHcy;": '\U00000427', - "COPY;": '\U000000A9', - "Cacute;": '\U00000106', - "Cap;": '\U000022D2', - "CapitalDifferentialD;": '\U00002145', - "Cayleys;": '\U0000212D', - "Ccaron;": '\U0000010C', - "Ccedil;": '\U000000C7', - "Ccirc;": '\U00000108', - "Cconint;": '\U00002230', - "Cdot;": '\U0000010A', - "Cedilla;": '\U000000B8', - "CenterDot;": '\U000000B7', - "Cfr;": '\U0000212D', - "Chi;": '\U000003A7', - "CircleDot;": '\U00002299', - "CircleMinus;": '\U00002296', - "CirclePlus;": '\U00002295', - "CircleTimes;": '\U00002297', - "ClockwiseContourIntegral;": '\U00002232', - "CloseCurlyDoubleQuote;": '\U0000201D', - "CloseCurlyQuote;": '\U00002019', - "Colon;": '\U00002237', - "Colone;": '\U00002A74', - "Congruent;": '\U00002261', - "Conint;": '\U0000222F', - "ContourIntegral;": '\U0000222E', - "Copf;": '\U00002102', - "Coproduct;": '\U00002210', - "CounterClockwiseContourIntegral;": '\U00002233', - "Cross;": '\U00002A2F', - "Cscr;": '\U0001D49E', - "Cup;": '\U000022D3', - "CupCap;": '\U0000224D', - "DD;": '\U00002145', - "DDotrahd;": '\U00002911', - "DJcy;": '\U00000402', - "DScy;": '\U00000405', - "DZcy;": '\U0000040F', - "Dagger;": '\U00002021', - "Darr;": '\U000021A1', - "Dashv;": '\U00002AE4', - "Dcaron;": '\U0000010E', - "Dcy;": '\U00000414', - "Del;": '\U00002207', - "Delta;": '\U00000394', - "Dfr;": '\U0001D507', - "DiacriticalAcute;": '\U000000B4', - "DiacriticalDot;": '\U000002D9', - "DiacriticalDoubleAcute;": '\U000002DD', - "DiacriticalGrave;": '\U00000060', - "DiacriticalTilde;": '\U000002DC', - "Diamond;": '\U000022C4', - "DifferentialD;": '\U00002146', - "Dopf;": '\U0001D53B', - "Dot;": '\U000000A8', - "DotDot;": '\U000020DC', - "DotEqual;": '\U00002250', - "DoubleContourIntegral;": '\U0000222F', - "DoubleDot;": '\U000000A8', - "DoubleDownArrow;": '\U000021D3', - "DoubleLeftArrow;": '\U000021D0', - "DoubleLeftRightArrow;": '\U000021D4', - "DoubleLeftTee;": '\U00002AE4', - "DoubleLongLeftArrow;": '\U000027F8', - "DoubleLongLeftRightArrow;": '\U000027FA', - "DoubleLongRightArrow;": '\U000027F9', - "DoubleRightArrow;": '\U000021D2', - "DoubleRightTee;": '\U000022A8', - "DoubleUpArrow;": '\U000021D1', - "DoubleUpDownArrow;": '\U000021D5', - "DoubleVerticalBar;": '\U00002225', - "DownArrow;": '\U00002193', - "DownArrowBar;": '\U00002913', - "DownArrowUpArrow;": '\U000021F5', - "DownBreve;": '\U00000311', - "DownLeftRightVector;": '\U00002950', - "DownLeftTeeVector;": '\U0000295E', - "DownLeftVector;": '\U000021BD', - "DownLeftVectorBar;": '\U00002956', - "DownRightTeeVector;": '\U0000295F', - "DownRightVector;": '\U000021C1', - "DownRightVectorBar;": '\U00002957', - "DownTee;": '\U000022A4', - "DownTeeArrow;": '\U000021A7', - "Downarrow;": '\U000021D3', - "Dscr;": '\U0001D49F', - "Dstrok;": '\U00000110', - "ENG;": '\U0000014A', - "ETH;": '\U000000D0', - "Eacute;": '\U000000C9', - "Ecaron;": '\U0000011A', - "Ecirc;": '\U000000CA', - "Ecy;": '\U0000042D', - "Edot;": '\U00000116', - "Efr;": '\U0001D508', - "Egrave;": '\U000000C8', - "Element;": '\U00002208', - "Emacr;": '\U00000112', - "EmptySmallSquare;": '\U000025FB', - "EmptyVerySmallSquare;": '\U000025AB', - "Eogon;": '\U00000118', - "Eopf;": '\U0001D53C', - "Epsilon;": '\U00000395', - "Equal;": '\U00002A75', - "EqualTilde;": '\U00002242', - "Equilibrium;": '\U000021CC', - "Escr;": '\U00002130', - "Esim;": '\U00002A73', - "Eta;": '\U00000397', - "Euml;": '\U000000CB', - "Exists;": '\U00002203', - "ExponentialE;": '\U00002147', - "Fcy;": '\U00000424', - "Ffr;": '\U0001D509', - "FilledSmallSquare;": '\U000025FC', - "FilledVerySmallSquare;": '\U000025AA', - "Fopf;": '\U0001D53D', - "ForAll;": '\U00002200', - "Fouriertrf;": '\U00002131', - "Fscr;": '\U00002131', - "GJcy;": '\U00000403', - "GT;": '\U0000003E', - "Gamma;": '\U00000393', - "Gammad;": '\U000003DC', - "Gbreve;": '\U0000011E', - "Gcedil;": '\U00000122', - "Gcirc;": '\U0000011C', - "Gcy;": '\U00000413', - "Gdot;": '\U00000120', - "Gfr;": '\U0001D50A', - "Gg;": '\U000022D9', - "Gopf;": '\U0001D53E', - "GreaterEqual;": '\U00002265', - "GreaterEqualLess;": '\U000022DB', - "GreaterFullEqual;": '\U00002267', - "GreaterGreater;": '\U00002AA2', - "GreaterLess;": '\U00002277', - "GreaterSlantEqual;": '\U00002A7E', - "GreaterTilde;": '\U00002273', - "Gscr;": '\U0001D4A2', - "Gt;": '\U0000226B', - "HARDcy;": '\U0000042A', - "Hacek;": '\U000002C7', - "Hat;": '\U0000005E', - "Hcirc;": '\U00000124', - "Hfr;": '\U0000210C', - "HilbertSpace;": '\U0000210B', - "Hopf;": '\U0000210D', - "HorizontalLine;": '\U00002500', - "Hscr;": '\U0000210B', - "Hstrok;": '\U00000126', - "HumpDownHump;": '\U0000224E', - "HumpEqual;": '\U0000224F', - "IEcy;": '\U00000415', - "IJlig;": '\U00000132', - "IOcy;": '\U00000401', - "Iacute;": '\U000000CD', - "Icirc;": '\U000000CE', - "Icy;": '\U00000418', - "Idot;": '\U00000130', - "Ifr;": '\U00002111', - "Igrave;": '\U000000CC', - "Im;": '\U00002111', - "Imacr;": '\U0000012A', - "ImaginaryI;": '\U00002148', - "Implies;": '\U000021D2', - "Int;": '\U0000222C', - "Integral;": '\U0000222B', - "Intersection;": '\U000022C2', - "InvisibleComma;": '\U00002063', - "InvisibleTimes;": '\U00002062', - "Iogon;": '\U0000012E', - "Iopf;": '\U0001D540', - "Iota;": '\U00000399', - "Iscr;": '\U00002110', - "Itilde;": '\U00000128', - "Iukcy;": '\U00000406', - "Iuml;": '\U000000CF', - "Jcirc;": '\U00000134', - "Jcy;": '\U00000419', - "Jfr;": '\U0001D50D', - "Jopf;": '\U0001D541', - "Jscr;": '\U0001D4A5', - "Jsercy;": '\U00000408', - "Jukcy;": '\U00000404', - "KHcy;": '\U00000425', - "KJcy;": '\U0000040C', - "Kappa;": '\U0000039A', - "Kcedil;": '\U00000136', - "Kcy;": '\U0000041A', - "Kfr;": '\U0001D50E', - "Kopf;": '\U0001D542', - "Kscr;": '\U0001D4A6', - "LJcy;": '\U00000409', - "LT;": '\U0000003C', - "Lacute;": '\U00000139', - "Lambda;": '\U0000039B', - "Lang;": '\U000027EA', - "Laplacetrf;": '\U00002112', - "Larr;": '\U0000219E', - "Lcaron;": '\U0000013D', - "Lcedil;": '\U0000013B', - "Lcy;": '\U0000041B', - "LeftAngleBracket;": '\U000027E8', - "LeftArrow;": '\U00002190', - "LeftArrowBar;": '\U000021E4', - "LeftArrowRightArrow;": '\U000021C6', - "LeftCeiling;": '\U00002308', - "LeftDoubleBracket;": '\U000027E6', - "LeftDownTeeVector;": '\U00002961', - "LeftDownVector;": '\U000021C3', - "LeftDownVectorBar;": '\U00002959', - "LeftFloor;": '\U0000230A', - "LeftRightArrow;": '\U00002194', - "LeftRightVector;": '\U0000294E', - "LeftTee;": '\U000022A3', - "LeftTeeArrow;": '\U000021A4', - "LeftTeeVector;": '\U0000295A', - "LeftTriangle;": '\U000022B2', - "LeftTriangleBar;": '\U000029CF', - "LeftTriangleEqual;": '\U000022B4', - "LeftUpDownVector;": '\U00002951', - "LeftUpTeeVector;": '\U00002960', - "LeftUpVector;": '\U000021BF', - "LeftUpVectorBar;": '\U00002958', - "LeftVector;": '\U000021BC', - "LeftVectorBar;": '\U00002952', - "Leftarrow;": '\U000021D0', - "Leftrightarrow;": '\U000021D4', - "LessEqualGreater;": '\U000022DA', - "LessFullEqual;": '\U00002266', - "LessGreater;": '\U00002276', - "LessLess;": '\U00002AA1', - "LessSlantEqual;": '\U00002A7D', - "LessTilde;": '\U00002272', - "Lfr;": '\U0001D50F', - "Ll;": '\U000022D8', - "Lleftarrow;": '\U000021DA', - "Lmidot;": '\U0000013F', - "LongLeftArrow;": '\U000027F5', - "LongLeftRightArrow;": '\U000027F7', - "LongRightArrow;": '\U000027F6', - "Longleftarrow;": '\U000027F8', - "Longleftrightarrow;": '\U000027FA', - "Longrightarrow;": '\U000027F9', - "Lopf;": '\U0001D543', - "LowerLeftArrow;": '\U00002199', - "LowerRightArrow;": '\U00002198', - "Lscr;": '\U00002112', - "Lsh;": '\U000021B0', - "Lstrok;": '\U00000141', - "Lt;": '\U0000226A', - "Map;": '\U00002905', - "Mcy;": '\U0000041C', - "MediumSpace;": '\U0000205F', - "Mellintrf;": '\U00002133', - "Mfr;": '\U0001D510', - "MinusPlus;": '\U00002213', - "Mopf;": '\U0001D544', - "Mscr;": '\U00002133', - "Mu;": '\U0000039C', - "NJcy;": '\U0000040A', - "Nacute;": '\U00000143', - "Ncaron;": '\U00000147', - "Ncedil;": '\U00000145', - "Ncy;": '\U0000041D', - "NegativeMediumSpace;": '\U0000200B', - "NegativeThickSpace;": '\U0000200B', - "NegativeThinSpace;": '\U0000200B', - "NegativeVeryThinSpace;": '\U0000200B', - "NestedGreaterGreater;": '\U0000226B', - "NestedLessLess;": '\U0000226A', - "NewLine;": '\U0000000A', - "Nfr;": '\U0001D511', - "NoBreak;": '\U00002060', - "NonBreakingSpace;": '\U000000A0', - "Nopf;": '\U00002115', - "Not;": '\U00002AEC', - "NotCongruent;": '\U00002262', - "NotCupCap;": '\U0000226D', - "NotDoubleVerticalBar;": '\U00002226', - "NotElement;": '\U00002209', - "NotEqual;": '\U00002260', - "NotExists;": '\U00002204', - "NotGreater;": '\U0000226F', - "NotGreaterEqual;": '\U00002271', - "NotGreaterLess;": '\U00002279', - "NotGreaterTilde;": '\U00002275', - "NotLeftTriangle;": '\U000022EA', - "NotLeftTriangleEqual;": '\U000022EC', - "NotLess;": '\U0000226E', - "NotLessEqual;": '\U00002270', - "NotLessGreater;": '\U00002278', - "NotLessTilde;": '\U00002274', - "NotPrecedes;": '\U00002280', - "NotPrecedesSlantEqual;": '\U000022E0', - "NotReverseElement;": '\U0000220C', - "NotRightTriangle;": '\U000022EB', - "NotRightTriangleEqual;": '\U000022ED', - "NotSquareSubsetEqual;": '\U000022E2', - "NotSquareSupersetEqual;": '\U000022E3', - "NotSubsetEqual;": '\U00002288', - "NotSucceeds;": '\U00002281', - "NotSucceedsSlantEqual;": '\U000022E1', - "NotSupersetEqual;": '\U00002289', - "NotTilde;": '\U00002241', - "NotTildeEqual;": '\U00002244', - "NotTildeFullEqual;": '\U00002247', - "NotTildeTilde;": '\U00002249', - "NotVerticalBar;": '\U00002224', - "Nscr;": '\U0001D4A9', - "Ntilde;": '\U000000D1', - "Nu;": '\U0000039D', - "OElig;": '\U00000152', - "Oacute;": '\U000000D3', - "Ocirc;": '\U000000D4', - "Ocy;": '\U0000041E', - "Odblac;": '\U00000150', - "Ofr;": '\U0001D512', - "Ograve;": '\U000000D2', - "Omacr;": '\U0000014C', - "Omega;": '\U000003A9', - "Omicron;": '\U0000039F', - "Oopf;": '\U0001D546', - "OpenCurlyDoubleQuote;": '\U0000201C', - "OpenCurlyQuote;": '\U00002018', - "Or;": '\U00002A54', - "Oscr;": '\U0001D4AA', - "Oslash;": '\U000000D8', - "Otilde;": '\U000000D5', - "Otimes;": '\U00002A37', - "Ouml;": '\U000000D6', - "OverBar;": '\U0000203E', - "OverBrace;": '\U000023DE', - "OverBracket;": '\U000023B4', - "OverParenthesis;": '\U000023DC', - "PartialD;": '\U00002202', - "Pcy;": '\U0000041F', - "Pfr;": '\U0001D513', - "Phi;": '\U000003A6', - "Pi;": '\U000003A0', - "PlusMinus;": '\U000000B1', - "Poincareplane;": '\U0000210C', - "Popf;": '\U00002119', - "Pr;": '\U00002ABB', - "Precedes;": '\U0000227A', - "PrecedesEqual;": '\U00002AAF', - "PrecedesSlantEqual;": '\U0000227C', - "PrecedesTilde;": '\U0000227E', - "Prime;": '\U00002033', - "Product;": '\U0000220F', - "Proportion;": '\U00002237', - "Proportional;": '\U0000221D', - "Pscr;": '\U0001D4AB', - "Psi;": '\U000003A8', - "QUOT;": '\U00000022', - "Qfr;": '\U0001D514', - "Qopf;": '\U0000211A', - "Qscr;": '\U0001D4AC', - "RBarr;": '\U00002910', - "REG;": '\U000000AE', - "Racute;": '\U00000154', - "Rang;": '\U000027EB', - "Rarr;": '\U000021A0', - "Rarrtl;": '\U00002916', - "Rcaron;": '\U00000158', - "Rcedil;": '\U00000156', - "Rcy;": '\U00000420', - "Re;": '\U0000211C', - "ReverseElement;": '\U0000220B', - "ReverseEquilibrium;": '\U000021CB', - "ReverseUpEquilibrium;": '\U0000296F', - "Rfr;": '\U0000211C', - "Rho;": '\U000003A1', - "RightAngleBracket;": '\U000027E9', - "RightArrow;": '\U00002192', - "RightArrowBar;": '\U000021E5', - "RightArrowLeftArrow;": '\U000021C4', - "RightCeiling;": '\U00002309', - "RightDoubleBracket;": '\U000027E7', - "RightDownTeeVector;": '\U0000295D', - "RightDownVector;": '\U000021C2', - "RightDownVectorBar;": '\U00002955', - "RightFloor;": '\U0000230B', - "RightTee;": '\U000022A2', - "RightTeeArrow;": '\U000021A6', - "RightTeeVector;": '\U0000295B', - "RightTriangle;": '\U000022B3', - "RightTriangleBar;": '\U000029D0', - "RightTriangleEqual;": '\U000022B5', - "RightUpDownVector;": '\U0000294F', - "RightUpTeeVector;": '\U0000295C', - "RightUpVector;": '\U000021BE', - "RightUpVectorBar;": '\U00002954', - "RightVector;": '\U000021C0', - "RightVectorBar;": '\U00002953', - "Rightarrow;": '\U000021D2', - "Ropf;": '\U0000211D', - "RoundImplies;": '\U00002970', - "Rrightarrow;": '\U000021DB', - "Rscr;": '\U0000211B', - "Rsh;": '\U000021B1', - "RuleDelayed;": '\U000029F4', - "SHCHcy;": '\U00000429', - "SHcy;": '\U00000428', - "SOFTcy;": '\U0000042C', - "Sacute;": '\U0000015A', - "Sc;": '\U00002ABC', - "Scaron;": '\U00000160', - "Scedil;": '\U0000015E', - "Scirc;": '\U0000015C', - "Scy;": '\U00000421', - "Sfr;": '\U0001D516', - "ShortDownArrow;": '\U00002193', - "ShortLeftArrow;": '\U00002190', - "ShortRightArrow;": '\U00002192', - "ShortUpArrow;": '\U00002191', - "Sigma;": '\U000003A3', - "SmallCircle;": '\U00002218', - "Sopf;": '\U0001D54A', - "Sqrt;": '\U0000221A', - "Square;": '\U000025A1', - "SquareIntersection;": '\U00002293', - "SquareSubset;": '\U0000228F', - "SquareSubsetEqual;": '\U00002291', - "SquareSuperset;": '\U00002290', - "SquareSupersetEqual;": '\U00002292', - "SquareUnion;": '\U00002294', - "Sscr;": '\U0001D4AE', - "Star;": '\U000022C6', - "Sub;": '\U000022D0', - "Subset;": '\U000022D0', - "SubsetEqual;": '\U00002286', - "Succeeds;": '\U0000227B', - "SucceedsEqual;": '\U00002AB0', - "SucceedsSlantEqual;": '\U0000227D', - "SucceedsTilde;": '\U0000227F', - "SuchThat;": '\U0000220B', - "Sum;": '\U00002211', - "Sup;": '\U000022D1', - "Superset;": '\U00002283', - "SupersetEqual;": '\U00002287', - "Supset;": '\U000022D1', - "THORN;": '\U000000DE', - "TRADE;": '\U00002122', - "TSHcy;": '\U0000040B', - "TScy;": '\U00000426', - "Tab;": '\U00000009', - "Tau;": '\U000003A4', - "Tcaron;": '\U00000164', - "Tcedil;": '\U00000162', - "Tcy;": '\U00000422', - "Tfr;": '\U0001D517', - "Therefore;": '\U00002234', - "Theta;": '\U00000398', - "ThinSpace;": '\U00002009', - "Tilde;": '\U0000223C', - "TildeEqual;": '\U00002243', - "TildeFullEqual;": '\U00002245', - "TildeTilde;": '\U00002248', - "Topf;": '\U0001D54B', - "TripleDot;": '\U000020DB', - "Tscr;": '\U0001D4AF', - "Tstrok;": '\U00000166', - "Uacute;": '\U000000DA', - "Uarr;": '\U0000219F', - "Uarrocir;": '\U00002949', - "Ubrcy;": '\U0000040E', - "Ubreve;": '\U0000016C', - "Ucirc;": '\U000000DB', - "Ucy;": '\U00000423', - "Udblac;": '\U00000170', - "Ufr;": '\U0001D518', - "Ugrave;": '\U000000D9', - "Umacr;": '\U0000016A', - "UnderBar;": '\U0000005F', - "UnderBrace;": '\U000023DF', - "UnderBracket;": '\U000023B5', - "UnderParenthesis;": '\U000023DD', - "Union;": '\U000022C3', - "UnionPlus;": '\U0000228E', - "Uogon;": '\U00000172', - "Uopf;": '\U0001D54C', - "UpArrow;": '\U00002191', - "UpArrowBar;": '\U00002912', - "UpArrowDownArrow;": '\U000021C5', - "UpDownArrow;": '\U00002195', - "UpEquilibrium;": '\U0000296E', - "UpTee;": '\U000022A5', - "UpTeeArrow;": '\U000021A5', - "Uparrow;": '\U000021D1', - "Updownarrow;": '\U000021D5', - "UpperLeftArrow;": '\U00002196', - "UpperRightArrow;": '\U00002197', - "Upsi;": '\U000003D2', - "Upsilon;": '\U000003A5', - "Uring;": '\U0000016E', - "Uscr;": '\U0001D4B0', - "Utilde;": '\U00000168', - "Uuml;": '\U000000DC', - "VDash;": '\U000022AB', - "Vbar;": '\U00002AEB', - "Vcy;": '\U00000412', - "Vdash;": '\U000022A9', - "Vdashl;": '\U00002AE6', - "Vee;": '\U000022C1', - "Verbar;": '\U00002016', - "Vert;": '\U00002016', - "VerticalBar;": '\U00002223', - "VerticalLine;": '\U0000007C', - "VerticalSeparator;": '\U00002758', - "VerticalTilde;": '\U00002240', - "VeryThinSpace;": '\U0000200A', - "Vfr;": '\U0001D519', - "Vopf;": '\U0001D54D', - "Vscr;": '\U0001D4B1', - "Vvdash;": '\U000022AA', - "Wcirc;": '\U00000174', - "Wedge;": '\U000022C0', - "Wfr;": '\U0001D51A', - "Wopf;": '\U0001D54E', - "Wscr;": '\U0001D4B2', - "Xfr;": '\U0001D51B', - "Xi;": '\U0000039E', - "Xopf;": '\U0001D54F', - "Xscr;": '\U0001D4B3', - "YAcy;": '\U0000042F', - "YIcy;": '\U00000407', - "YUcy;": '\U0000042E', - "Yacute;": '\U000000DD', - "Ycirc;": '\U00000176', - "Ycy;": '\U0000042B', - "Yfr;": '\U0001D51C', - "Yopf;": '\U0001D550', - "Yscr;": '\U0001D4B4', - "Yuml;": '\U00000178', - "ZHcy;": '\U00000416', - "Zacute;": '\U00000179', - "Zcaron;": '\U0000017D', - "Zcy;": '\U00000417', - "Zdot;": '\U0000017B', - "ZeroWidthSpace;": '\U0000200B', - "Zeta;": '\U00000396', - "Zfr;": '\U00002128', - "Zopf;": '\U00002124', - "Zscr;": '\U0001D4B5', - "aacute;": '\U000000E1', - "abreve;": '\U00000103', - "ac;": '\U0000223E', - "acd;": '\U0000223F', - "acirc;": '\U000000E2', - "acute;": '\U000000B4', - "acy;": '\U00000430', - "aelig;": '\U000000E6', - "af;": '\U00002061', - "afr;": '\U0001D51E', - "agrave;": '\U000000E0', - "alefsym;": '\U00002135', - "aleph;": '\U00002135', - "alpha;": '\U000003B1', - "amacr;": '\U00000101', - "amalg;": '\U00002A3F', - "amp;": '\U00000026', - "and;": '\U00002227', - "andand;": '\U00002A55', - "andd;": '\U00002A5C', - "andslope;": '\U00002A58', - "andv;": '\U00002A5A', - "ang;": '\U00002220', - "ange;": '\U000029A4', - "angle;": '\U00002220', - "angmsd;": '\U00002221', - "angmsdaa;": '\U000029A8', - "angmsdab;": '\U000029A9', - "angmsdac;": '\U000029AA', - "angmsdad;": '\U000029AB', - "angmsdae;": '\U000029AC', - "angmsdaf;": '\U000029AD', - "angmsdag;": '\U000029AE', - "angmsdah;": '\U000029AF', - "angrt;": '\U0000221F', - "angrtvb;": '\U000022BE', - "angrtvbd;": '\U0000299D', - "angsph;": '\U00002222', - "angst;": '\U000000C5', - "angzarr;": '\U0000237C', - "aogon;": '\U00000105', - "aopf;": '\U0001D552', - "ap;": '\U00002248', - "apE;": '\U00002A70', - "apacir;": '\U00002A6F', - "ape;": '\U0000224A', - "apid;": '\U0000224B', - "apos;": '\U00000027', - "approx;": '\U00002248', - "approxeq;": '\U0000224A', - "aring;": '\U000000E5', - "ascr;": '\U0001D4B6', - "ast;": '\U0000002A', - "asymp;": '\U00002248', - "asympeq;": '\U0000224D', - "atilde;": '\U000000E3', - "auml;": '\U000000E4', - "awconint;": '\U00002233', - "awint;": '\U00002A11', - "bNot;": '\U00002AED', - "backcong;": '\U0000224C', - "backepsilon;": '\U000003F6', - "backprime;": '\U00002035', - "backsim;": '\U0000223D', - "backsimeq;": '\U000022CD', - "barvee;": '\U000022BD', - "barwed;": '\U00002305', - "barwedge;": '\U00002305', - "bbrk;": '\U000023B5', - "bbrktbrk;": '\U000023B6', - "bcong;": '\U0000224C', - "bcy;": '\U00000431', - "bdquo;": '\U0000201E', - "becaus;": '\U00002235', - "because;": '\U00002235', - "bemptyv;": '\U000029B0', - "bepsi;": '\U000003F6', - "bernou;": '\U0000212C', - "beta;": '\U000003B2', - "beth;": '\U00002136', - "between;": '\U0000226C', - "bfr;": '\U0001D51F', - "bigcap;": '\U000022C2', - "bigcirc;": '\U000025EF', - "bigcup;": '\U000022C3', - "bigodot;": '\U00002A00', - "bigoplus;": '\U00002A01', - "bigotimes;": '\U00002A02', - "bigsqcup;": '\U00002A06', - "bigstar;": '\U00002605', - "bigtriangledown;": '\U000025BD', - "bigtriangleup;": '\U000025B3', - "biguplus;": '\U00002A04', - "bigvee;": '\U000022C1', - "bigwedge;": '\U000022C0', - "bkarow;": '\U0000290D', - "blacklozenge;": '\U000029EB', - "blacksquare;": '\U000025AA', - "blacktriangle;": '\U000025B4', - "blacktriangledown;": '\U000025BE', - "blacktriangleleft;": '\U000025C2', - "blacktriangleright;": '\U000025B8', - "blank;": '\U00002423', - "blk12;": '\U00002592', - "blk14;": '\U00002591', - "blk34;": '\U00002593', - "block;": '\U00002588', - "bnot;": '\U00002310', - "bopf;": '\U0001D553', - "bot;": '\U000022A5', - "bottom;": '\U000022A5', - "bowtie;": '\U000022C8', - "boxDL;": '\U00002557', - "boxDR;": '\U00002554', - "boxDl;": '\U00002556', - "boxDr;": '\U00002553', - "boxH;": '\U00002550', - "boxHD;": '\U00002566', - "boxHU;": '\U00002569', - "boxHd;": '\U00002564', - "boxHu;": '\U00002567', - "boxUL;": '\U0000255D', - "boxUR;": '\U0000255A', - "boxUl;": '\U0000255C', - "boxUr;": '\U00002559', - "boxV;": '\U00002551', - "boxVH;": '\U0000256C', - "boxVL;": '\U00002563', - "boxVR;": '\U00002560', - "boxVh;": '\U0000256B', - "boxVl;": '\U00002562', - "boxVr;": '\U0000255F', - "boxbox;": '\U000029C9', - "boxdL;": '\U00002555', - "boxdR;": '\U00002552', - "boxdl;": '\U00002510', - "boxdr;": '\U0000250C', - "boxh;": '\U00002500', - "boxhD;": '\U00002565', - "boxhU;": '\U00002568', - "boxhd;": '\U0000252C', - "boxhu;": '\U00002534', - "boxminus;": '\U0000229F', - "boxplus;": '\U0000229E', - "boxtimes;": '\U000022A0', - "boxuL;": '\U0000255B', - "boxuR;": '\U00002558', - "boxul;": '\U00002518', - "boxur;": '\U00002514', - "boxv;": '\U00002502', - "boxvH;": '\U0000256A', - "boxvL;": '\U00002561', - "boxvR;": '\U0000255E', - "boxvh;": '\U0000253C', - "boxvl;": '\U00002524', - "boxvr;": '\U0000251C', - "bprime;": '\U00002035', - "breve;": '\U000002D8', - "brvbar;": '\U000000A6', - "bscr;": '\U0001D4B7', - "bsemi;": '\U0000204F', - "bsim;": '\U0000223D', - "bsime;": '\U000022CD', - "bsol;": '\U0000005C', - "bsolb;": '\U000029C5', - "bsolhsub;": '\U000027C8', - "bull;": '\U00002022', - "bullet;": '\U00002022', - "bump;": '\U0000224E', - "bumpE;": '\U00002AAE', - "bumpe;": '\U0000224F', - "bumpeq;": '\U0000224F', - "cacute;": '\U00000107', - "cap;": '\U00002229', - "capand;": '\U00002A44', - "capbrcup;": '\U00002A49', - "capcap;": '\U00002A4B', - "capcup;": '\U00002A47', - "capdot;": '\U00002A40', - "caret;": '\U00002041', - "caron;": '\U000002C7', - "ccaps;": '\U00002A4D', - "ccaron;": '\U0000010D', - "ccedil;": '\U000000E7', - "ccirc;": '\U00000109', - "ccups;": '\U00002A4C', - "ccupssm;": '\U00002A50', - "cdot;": '\U0000010B', - "cedil;": '\U000000B8', - "cemptyv;": '\U000029B2', - "cent;": '\U000000A2', - "centerdot;": '\U000000B7', - "cfr;": '\U0001D520', - "chcy;": '\U00000447', - "check;": '\U00002713', - "checkmark;": '\U00002713', - "chi;": '\U000003C7', - "cir;": '\U000025CB', - "cirE;": '\U000029C3', - "circ;": '\U000002C6', - "circeq;": '\U00002257', - "circlearrowleft;": '\U000021BA', - "circlearrowright;": '\U000021BB', - "circledR;": '\U000000AE', - "circledS;": '\U000024C8', - "circledast;": '\U0000229B', - "circledcirc;": '\U0000229A', - "circleddash;": '\U0000229D', - "cire;": '\U00002257', - "cirfnint;": '\U00002A10', - "cirmid;": '\U00002AEF', - "cirscir;": '\U000029C2', - "clubs;": '\U00002663', - "clubsuit;": '\U00002663', - "colon;": '\U0000003A', - "colone;": '\U00002254', - "coloneq;": '\U00002254', - "comma;": '\U0000002C', - "commat;": '\U00000040', - "comp;": '\U00002201', - "compfn;": '\U00002218', - "complement;": '\U00002201', - "complexes;": '\U00002102', - "cong;": '\U00002245', - "congdot;": '\U00002A6D', - "conint;": '\U0000222E', - "copf;": '\U0001D554', - "coprod;": '\U00002210', - "copy;": '\U000000A9', - "copysr;": '\U00002117', - "crarr;": '\U000021B5', - "cross;": '\U00002717', - "cscr;": '\U0001D4B8', - "csub;": '\U00002ACF', - "csube;": '\U00002AD1', - "csup;": '\U00002AD0', - "csupe;": '\U00002AD2', - "ctdot;": '\U000022EF', - "cudarrl;": '\U00002938', - "cudarrr;": '\U00002935', - "cuepr;": '\U000022DE', - "cuesc;": '\U000022DF', - "cularr;": '\U000021B6', - "cularrp;": '\U0000293D', - "cup;": '\U0000222A', - "cupbrcap;": '\U00002A48', - "cupcap;": '\U00002A46', - "cupcup;": '\U00002A4A', - "cupdot;": '\U0000228D', - "cupor;": '\U00002A45', - "curarr;": '\U000021B7', - "curarrm;": '\U0000293C', - "curlyeqprec;": '\U000022DE', - "curlyeqsucc;": '\U000022DF', - "curlyvee;": '\U000022CE', - "curlywedge;": '\U000022CF', - "curren;": '\U000000A4', - "curvearrowleft;": '\U000021B6', - "curvearrowright;": '\U000021B7', - "cuvee;": '\U000022CE', - "cuwed;": '\U000022CF', - "cwconint;": '\U00002232', - "cwint;": '\U00002231', - "cylcty;": '\U0000232D', - "dArr;": '\U000021D3', - "dHar;": '\U00002965', - "dagger;": '\U00002020', - "daleth;": '\U00002138', - "darr;": '\U00002193', - "dash;": '\U00002010', - "dashv;": '\U000022A3', - "dbkarow;": '\U0000290F', - "dblac;": '\U000002DD', - "dcaron;": '\U0000010F', - "dcy;": '\U00000434', - "dd;": '\U00002146', - "ddagger;": '\U00002021', - "ddarr;": '\U000021CA', - "ddotseq;": '\U00002A77', - "deg;": '\U000000B0', - "delta;": '\U000003B4', - "demptyv;": '\U000029B1', - "dfisht;": '\U0000297F', - "dfr;": '\U0001D521', - "dharl;": '\U000021C3', - "dharr;": '\U000021C2', - "diam;": '\U000022C4', - "diamond;": '\U000022C4', - "diamondsuit;": '\U00002666', - "diams;": '\U00002666', - "die;": '\U000000A8', - "digamma;": '\U000003DD', - "disin;": '\U000022F2', - "div;": '\U000000F7', - "divide;": '\U000000F7', - "divideontimes;": '\U000022C7', - "divonx;": '\U000022C7', - "djcy;": '\U00000452', - "dlcorn;": '\U0000231E', - "dlcrop;": '\U0000230D', - "dollar;": '\U00000024', - "dopf;": '\U0001D555', - "dot;": '\U000002D9', - "doteq;": '\U00002250', - "doteqdot;": '\U00002251', - "dotminus;": '\U00002238', - "dotplus;": '\U00002214', - "dotsquare;": '\U000022A1', - "doublebarwedge;": '\U00002306', - "downarrow;": '\U00002193', - "downdownarrows;": '\U000021CA', - "downharpoonleft;": '\U000021C3', - "downharpoonright;": '\U000021C2', - "drbkarow;": '\U00002910', - "drcorn;": '\U0000231F', - "drcrop;": '\U0000230C', - "dscr;": '\U0001D4B9', - "dscy;": '\U00000455', - "dsol;": '\U000029F6', - "dstrok;": '\U00000111', - "dtdot;": '\U000022F1', - "dtri;": '\U000025BF', - "dtrif;": '\U000025BE', - "duarr;": '\U000021F5', - "duhar;": '\U0000296F', - "dwangle;": '\U000029A6', - "dzcy;": '\U0000045F', - "dzigrarr;": '\U000027FF', - "eDDot;": '\U00002A77', - "eDot;": '\U00002251', - "eacute;": '\U000000E9', - "easter;": '\U00002A6E', - "ecaron;": '\U0000011B', - "ecir;": '\U00002256', - "ecirc;": '\U000000EA', - "ecolon;": '\U00002255', - "ecy;": '\U0000044D', - "edot;": '\U00000117', - "ee;": '\U00002147', - "efDot;": '\U00002252', - "efr;": '\U0001D522', - "eg;": '\U00002A9A', - "egrave;": '\U000000E8', - "egs;": '\U00002A96', - "egsdot;": '\U00002A98', - "el;": '\U00002A99', - "elinters;": '\U000023E7', - "ell;": '\U00002113', - "els;": '\U00002A95', - "elsdot;": '\U00002A97', - "emacr;": '\U00000113', - "empty;": '\U00002205', - "emptyset;": '\U00002205', - "emptyv;": '\U00002205', - "emsp;": '\U00002003', - "emsp13;": '\U00002004', - "emsp14;": '\U00002005', - "eng;": '\U0000014B', - "ensp;": '\U00002002', - "eogon;": '\U00000119', - "eopf;": '\U0001D556', - "epar;": '\U000022D5', - "eparsl;": '\U000029E3', - "eplus;": '\U00002A71', - "epsi;": '\U000003B5', - "epsilon;": '\U000003B5', - "epsiv;": '\U000003F5', - "eqcirc;": '\U00002256', - "eqcolon;": '\U00002255', - "eqsim;": '\U00002242', - "eqslantgtr;": '\U00002A96', - "eqslantless;": '\U00002A95', - "equals;": '\U0000003D', - "equest;": '\U0000225F', - "equiv;": '\U00002261', - "equivDD;": '\U00002A78', - "eqvparsl;": '\U000029E5', - "erDot;": '\U00002253', - "erarr;": '\U00002971', - "escr;": '\U0000212F', - "esdot;": '\U00002250', - "esim;": '\U00002242', - "eta;": '\U000003B7', - "eth;": '\U000000F0', - "euml;": '\U000000EB', - "euro;": '\U000020AC', - "excl;": '\U00000021', - "exist;": '\U00002203', - "expectation;": '\U00002130', - "exponentiale;": '\U00002147', - "fallingdotseq;": '\U00002252', - "fcy;": '\U00000444', - "female;": '\U00002640', - "ffilig;": '\U0000FB03', - "fflig;": '\U0000FB00', - "ffllig;": '\U0000FB04', - "ffr;": '\U0001D523', - "filig;": '\U0000FB01', - "flat;": '\U0000266D', - "fllig;": '\U0000FB02', - "fltns;": '\U000025B1', - "fnof;": '\U00000192', - "fopf;": '\U0001D557', - "forall;": '\U00002200', - "fork;": '\U000022D4', - "forkv;": '\U00002AD9', - "fpartint;": '\U00002A0D', - "frac12;": '\U000000BD', - "frac13;": '\U00002153', - "frac14;": '\U000000BC', - "frac15;": '\U00002155', - "frac16;": '\U00002159', - "frac18;": '\U0000215B', - "frac23;": '\U00002154', - "frac25;": '\U00002156', - "frac34;": '\U000000BE', - "frac35;": '\U00002157', - "frac38;": '\U0000215C', - "frac45;": '\U00002158', - "frac56;": '\U0000215A', - "frac58;": '\U0000215D', - "frac78;": '\U0000215E', - "frasl;": '\U00002044', - "frown;": '\U00002322', - "fscr;": '\U0001D4BB', - "gE;": '\U00002267', - "gEl;": '\U00002A8C', - "gacute;": '\U000001F5', - "gamma;": '\U000003B3', - "gammad;": '\U000003DD', - "gap;": '\U00002A86', - "gbreve;": '\U0000011F', - "gcirc;": '\U0000011D', - "gcy;": '\U00000433', - "gdot;": '\U00000121', - "ge;": '\U00002265', - "gel;": '\U000022DB', - "geq;": '\U00002265', - "geqq;": '\U00002267', - "geqslant;": '\U00002A7E', - "ges;": '\U00002A7E', - "gescc;": '\U00002AA9', - "gesdot;": '\U00002A80', - "gesdoto;": '\U00002A82', - "gesdotol;": '\U00002A84', - "gesles;": '\U00002A94', - "gfr;": '\U0001D524', - "gg;": '\U0000226B', - "ggg;": '\U000022D9', - "gimel;": '\U00002137', - "gjcy;": '\U00000453', - "gl;": '\U00002277', - "glE;": '\U00002A92', - "gla;": '\U00002AA5', - "glj;": '\U00002AA4', - "gnE;": '\U00002269', - "gnap;": '\U00002A8A', - "gnapprox;": '\U00002A8A', - "gne;": '\U00002A88', - "gneq;": '\U00002A88', - "gneqq;": '\U00002269', - "gnsim;": '\U000022E7', - "gopf;": '\U0001D558', - "grave;": '\U00000060', - "gscr;": '\U0000210A', - "gsim;": '\U00002273', - "gsime;": '\U00002A8E', - "gsiml;": '\U00002A90', - "gt;": '\U0000003E', - "gtcc;": '\U00002AA7', - "gtcir;": '\U00002A7A', - "gtdot;": '\U000022D7', - "gtlPar;": '\U00002995', - "gtquest;": '\U00002A7C', - "gtrapprox;": '\U00002A86', - "gtrarr;": '\U00002978', - "gtrdot;": '\U000022D7', - "gtreqless;": '\U000022DB', - "gtreqqless;": '\U00002A8C', - "gtrless;": '\U00002277', - "gtrsim;": '\U00002273', - "hArr;": '\U000021D4', - "hairsp;": '\U0000200A', - "half;": '\U000000BD', - "hamilt;": '\U0000210B', - "hardcy;": '\U0000044A', - "harr;": '\U00002194', - "harrcir;": '\U00002948', - "harrw;": '\U000021AD', - "hbar;": '\U0000210F', - "hcirc;": '\U00000125', - "hearts;": '\U00002665', - "heartsuit;": '\U00002665', - "hellip;": '\U00002026', - "hercon;": '\U000022B9', - "hfr;": '\U0001D525', - "hksearow;": '\U00002925', - "hkswarow;": '\U00002926', - "hoarr;": '\U000021FF', - "homtht;": '\U0000223B', - "hookleftarrow;": '\U000021A9', - "hookrightarrow;": '\U000021AA', - "hopf;": '\U0001D559', - "horbar;": '\U00002015', - "hscr;": '\U0001D4BD', - "hslash;": '\U0000210F', - "hstrok;": '\U00000127', - "hybull;": '\U00002043', - "hyphen;": '\U00002010', - "iacute;": '\U000000ED', - "ic;": '\U00002063', - "icirc;": '\U000000EE', - "icy;": '\U00000438', - "iecy;": '\U00000435', - "iexcl;": '\U000000A1', - "iff;": '\U000021D4', - "ifr;": '\U0001D526', - "igrave;": '\U000000EC', - "ii;": '\U00002148', - "iiiint;": '\U00002A0C', - "iiint;": '\U0000222D', - "iinfin;": '\U000029DC', - "iiota;": '\U00002129', - "ijlig;": '\U00000133', - "imacr;": '\U0000012B', - "image;": '\U00002111', - "imagline;": '\U00002110', - "imagpart;": '\U00002111', - "imath;": '\U00000131', - "imof;": '\U000022B7', - "imped;": '\U000001B5', - "in;": '\U00002208', - "incare;": '\U00002105', - "infin;": '\U0000221E', - "infintie;": '\U000029DD', - "inodot;": '\U00000131', - "int;": '\U0000222B', - "intcal;": '\U000022BA', - "integers;": '\U00002124', - "intercal;": '\U000022BA', - "intlarhk;": '\U00002A17', - "intprod;": '\U00002A3C', - "iocy;": '\U00000451', - "iogon;": '\U0000012F', - "iopf;": '\U0001D55A', - "iota;": '\U000003B9', - "iprod;": '\U00002A3C', - "iquest;": '\U000000BF', - "iscr;": '\U0001D4BE', - "isin;": '\U00002208', - "isinE;": '\U000022F9', - "isindot;": '\U000022F5', - "isins;": '\U000022F4', - "isinsv;": '\U000022F3', - "isinv;": '\U00002208', - "it;": '\U00002062', - "itilde;": '\U00000129', - "iukcy;": '\U00000456', - "iuml;": '\U000000EF', - "jcirc;": '\U00000135', - "jcy;": '\U00000439', - "jfr;": '\U0001D527', - "jmath;": '\U00000237', - "jopf;": '\U0001D55B', - "jscr;": '\U0001D4BF', - "jsercy;": '\U00000458', - "jukcy;": '\U00000454', - "kappa;": '\U000003BA', - "kappav;": '\U000003F0', - "kcedil;": '\U00000137', - "kcy;": '\U0000043A', - "kfr;": '\U0001D528', - "kgreen;": '\U00000138', - "khcy;": '\U00000445', - "kjcy;": '\U0000045C', - "kopf;": '\U0001D55C', - "kscr;": '\U0001D4C0', - "lAarr;": '\U000021DA', - "lArr;": '\U000021D0', - "lAtail;": '\U0000291B', - "lBarr;": '\U0000290E', - "lE;": '\U00002266', - "lEg;": '\U00002A8B', - "lHar;": '\U00002962', - "lacute;": '\U0000013A', - "laemptyv;": '\U000029B4', - "lagran;": '\U00002112', - "lambda;": '\U000003BB', - "lang;": '\U000027E8', - "langd;": '\U00002991', - "langle;": '\U000027E8', - "lap;": '\U00002A85', - "laquo;": '\U000000AB', - "larr;": '\U00002190', - "larrb;": '\U000021E4', - "larrbfs;": '\U0000291F', - "larrfs;": '\U0000291D', - "larrhk;": '\U000021A9', - "larrlp;": '\U000021AB', - "larrpl;": '\U00002939', - "larrsim;": '\U00002973', - "larrtl;": '\U000021A2', - "lat;": '\U00002AAB', - "latail;": '\U00002919', - "late;": '\U00002AAD', - "lbarr;": '\U0000290C', - "lbbrk;": '\U00002772', - "lbrace;": '\U0000007B', - "lbrack;": '\U0000005B', - "lbrke;": '\U0000298B', - "lbrksld;": '\U0000298F', - "lbrkslu;": '\U0000298D', - "lcaron;": '\U0000013E', - "lcedil;": '\U0000013C', - "lceil;": '\U00002308', - "lcub;": '\U0000007B', - "lcy;": '\U0000043B', - "ldca;": '\U00002936', - "ldquo;": '\U0000201C', - "ldquor;": '\U0000201E', - "ldrdhar;": '\U00002967', - "ldrushar;": '\U0000294B', - "ldsh;": '\U000021B2', - "le;": '\U00002264', - "leftarrow;": '\U00002190', - "leftarrowtail;": '\U000021A2', - "leftharpoondown;": '\U000021BD', - "leftharpoonup;": '\U000021BC', - "leftleftarrows;": '\U000021C7', - "leftrightarrow;": '\U00002194', - "leftrightarrows;": '\U000021C6', - "leftrightharpoons;": '\U000021CB', - "leftrightsquigarrow;": '\U000021AD', - "leftthreetimes;": '\U000022CB', - "leg;": '\U000022DA', - "leq;": '\U00002264', - "leqq;": '\U00002266', - "leqslant;": '\U00002A7D', - "les;": '\U00002A7D', - "lescc;": '\U00002AA8', - "lesdot;": '\U00002A7F', - "lesdoto;": '\U00002A81', - "lesdotor;": '\U00002A83', - "lesges;": '\U00002A93', - "lessapprox;": '\U00002A85', - "lessdot;": '\U000022D6', - "lesseqgtr;": '\U000022DA', - "lesseqqgtr;": '\U00002A8B', - "lessgtr;": '\U00002276', - "lesssim;": '\U00002272', - "lfisht;": '\U0000297C', - "lfloor;": '\U0000230A', - "lfr;": '\U0001D529', - "lg;": '\U00002276', - "lgE;": '\U00002A91', - "lhard;": '\U000021BD', - "lharu;": '\U000021BC', - "lharul;": '\U0000296A', - "lhblk;": '\U00002584', - "ljcy;": '\U00000459', - "ll;": '\U0000226A', - "llarr;": '\U000021C7', - "llcorner;": '\U0000231E', - "llhard;": '\U0000296B', - "lltri;": '\U000025FA', - "lmidot;": '\U00000140', - "lmoust;": '\U000023B0', - "lmoustache;": '\U000023B0', - "lnE;": '\U00002268', - "lnap;": '\U00002A89', - "lnapprox;": '\U00002A89', - "lne;": '\U00002A87', - "lneq;": '\U00002A87', - "lneqq;": '\U00002268', - "lnsim;": '\U000022E6', - "loang;": '\U000027EC', - "loarr;": '\U000021FD', - "lobrk;": '\U000027E6', - "longleftarrow;": '\U000027F5', - "longleftrightarrow;": '\U000027F7', - "longmapsto;": '\U000027FC', - "longrightarrow;": '\U000027F6', - "looparrowleft;": '\U000021AB', - "looparrowright;": '\U000021AC', - "lopar;": '\U00002985', - "lopf;": '\U0001D55D', - "loplus;": '\U00002A2D', - "lotimes;": '\U00002A34', - "lowast;": '\U00002217', - "lowbar;": '\U0000005F', - "loz;": '\U000025CA', - "lozenge;": '\U000025CA', - "lozf;": '\U000029EB', - "lpar;": '\U00000028', - "lparlt;": '\U00002993', - "lrarr;": '\U000021C6', - "lrcorner;": '\U0000231F', - "lrhar;": '\U000021CB', - "lrhard;": '\U0000296D', - "lrm;": '\U0000200E', - "lrtri;": '\U000022BF', - "lsaquo;": '\U00002039', - "lscr;": '\U0001D4C1', - "lsh;": '\U000021B0', - "lsim;": '\U00002272', - "lsime;": '\U00002A8D', - "lsimg;": '\U00002A8F', - "lsqb;": '\U0000005B', - "lsquo;": '\U00002018', - "lsquor;": '\U0000201A', - "lstrok;": '\U00000142', - "lt;": '\U0000003C', - "ltcc;": '\U00002AA6', - "ltcir;": '\U00002A79', - "ltdot;": '\U000022D6', - "lthree;": '\U000022CB', - "ltimes;": '\U000022C9', - "ltlarr;": '\U00002976', - "ltquest;": '\U00002A7B', - "ltrPar;": '\U00002996', - "ltri;": '\U000025C3', - "ltrie;": '\U000022B4', - "ltrif;": '\U000025C2', - "lurdshar;": '\U0000294A', - "luruhar;": '\U00002966', - "mDDot;": '\U0000223A', - "macr;": '\U000000AF', - "male;": '\U00002642', - "malt;": '\U00002720', - "maltese;": '\U00002720', - "map;": '\U000021A6', - "mapsto;": '\U000021A6', - "mapstodown;": '\U000021A7', - "mapstoleft;": '\U000021A4', - "mapstoup;": '\U000021A5', - "marker;": '\U000025AE', - "mcomma;": '\U00002A29', - "mcy;": '\U0000043C', - "mdash;": '\U00002014', - "measuredangle;": '\U00002221', - "mfr;": '\U0001D52A', - "mho;": '\U00002127', - "micro;": '\U000000B5', - "mid;": '\U00002223', - "midast;": '\U0000002A', - "midcir;": '\U00002AF0', - "middot;": '\U000000B7', - "minus;": '\U00002212', - "minusb;": '\U0000229F', - "minusd;": '\U00002238', - "minusdu;": '\U00002A2A', - "mlcp;": '\U00002ADB', - "mldr;": '\U00002026', - "mnplus;": '\U00002213', - "models;": '\U000022A7', - "mopf;": '\U0001D55E', - "mp;": '\U00002213', - "mscr;": '\U0001D4C2', - "mstpos;": '\U0000223E', - "mu;": '\U000003BC', - "multimap;": '\U000022B8', - "mumap;": '\U000022B8', - "nLeftarrow;": '\U000021CD', - "nLeftrightarrow;": '\U000021CE', - "nRightarrow;": '\U000021CF', - "nVDash;": '\U000022AF', - "nVdash;": '\U000022AE', - "nabla;": '\U00002207', - "nacute;": '\U00000144', - "nap;": '\U00002249', - "napos;": '\U00000149', - "napprox;": '\U00002249', - "natur;": '\U0000266E', - "natural;": '\U0000266E', - "naturals;": '\U00002115', - "nbsp;": '\U000000A0', - "ncap;": '\U00002A43', - "ncaron;": '\U00000148', - "ncedil;": '\U00000146', - "ncong;": '\U00002247', - "ncup;": '\U00002A42', - "ncy;": '\U0000043D', - "ndash;": '\U00002013', - "ne;": '\U00002260', - "neArr;": '\U000021D7', - "nearhk;": '\U00002924', - "nearr;": '\U00002197', - "nearrow;": '\U00002197', - "nequiv;": '\U00002262', - "nesear;": '\U00002928', - "nexist;": '\U00002204', - "nexists;": '\U00002204', - "nfr;": '\U0001D52B', - "nge;": '\U00002271', - "ngeq;": '\U00002271', - "ngsim;": '\U00002275', - "ngt;": '\U0000226F', - "ngtr;": '\U0000226F', - "nhArr;": '\U000021CE', - "nharr;": '\U000021AE', - "nhpar;": '\U00002AF2', - "ni;": '\U0000220B', - "nis;": '\U000022FC', - "nisd;": '\U000022FA', - "niv;": '\U0000220B', - "njcy;": '\U0000045A', - "nlArr;": '\U000021CD', - "nlarr;": '\U0000219A', - "nldr;": '\U00002025', - "nle;": '\U00002270', - "nleftarrow;": '\U0000219A', - "nleftrightarrow;": '\U000021AE', - "nleq;": '\U00002270', - "nless;": '\U0000226E', - "nlsim;": '\U00002274', - "nlt;": '\U0000226E', - "nltri;": '\U000022EA', - "nltrie;": '\U000022EC', - "nmid;": '\U00002224', - "nopf;": '\U0001D55F', - "not;": '\U000000AC', - "notin;": '\U00002209', - "notinva;": '\U00002209', - "notinvb;": '\U000022F7', - "notinvc;": '\U000022F6', - "notni;": '\U0000220C', - "notniva;": '\U0000220C', - "notnivb;": '\U000022FE', - "notnivc;": '\U000022FD', - "npar;": '\U00002226', - "nparallel;": '\U00002226', - "npolint;": '\U00002A14', - "npr;": '\U00002280', - "nprcue;": '\U000022E0', - "nprec;": '\U00002280', - "nrArr;": '\U000021CF', - "nrarr;": '\U0000219B', - "nrightarrow;": '\U0000219B', - "nrtri;": '\U000022EB', - "nrtrie;": '\U000022ED', - "nsc;": '\U00002281', - "nsccue;": '\U000022E1', - "nscr;": '\U0001D4C3', - "nshortmid;": '\U00002224', - "nshortparallel;": '\U00002226', - "nsim;": '\U00002241', - "nsime;": '\U00002244', - "nsimeq;": '\U00002244', - "nsmid;": '\U00002224', - "nspar;": '\U00002226', - "nsqsube;": '\U000022E2', - "nsqsupe;": '\U000022E3', - "nsub;": '\U00002284', - "nsube;": '\U00002288', - "nsubseteq;": '\U00002288', - "nsucc;": '\U00002281', - "nsup;": '\U00002285', - "nsupe;": '\U00002289', - "nsupseteq;": '\U00002289', - "ntgl;": '\U00002279', - "ntilde;": '\U000000F1', - "ntlg;": '\U00002278', - "ntriangleleft;": '\U000022EA', - "ntrianglelefteq;": '\U000022EC', - "ntriangleright;": '\U000022EB', - "ntrianglerighteq;": '\U000022ED', - "nu;": '\U000003BD', - "num;": '\U00000023', - "numero;": '\U00002116', - "numsp;": '\U00002007', - "nvDash;": '\U000022AD', - "nvHarr;": '\U00002904', - "nvdash;": '\U000022AC', - "nvinfin;": '\U000029DE', - "nvlArr;": '\U00002902', - "nvrArr;": '\U00002903', - "nwArr;": '\U000021D6', - "nwarhk;": '\U00002923', - "nwarr;": '\U00002196', - "nwarrow;": '\U00002196', - "nwnear;": '\U00002927', - "oS;": '\U000024C8', - "oacute;": '\U000000F3', - "oast;": '\U0000229B', - "ocir;": '\U0000229A', - "ocirc;": '\U000000F4', - "ocy;": '\U0000043E', - "odash;": '\U0000229D', - "odblac;": '\U00000151', - "odiv;": '\U00002A38', - "odot;": '\U00002299', - "odsold;": '\U000029BC', - "oelig;": '\U00000153', - "ofcir;": '\U000029BF', - "ofr;": '\U0001D52C', - "ogon;": '\U000002DB', - "ograve;": '\U000000F2', - "ogt;": '\U000029C1', - "ohbar;": '\U000029B5', - "ohm;": '\U000003A9', - "oint;": '\U0000222E', - "olarr;": '\U000021BA', - "olcir;": '\U000029BE', - "olcross;": '\U000029BB', - "oline;": '\U0000203E', - "olt;": '\U000029C0', - "omacr;": '\U0000014D', - "omega;": '\U000003C9', - "omicron;": '\U000003BF', - "omid;": '\U000029B6', - "ominus;": '\U00002296', - "oopf;": '\U0001D560', - "opar;": '\U000029B7', - "operp;": '\U000029B9', - "oplus;": '\U00002295', - "or;": '\U00002228', - "orarr;": '\U000021BB', - "ord;": '\U00002A5D', - "order;": '\U00002134', - "orderof;": '\U00002134', - "ordf;": '\U000000AA', - "ordm;": '\U000000BA', - "origof;": '\U000022B6', - "oror;": '\U00002A56', - "orslope;": '\U00002A57', - "orv;": '\U00002A5B', - "oscr;": '\U00002134', - "oslash;": '\U000000F8', - "osol;": '\U00002298', - "otilde;": '\U000000F5', - "otimes;": '\U00002297', - "otimesas;": '\U00002A36', - "ouml;": '\U000000F6', - "ovbar;": '\U0000233D', - "par;": '\U00002225', - "para;": '\U000000B6', - "parallel;": '\U00002225', - "parsim;": '\U00002AF3', - "parsl;": '\U00002AFD', - "part;": '\U00002202', - "pcy;": '\U0000043F', - "percnt;": '\U00000025', - "period;": '\U0000002E', - "permil;": '\U00002030', - "perp;": '\U000022A5', - "pertenk;": '\U00002031', - "pfr;": '\U0001D52D', - "phi;": '\U000003C6', - "phiv;": '\U000003D5', - "phmmat;": '\U00002133', - "phone;": '\U0000260E', - "pi;": '\U000003C0', - "pitchfork;": '\U000022D4', - "piv;": '\U000003D6', - "planck;": '\U0000210F', - "planckh;": '\U0000210E', - "plankv;": '\U0000210F', - "plus;": '\U0000002B', - "plusacir;": '\U00002A23', - "plusb;": '\U0000229E', - "pluscir;": '\U00002A22', - "plusdo;": '\U00002214', - "plusdu;": '\U00002A25', - "pluse;": '\U00002A72', - "plusmn;": '\U000000B1', - "plussim;": '\U00002A26', - "plustwo;": '\U00002A27', - "pm;": '\U000000B1', - "pointint;": '\U00002A15', - "popf;": '\U0001D561', - "pound;": '\U000000A3', - "pr;": '\U0000227A', - "prE;": '\U00002AB3', - "prap;": '\U00002AB7', - "prcue;": '\U0000227C', - "pre;": '\U00002AAF', - "prec;": '\U0000227A', - "precapprox;": '\U00002AB7', - "preccurlyeq;": '\U0000227C', - "preceq;": '\U00002AAF', - "precnapprox;": '\U00002AB9', - "precneqq;": '\U00002AB5', - "precnsim;": '\U000022E8', - "precsim;": '\U0000227E', - "prime;": '\U00002032', - "primes;": '\U00002119', - "prnE;": '\U00002AB5', - "prnap;": '\U00002AB9', - "prnsim;": '\U000022E8', - "prod;": '\U0000220F', - "profalar;": '\U0000232E', - "profline;": '\U00002312', - "profsurf;": '\U00002313', - "prop;": '\U0000221D', - "propto;": '\U0000221D', - "prsim;": '\U0000227E', - "prurel;": '\U000022B0', - "pscr;": '\U0001D4C5', - "psi;": '\U000003C8', - "puncsp;": '\U00002008', - "qfr;": '\U0001D52E', - "qint;": '\U00002A0C', - "qopf;": '\U0001D562', - "qprime;": '\U00002057', - "qscr;": '\U0001D4C6', - "quaternions;": '\U0000210D', - "quatint;": '\U00002A16', - "quest;": '\U0000003F', - "questeq;": '\U0000225F', - "quot;": '\U00000022', - "rAarr;": '\U000021DB', - "rArr;": '\U000021D2', - "rAtail;": '\U0000291C', - "rBarr;": '\U0000290F', - "rHar;": '\U00002964', - "racute;": '\U00000155', - "radic;": '\U0000221A', - "raemptyv;": '\U000029B3', - "rang;": '\U000027E9', - "rangd;": '\U00002992', - "range;": '\U000029A5', - "rangle;": '\U000027E9', - "raquo;": '\U000000BB', - "rarr;": '\U00002192', - "rarrap;": '\U00002975', - "rarrb;": '\U000021E5', - "rarrbfs;": '\U00002920', - "rarrc;": '\U00002933', - "rarrfs;": '\U0000291E', - "rarrhk;": '\U000021AA', - "rarrlp;": '\U000021AC', - "rarrpl;": '\U00002945', - "rarrsim;": '\U00002974', - "rarrtl;": '\U000021A3', - "rarrw;": '\U0000219D', - "ratail;": '\U0000291A', - "ratio;": '\U00002236', - "rationals;": '\U0000211A', - "rbarr;": '\U0000290D', - "rbbrk;": '\U00002773', - "rbrace;": '\U0000007D', - "rbrack;": '\U0000005D', - "rbrke;": '\U0000298C', - "rbrksld;": '\U0000298E', - "rbrkslu;": '\U00002990', - "rcaron;": '\U00000159', - "rcedil;": '\U00000157', - "rceil;": '\U00002309', - "rcub;": '\U0000007D', - "rcy;": '\U00000440', - "rdca;": '\U00002937', - "rdldhar;": '\U00002969', - "rdquo;": '\U0000201D', - "rdquor;": '\U0000201D', - "rdsh;": '\U000021B3', - "real;": '\U0000211C', - "realine;": '\U0000211B', - "realpart;": '\U0000211C', - "reals;": '\U0000211D', - "rect;": '\U000025AD', - "reg;": '\U000000AE', - "rfisht;": '\U0000297D', - "rfloor;": '\U0000230B', - "rfr;": '\U0001D52F', - "rhard;": '\U000021C1', - "rharu;": '\U000021C0', - "rharul;": '\U0000296C', - "rho;": '\U000003C1', - "rhov;": '\U000003F1', - "rightarrow;": '\U00002192', - "rightarrowtail;": '\U000021A3', - "rightharpoondown;": '\U000021C1', - "rightharpoonup;": '\U000021C0', - "rightleftarrows;": '\U000021C4', - "rightleftharpoons;": '\U000021CC', - "rightrightarrows;": '\U000021C9', - "rightsquigarrow;": '\U0000219D', - "rightthreetimes;": '\U000022CC', - "ring;": '\U000002DA', - "risingdotseq;": '\U00002253', - "rlarr;": '\U000021C4', - "rlhar;": '\U000021CC', - "rlm;": '\U0000200F', - "rmoust;": '\U000023B1', - "rmoustache;": '\U000023B1', - "rnmid;": '\U00002AEE', - "roang;": '\U000027ED', - "roarr;": '\U000021FE', - "robrk;": '\U000027E7', - "ropar;": '\U00002986', - "ropf;": '\U0001D563', - "roplus;": '\U00002A2E', - "rotimes;": '\U00002A35', - "rpar;": '\U00000029', - "rpargt;": '\U00002994', - "rppolint;": '\U00002A12', - "rrarr;": '\U000021C9', - "rsaquo;": '\U0000203A', - "rscr;": '\U0001D4C7', - "rsh;": '\U000021B1', - "rsqb;": '\U0000005D', - "rsquo;": '\U00002019', - "rsquor;": '\U00002019', - "rthree;": '\U000022CC', - "rtimes;": '\U000022CA', - "rtri;": '\U000025B9', - "rtrie;": '\U000022B5', - "rtrif;": '\U000025B8', - "rtriltri;": '\U000029CE', - "ruluhar;": '\U00002968', - "rx;": '\U0000211E', - "sacute;": '\U0000015B', - "sbquo;": '\U0000201A', - "sc;": '\U0000227B', - "scE;": '\U00002AB4', - "scap;": '\U00002AB8', - "scaron;": '\U00000161', - "sccue;": '\U0000227D', - "sce;": '\U00002AB0', - "scedil;": '\U0000015F', - "scirc;": '\U0000015D', - "scnE;": '\U00002AB6', - "scnap;": '\U00002ABA', - "scnsim;": '\U000022E9', - "scpolint;": '\U00002A13', - "scsim;": '\U0000227F', - "scy;": '\U00000441', - "sdot;": '\U000022C5', - "sdotb;": '\U000022A1', - "sdote;": '\U00002A66', - "seArr;": '\U000021D8', - "searhk;": '\U00002925', - "searr;": '\U00002198', - "searrow;": '\U00002198', - "sect;": '\U000000A7', - "semi;": '\U0000003B', - "seswar;": '\U00002929', - "setminus;": '\U00002216', - "setmn;": '\U00002216', - "sext;": '\U00002736', - "sfr;": '\U0001D530', - "sfrown;": '\U00002322', - "sharp;": '\U0000266F', - "shchcy;": '\U00000449', - "shcy;": '\U00000448', - "shortmid;": '\U00002223', - "shortparallel;": '\U00002225', - "shy;": '\U000000AD', - "sigma;": '\U000003C3', - "sigmaf;": '\U000003C2', - "sigmav;": '\U000003C2', - "sim;": '\U0000223C', - "simdot;": '\U00002A6A', - "sime;": '\U00002243', - "simeq;": '\U00002243', - "simg;": '\U00002A9E', - "simgE;": '\U00002AA0', - "siml;": '\U00002A9D', - "simlE;": '\U00002A9F', - "simne;": '\U00002246', - "simplus;": '\U00002A24', - "simrarr;": '\U00002972', - "slarr;": '\U00002190', - "smallsetminus;": '\U00002216', - "smashp;": '\U00002A33', - "smeparsl;": '\U000029E4', - "smid;": '\U00002223', - "smile;": '\U00002323', - "smt;": '\U00002AAA', - "smte;": '\U00002AAC', - "softcy;": '\U0000044C', - "sol;": '\U0000002F', - "solb;": '\U000029C4', - "solbar;": '\U0000233F', - "sopf;": '\U0001D564', - "spades;": '\U00002660', - "spadesuit;": '\U00002660', - "spar;": '\U00002225', - "sqcap;": '\U00002293', - "sqcup;": '\U00002294', - "sqsub;": '\U0000228F', - "sqsube;": '\U00002291', - "sqsubset;": '\U0000228F', - "sqsubseteq;": '\U00002291', - "sqsup;": '\U00002290', - "sqsupe;": '\U00002292', - "sqsupset;": '\U00002290', - "sqsupseteq;": '\U00002292', - "squ;": '\U000025A1', - "square;": '\U000025A1', - "squarf;": '\U000025AA', - "squf;": '\U000025AA', - "srarr;": '\U00002192', - "sscr;": '\U0001D4C8', - "ssetmn;": '\U00002216', - "ssmile;": '\U00002323', - "sstarf;": '\U000022C6', - "star;": '\U00002606', - "starf;": '\U00002605', - "straightepsilon;": '\U000003F5', - "straightphi;": '\U000003D5', - "strns;": '\U000000AF', - "sub;": '\U00002282', - "subE;": '\U00002AC5', - "subdot;": '\U00002ABD', - "sube;": '\U00002286', - "subedot;": '\U00002AC3', - "submult;": '\U00002AC1', - "subnE;": '\U00002ACB', - "subne;": '\U0000228A', - "subplus;": '\U00002ABF', - "subrarr;": '\U00002979', - "subset;": '\U00002282', - "subseteq;": '\U00002286', - "subseteqq;": '\U00002AC5', - "subsetneq;": '\U0000228A', - "subsetneqq;": '\U00002ACB', - "subsim;": '\U00002AC7', - "subsub;": '\U00002AD5', - "subsup;": '\U00002AD3', - "succ;": '\U0000227B', - "succapprox;": '\U00002AB8', - "succcurlyeq;": '\U0000227D', - "succeq;": '\U00002AB0', - "succnapprox;": '\U00002ABA', - "succneqq;": '\U00002AB6', - "succnsim;": '\U000022E9', - "succsim;": '\U0000227F', - "sum;": '\U00002211', - "sung;": '\U0000266A', - "sup;": '\U00002283', - "sup1;": '\U000000B9', - "sup2;": '\U000000B2', - "sup3;": '\U000000B3', - "supE;": '\U00002AC6', - "supdot;": '\U00002ABE', - "supdsub;": '\U00002AD8', - "supe;": '\U00002287', - "supedot;": '\U00002AC4', - "suphsol;": '\U000027C9', - "suphsub;": '\U00002AD7', - "suplarr;": '\U0000297B', - "supmult;": '\U00002AC2', - "supnE;": '\U00002ACC', - "supne;": '\U0000228B', - "supplus;": '\U00002AC0', - "supset;": '\U00002283', - "supseteq;": '\U00002287', - "supseteqq;": '\U00002AC6', - "supsetneq;": '\U0000228B', - "supsetneqq;": '\U00002ACC', - "supsim;": '\U00002AC8', - "supsub;": '\U00002AD4', - "supsup;": '\U00002AD6', - "swArr;": '\U000021D9', - "swarhk;": '\U00002926', - "swarr;": '\U00002199', - "swarrow;": '\U00002199', - "swnwar;": '\U0000292A', - "szlig;": '\U000000DF', - "target;": '\U00002316', - "tau;": '\U000003C4', - "tbrk;": '\U000023B4', - "tcaron;": '\U00000165', - "tcedil;": '\U00000163', - "tcy;": '\U00000442', - "tdot;": '\U000020DB', - "telrec;": '\U00002315', - "tfr;": '\U0001D531', - "there4;": '\U00002234', - "therefore;": '\U00002234', - "theta;": '\U000003B8', - "thetasym;": '\U000003D1', - "thetav;": '\U000003D1', - "thickapprox;": '\U00002248', - "thicksim;": '\U0000223C', - "thinsp;": '\U00002009', - "thkap;": '\U00002248', - "thksim;": '\U0000223C', - "thorn;": '\U000000FE', - "tilde;": '\U000002DC', - "times;": '\U000000D7', - "timesb;": '\U000022A0', - "timesbar;": '\U00002A31', - "timesd;": '\U00002A30', - "tint;": '\U0000222D', - "toea;": '\U00002928', - "top;": '\U000022A4', - "topbot;": '\U00002336', - "topcir;": '\U00002AF1', - "topf;": '\U0001D565', - "topfork;": '\U00002ADA', - "tosa;": '\U00002929', - "tprime;": '\U00002034', - "trade;": '\U00002122', - "triangle;": '\U000025B5', - "triangledown;": '\U000025BF', - "triangleleft;": '\U000025C3', - "trianglelefteq;": '\U000022B4', - "triangleq;": '\U0000225C', - "triangleright;": '\U000025B9', - "trianglerighteq;": '\U000022B5', - "tridot;": '\U000025EC', - "trie;": '\U0000225C', - "triminus;": '\U00002A3A', - "triplus;": '\U00002A39', - "trisb;": '\U000029CD', - "tritime;": '\U00002A3B', - "trpezium;": '\U000023E2', - "tscr;": '\U0001D4C9', - "tscy;": '\U00000446', - "tshcy;": '\U0000045B', - "tstrok;": '\U00000167', - "twixt;": '\U0000226C', - "twoheadleftarrow;": '\U0000219E', - "twoheadrightarrow;": '\U000021A0', - "uArr;": '\U000021D1', - "uHar;": '\U00002963', - "uacute;": '\U000000FA', - "uarr;": '\U00002191', - "ubrcy;": '\U0000045E', - "ubreve;": '\U0000016D', - "ucirc;": '\U000000FB', - "ucy;": '\U00000443', - "udarr;": '\U000021C5', - "udblac;": '\U00000171', - "udhar;": '\U0000296E', - "ufisht;": '\U0000297E', - "ufr;": '\U0001D532', - "ugrave;": '\U000000F9', - "uharl;": '\U000021BF', - "uharr;": '\U000021BE', - "uhblk;": '\U00002580', - "ulcorn;": '\U0000231C', - "ulcorner;": '\U0000231C', - "ulcrop;": '\U0000230F', - "ultri;": '\U000025F8', - "umacr;": '\U0000016B', - "uml;": '\U000000A8', - "uogon;": '\U00000173', - "uopf;": '\U0001D566', - "uparrow;": '\U00002191', - "updownarrow;": '\U00002195', - "upharpoonleft;": '\U000021BF', - "upharpoonright;": '\U000021BE', - "uplus;": '\U0000228E', - "upsi;": '\U000003C5', - "upsih;": '\U000003D2', - "upsilon;": '\U000003C5', - "upuparrows;": '\U000021C8', - "urcorn;": '\U0000231D', - "urcorner;": '\U0000231D', - "urcrop;": '\U0000230E', - "uring;": '\U0000016F', - "urtri;": '\U000025F9', - "uscr;": '\U0001D4CA', - "utdot;": '\U000022F0', - "utilde;": '\U00000169', - "utri;": '\U000025B5', - "utrif;": '\U000025B4', - "uuarr;": '\U000021C8', - "uuml;": '\U000000FC', - "uwangle;": '\U000029A7', - "vArr;": '\U000021D5', - "vBar;": '\U00002AE8', - "vBarv;": '\U00002AE9', - "vDash;": '\U000022A8', - "vangrt;": '\U0000299C', - "varepsilon;": '\U000003F5', - "varkappa;": '\U000003F0', - "varnothing;": '\U00002205', - "varphi;": '\U000003D5', - "varpi;": '\U000003D6', - "varpropto;": '\U0000221D', - "varr;": '\U00002195', - "varrho;": '\U000003F1', - "varsigma;": '\U000003C2', - "vartheta;": '\U000003D1', - "vartriangleleft;": '\U000022B2', - "vartriangleright;": '\U000022B3', - "vcy;": '\U00000432', - "vdash;": '\U000022A2', - "vee;": '\U00002228', - "veebar;": '\U000022BB', - "veeeq;": '\U0000225A', - "vellip;": '\U000022EE', - "verbar;": '\U0000007C', - "vert;": '\U0000007C', - "vfr;": '\U0001D533', - "vltri;": '\U000022B2', - "vopf;": '\U0001D567', - "vprop;": '\U0000221D', - "vrtri;": '\U000022B3', - "vscr;": '\U0001D4CB', - "vzigzag;": '\U0000299A', - "wcirc;": '\U00000175', - "wedbar;": '\U00002A5F', - "wedge;": '\U00002227', - "wedgeq;": '\U00002259', - "weierp;": '\U00002118', - "wfr;": '\U0001D534', - "wopf;": '\U0001D568', - "wp;": '\U00002118', - "wr;": '\U00002240', - "wreath;": '\U00002240', - "wscr;": '\U0001D4CC', - "xcap;": '\U000022C2', - "xcirc;": '\U000025EF', - "xcup;": '\U000022C3', - "xdtri;": '\U000025BD', - "xfr;": '\U0001D535', - "xhArr;": '\U000027FA', - "xharr;": '\U000027F7', - "xi;": '\U000003BE', - "xlArr;": '\U000027F8', - "xlarr;": '\U000027F5', - "xmap;": '\U000027FC', - "xnis;": '\U000022FB', - "xodot;": '\U00002A00', - "xopf;": '\U0001D569', - "xoplus;": '\U00002A01', - "xotime;": '\U00002A02', - "xrArr;": '\U000027F9', - "xrarr;": '\U000027F6', - "xscr;": '\U0001D4CD', - "xsqcup;": '\U00002A06', - "xuplus;": '\U00002A04', - "xutri;": '\U000025B3', - "xvee;": '\U000022C1', - "xwedge;": '\U000022C0', - "yacute;": '\U000000FD', - "yacy;": '\U0000044F', - "ycirc;": '\U00000177', - "ycy;": '\U0000044B', - "yen;": '\U000000A5', - "yfr;": '\U0001D536', - "yicy;": '\U00000457', - "yopf;": '\U0001D56A', - "yscr;": '\U0001D4CE', - "yucy;": '\U0000044E', - "yuml;": '\U000000FF', - "zacute;": '\U0000017A', - "zcaron;": '\U0000017E', - "zcy;": '\U00000437', - "zdot;": '\U0000017C', - "zeetrf;": '\U00002128', - "zeta;": '\U000003B6', - "zfr;": '\U0001D537', - "zhcy;": '\U00000436', - "zigrarr;": '\U000021DD', - "zopf;": '\U0001D56B', - "zscr;": '\U0001D4CF', - "zwj;": '\U0000200D', - "zwnj;": '\U0000200C', - "AElig": '\U000000C6', - "AMP": '\U00000026', - "Aacute": '\U000000C1', - "Acirc": '\U000000C2', - "Agrave": '\U000000C0', - "Aring": '\U000000C5', - "Atilde": '\U000000C3', - "Auml": '\U000000C4', - "COPY": '\U000000A9', - "Ccedil": '\U000000C7', - "ETH": '\U000000D0', - "Eacute": '\U000000C9', - "Ecirc": '\U000000CA', - "Egrave": '\U000000C8', - "Euml": '\U000000CB', - "GT": '\U0000003E', - "Iacute": '\U000000CD', - "Icirc": '\U000000CE', - "Igrave": '\U000000CC', - "Iuml": '\U000000CF', - "LT": '\U0000003C', - "Ntilde": '\U000000D1', - "Oacute": '\U000000D3', - "Ocirc": '\U000000D4', - "Ograve": '\U000000D2', - "Oslash": '\U000000D8', - "Otilde": '\U000000D5', - "Ouml": '\U000000D6', - "QUOT": '\U00000022', - "REG": '\U000000AE', - "THORN": '\U000000DE', - "Uacute": '\U000000DA', - "Ucirc": '\U000000DB', - "Ugrave": '\U000000D9', - "Uuml": '\U000000DC', - "Yacute": '\U000000DD', - "aacute": '\U000000E1', - "acirc": '\U000000E2', - "acute": '\U000000B4', - "aelig": '\U000000E6', - "agrave": '\U000000E0', - "amp": '\U00000026', - "aring": '\U000000E5', - "atilde": '\U000000E3', - "auml": '\U000000E4', - "brvbar": '\U000000A6', - "ccedil": '\U000000E7', - "cedil": '\U000000B8', - "cent": '\U000000A2', - "copy": '\U000000A9', - "curren": '\U000000A4', - "deg": '\U000000B0', - "divide": '\U000000F7', - "eacute": '\U000000E9', - "ecirc": '\U000000EA', - "egrave": '\U000000E8', - "eth": '\U000000F0', - "euml": '\U000000EB', - "frac12": '\U000000BD', - "frac14": '\U000000BC', - "frac34": '\U000000BE', - "gt": '\U0000003E', - "iacute": '\U000000ED', - "icirc": '\U000000EE', - "iexcl": '\U000000A1', - "igrave": '\U000000EC', - "iquest": '\U000000BF', - "iuml": '\U000000EF', - "laquo": '\U000000AB', - "lt": '\U0000003C', - "macr": '\U000000AF', - "micro": '\U000000B5', - "middot": '\U000000B7', - "nbsp": '\U000000A0', - "not": '\U000000AC', - "ntilde": '\U000000F1', - "oacute": '\U000000F3', - "ocirc": '\U000000F4', - "ograve": '\U000000F2', - "ordf": '\U000000AA', - "ordm": '\U000000BA', - "oslash": '\U000000F8', - "otilde": '\U000000F5', - "ouml": '\U000000F6', - "para": '\U000000B6', - "plusmn": '\U000000B1', - "pound": '\U000000A3', - "quot": '\U00000022', - "raquo": '\U000000BB', - "reg": '\U000000AE', - "sect": '\U000000A7', - "shy": '\U000000AD', - "sup1": '\U000000B9', - "sup2": '\U000000B2', - "sup3": '\U000000B3', - "szlig": '\U000000DF', - "thorn": '\U000000FE', - "times": '\U000000D7', - "uacute": '\U000000FA', - "ucirc": '\U000000FB', - "ugrave": '\U000000F9', - "uml": '\U000000A8', - "uuml": '\U000000FC', - "yacute": '\U000000FD', - "yen": '\U000000A5', - "yuml": '\U000000FF', -} - -// HTML entities that are two unicode codepoints. -var entity2 = map[string][2]rune{ - // TODO(nigeltao): Handle replacements that are wider than their names. - // "nLt;": {'\u226A', '\u20D2'}, - // "nGt;": {'\u226B', '\u20D2'}, - "NotEqualTilde;": {'\u2242', '\u0338'}, - "NotGreaterFullEqual;": {'\u2267', '\u0338'}, - "NotGreaterGreater;": {'\u226B', '\u0338'}, - "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, - "NotHumpDownHump;": {'\u224E', '\u0338'}, - "NotHumpEqual;": {'\u224F', '\u0338'}, - "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, - "NotLessLess;": {'\u226A', '\u0338'}, - "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, - "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, - "NotNestedLessLess;": {'\u2AA1', '\u0338'}, - "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, - "NotRightTriangleBar;": {'\u29D0', '\u0338'}, - "NotSquareSubset;": {'\u228F', '\u0338'}, - "NotSquareSuperset;": {'\u2290', '\u0338'}, - "NotSubset;": {'\u2282', '\u20D2'}, - "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, - "NotSucceedsTilde;": {'\u227F', '\u0338'}, - "NotSuperset;": {'\u2283', '\u20D2'}, - "ThickSpace;": {'\u205F', '\u200A'}, - "acE;": {'\u223E', '\u0333'}, - "bne;": {'\u003D', '\u20E5'}, - "bnequiv;": {'\u2261', '\u20E5'}, - "caps;": {'\u2229', '\uFE00'}, - "cups;": {'\u222A', '\uFE00'}, - "fjlig;": {'\u0066', '\u006A'}, - "gesl;": {'\u22DB', '\uFE00'}, - "gvertneqq;": {'\u2269', '\uFE00'}, - "gvnE;": {'\u2269', '\uFE00'}, - "lates;": {'\u2AAD', '\uFE00'}, - "lesg;": {'\u22DA', '\uFE00'}, - "lvertneqq;": {'\u2268', '\uFE00'}, - "lvnE;": {'\u2268', '\uFE00'}, - "nGg;": {'\u22D9', '\u0338'}, - "nGtv;": {'\u226B', '\u0338'}, - "nLl;": {'\u22D8', '\u0338'}, - "nLtv;": {'\u226A', '\u0338'}, - "nang;": {'\u2220', '\u20D2'}, - "napE;": {'\u2A70', '\u0338'}, - "napid;": {'\u224B', '\u0338'}, - "nbump;": {'\u224E', '\u0338'}, - "nbumpe;": {'\u224F', '\u0338'}, - "ncongdot;": {'\u2A6D', '\u0338'}, - "nedot;": {'\u2250', '\u0338'}, - "nesim;": {'\u2242', '\u0338'}, - "ngE;": {'\u2267', '\u0338'}, - "ngeqq;": {'\u2267', '\u0338'}, - "ngeqslant;": {'\u2A7E', '\u0338'}, - "nges;": {'\u2A7E', '\u0338'}, - "nlE;": {'\u2266', '\u0338'}, - "nleqq;": {'\u2266', '\u0338'}, - "nleqslant;": {'\u2A7D', '\u0338'}, - "nles;": {'\u2A7D', '\u0338'}, - "notinE;": {'\u22F9', '\u0338'}, - "notindot;": {'\u22F5', '\u0338'}, - "nparsl;": {'\u2AFD', '\u20E5'}, - "npart;": {'\u2202', '\u0338'}, - "npre;": {'\u2AAF', '\u0338'}, - "npreceq;": {'\u2AAF', '\u0338'}, - "nrarrc;": {'\u2933', '\u0338'}, - "nrarrw;": {'\u219D', '\u0338'}, - "nsce;": {'\u2AB0', '\u0338'}, - "nsubE;": {'\u2AC5', '\u0338'}, - "nsubset;": {'\u2282', '\u20D2'}, - "nsubseteqq;": {'\u2AC5', '\u0338'}, - "nsucceq;": {'\u2AB0', '\u0338'}, - "nsupE;": {'\u2AC6', '\u0338'}, - "nsupset;": {'\u2283', '\u20D2'}, - "nsupseteqq;": {'\u2AC6', '\u0338'}, - "nvap;": {'\u224D', '\u20D2'}, - "nvge;": {'\u2265', '\u20D2'}, - "nvgt;": {'\u003E', '\u20D2'}, - "nvle;": {'\u2264', '\u20D2'}, - "nvlt;": {'\u003C', '\u20D2'}, - "nvltrie;": {'\u22B4', '\u20D2'}, - "nvrtrie;": {'\u22B5', '\u20D2'}, - "nvsim;": {'\u223C', '\u20D2'}, - "race;": {'\u223D', '\u0331'}, - "smtes;": {'\u2AAC', '\uFE00'}, - "sqcaps;": {'\u2293', '\uFE00'}, - "sqcups;": {'\u2294', '\uFE00'}, - "varsubsetneq;": {'\u228A', '\uFE00'}, - "varsubsetneqq;": {'\u2ACB', '\uFE00'}, - "varsupsetneq;": {'\u228B', '\uFE00'}, - "varsupsetneqq;": {'\u2ACC', '\uFE00'}, - "vnsub;": {'\u2282', '\u20D2'}, - "vnsup;": {'\u2283', '\u20D2'}, - "vsubnE;": {'\u2ACB', '\uFE00'}, - "vsubne;": {'\u228A', '\uFE00'}, - "vsupnE;": {'\u2ACC', '\uFE00'}, - "vsupne;": {'\u228B', '\uFE00'}, -} diff --git a/vendor/golang.org/x/net/html/escape.go b/vendor/golang.org/x/net/html/escape.go deleted file mode 100644 index d856139620..0000000000 --- a/vendor/golang.org/x/net/html/escape.go +++ /dev/null @@ -1,258 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "bytes" - "strings" - "unicode/utf8" -) - -// These replacements permit compatibility with old numeric entities that -// assumed Windows-1252 encoding. -// https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference -var replacementTable = [...]rune{ - '\u20AC', // First entry is what 0x80 should be replaced with. - '\u0081', - '\u201A', - '\u0192', - '\u201E', - '\u2026', - '\u2020', - '\u2021', - '\u02C6', - '\u2030', - '\u0160', - '\u2039', - '\u0152', - '\u008D', - '\u017D', - '\u008F', - '\u0090', - '\u2018', - '\u2019', - '\u201C', - '\u201D', - '\u2022', - '\u2013', - '\u2014', - '\u02DC', - '\u2122', - '\u0161', - '\u203A', - '\u0153', - '\u009D', - '\u017E', - '\u0178', // Last entry is 0x9F. - // 0x00->'\uFFFD' is handled programmatically. - // 0x0D->'\u000D' is a no-op. -} - -// unescapeEntity reads an entity like "<" from b[src:] and writes the -// corresponding "<" to b[dst:], returning the incremented dst and src cursors. -// Precondition: b[src] == '&' && dst <= src. -// attribute should be true if parsing an attribute value. -func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { - // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference - - // i starts at 1 because we already know that s[0] == '&'. - i, s := 1, b[src:] - - if len(s) <= 1 { - b[dst] = b[src] - return dst + 1, src + 1 - } - - if s[i] == '#' { - if len(s) <= 3 { // We need to have at least "&#.". - b[dst] = b[src] - return dst + 1, src + 1 - } - i++ - c := s[i] - hex := false - if c == 'x' || c == 'X' { - hex = true - i++ - } - - x := '\x00' - for i < len(s) { - c = s[i] - i++ - if hex { - if '0' <= c && c <= '9' { - x = 16*x + rune(c) - '0' - continue - } else if 'a' <= c && c <= 'f' { - x = 16*x + rune(c) - 'a' + 10 - continue - } else if 'A' <= c && c <= 'F' { - x = 16*x + rune(c) - 'A' + 10 - continue - } - } else if '0' <= c && c <= '9' { - x = 10*x + rune(c) - '0' - continue - } - if c != ';' { - i-- - } - break - } - - if i <= 3 { // No characters matched. - b[dst] = b[src] - return dst + 1, src + 1 - } - - if 0x80 <= x && x <= 0x9F { - // Replace characters from Windows-1252 with UTF-8 equivalents. - x = replacementTable[x-0x80] - } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { - // Replace invalid characters with the replacement character. - x = '\uFFFD' - } - - return dst + utf8.EncodeRune(b[dst:], x), src + i - } - - // Consume the maximum number of characters possible, with the - // consumed characters matching one of the named references. - - for i < len(s) { - c := s[i] - i++ - // Lower-cased characters are more common in entities, so we check for them first. - if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { - continue - } - if c != ';' { - i-- - } - break - } - - entityName := string(s[1:i]) - if entityName == "" { - // No-op. - } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { - // No-op. - } else if x := entity[entityName]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + i - } else if x := entity2[entityName]; x[0] != 0 { - dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) - return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i - } else if !attribute { - maxLen := len(entityName) - 1 - if maxLen > longestEntityWithoutSemicolon { - maxLen = longestEntityWithoutSemicolon - } - for j := maxLen; j > 1; j-- { - if x := entity[entityName[:j]]; x != 0 { - return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 - } - } - } - - dst1, src1 = dst+i, src+i - copy(b[dst:dst1], b[src:src1]) - return dst1, src1 -} - -// unescape unescapes b's entities in-place, so that "a<b" becomes "a': - esc = ">" - case '"': - // """ is shorter than """. - esc = """ - case '\r': - esc = " " - default: - panic("unrecognized escape character") - } - s = s[i+1:] - if _, err := w.WriteString(esc); err != nil { - return err - } - i = strings.IndexAny(s, escapedChars) - } - _, err := w.WriteString(s) - return err -} - -// EscapeString escapes special characters like "<" to become "<". It -// escapes only five such characters: <, >, &, ' and ". -// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't -// always true. -func EscapeString(s string) string { - if strings.IndexAny(s, escapedChars) == -1 { - return s - } - var buf bytes.Buffer - escape(&buf, s) - return buf.String() -} - -// UnescapeString unescapes entities like "<" to become "<". It unescapes a -// larger range of entities than EscapeString escapes. For example, "á" -// unescapes to "á", as does "á" and "&xE1;". -// UnescapeString(EscapeString(s)) == s always holds, but the converse isn't -// always true. -func UnescapeString(s string) string { - for _, c := range s { - if c == '&' { - return string(unescape([]byte(s), false)) - } - } - return s -} diff --git a/vendor/golang.org/x/net/html/foreign.go b/vendor/golang.org/x/net/html/foreign.go deleted file mode 100644 index d3b3844099..0000000000 --- a/vendor/golang.org/x/net/html/foreign.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "strings" -) - -func adjustAttributeNames(aa []Attribute, nameMap map[string]string) { - for i := range aa { - if newName, ok := nameMap[aa[i].Key]; ok { - aa[i].Key = newName - } - } -} - -func adjustForeignAttributes(aa []Attribute) { - for i, a := range aa { - if a.Key == "" || a.Key[0] != 'x' { - continue - } - switch a.Key { - case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", - "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": - j := strings.Index(a.Key, ":") - aa[i].Namespace = a.Key[:j] - aa[i].Key = a.Key[j+1:] - } - } -} - -func htmlIntegrationPoint(n *Node) bool { - if n.Type != ElementNode { - return false - } - switch n.Namespace { - case "math": - if n.Data == "annotation-xml" { - for _, a := range n.Attr { - if a.Key == "encoding" { - val := strings.ToLower(a.Val) - if val == "text/html" || val == "application/xhtml+xml" { - return true - } - } - } - } - case "svg": - switch n.Data { - case "desc", "foreignObject", "title": - return true - } - } - return false -} - -func mathMLTextIntegrationPoint(n *Node) bool { - if n.Namespace != "math" { - return false - } - switch n.Data { - case "mi", "mo", "mn", "ms", "mtext": - return true - } - return false -} - -// Section 12.2.5.5. -var breakout = map[string]bool{ - "b": true, - "big": true, - "blockquote": true, - "body": true, - "br": true, - "center": true, - "code": true, - "dd": true, - "div": true, - "dl": true, - "dt": true, - "em": true, - "embed": true, - "h1": true, - "h2": true, - "h3": true, - "h4": true, - "h5": true, - "h6": true, - "head": true, - "hr": true, - "i": true, - "img": true, - "li": true, - "listing": true, - "menu": true, - "meta": true, - "nobr": true, - "ol": true, - "p": true, - "pre": true, - "ruby": true, - "s": true, - "small": true, - "span": true, - "strong": true, - "strike": true, - "sub": true, - "sup": true, - "table": true, - "tt": true, - "u": true, - "ul": true, - "var": true, -} - -// Section 12.2.5.5. -var svgTagNameAdjustments = map[string]string{ - "altglyph": "altGlyph", - "altglyphdef": "altGlyphDef", - "altglyphitem": "altGlyphItem", - "animatecolor": "animateColor", - "animatemotion": "animateMotion", - "animatetransform": "animateTransform", - "clippath": "clipPath", - "feblend": "feBlend", - "fecolormatrix": "feColorMatrix", - "fecomponenttransfer": "feComponentTransfer", - "fecomposite": "feComposite", - "feconvolvematrix": "feConvolveMatrix", - "fediffuselighting": "feDiffuseLighting", - "fedisplacementmap": "feDisplacementMap", - "fedistantlight": "feDistantLight", - "feflood": "feFlood", - "fefunca": "feFuncA", - "fefuncb": "feFuncB", - "fefuncg": "feFuncG", - "fefuncr": "feFuncR", - "fegaussianblur": "feGaussianBlur", - "feimage": "feImage", - "femerge": "feMerge", - "femergenode": "feMergeNode", - "femorphology": "feMorphology", - "feoffset": "feOffset", - "fepointlight": "fePointLight", - "fespecularlighting": "feSpecularLighting", - "fespotlight": "feSpotLight", - "fetile": "feTile", - "feturbulence": "feTurbulence", - "foreignobject": "foreignObject", - "glyphref": "glyphRef", - "lineargradient": "linearGradient", - "radialgradient": "radialGradient", - "textpath": "textPath", -} - -// Section 12.2.5.1 -var mathMLAttributeAdjustments = map[string]string{ - "definitionurl": "definitionURL", -} - -var svgAttributeAdjustments = map[string]string{ - "attributename": "attributeName", - "attributetype": "attributeType", - "basefrequency": "baseFrequency", - "baseprofile": "baseProfile", - "calcmode": "calcMode", - "clippathunits": "clipPathUnits", - "contentscripttype": "contentScriptType", - "contentstyletype": "contentStyleType", - "diffuseconstant": "diffuseConstant", - "edgemode": "edgeMode", - "externalresourcesrequired": "externalResourcesRequired", - "filterres": "filterRes", - "filterunits": "filterUnits", - "glyphref": "glyphRef", - "gradienttransform": "gradientTransform", - "gradientunits": "gradientUnits", - "kernelmatrix": "kernelMatrix", - "kernelunitlength": "kernelUnitLength", - "keypoints": "keyPoints", - "keysplines": "keySplines", - "keytimes": "keyTimes", - "lengthadjust": "lengthAdjust", - "limitingconeangle": "limitingConeAngle", - "markerheight": "markerHeight", - "markerunits": "markerUnits", - "markerwidth": "markerWidth", - "maskcontentunits": "maskContentUnits", - "maskunits": "maskUnits", - "numoctaves": "numOctaves", - "pathlength": "pathLength", - "patterncontentunits": "patternContentUnits", - "patterntransform": "patternTransform", - "patternunits": "patternUnits", - "pointsatx": "pointsAtX", - "pointsaty": "pointsAtY", - "pointsatz": "pointsAtZ", - "preservealpha": "preserveAlpha", - "preserveaspectratio": "preserveAspectRatio", - "primitiveunits": "primitiveUnits", - "refx": "refX", - "refy": "refY", - "repeatcount": "repeatCount", - "repeatdur": "repeatDur", - "requiredextensions": "requiredExtensions", - "requiredfeatures": "requiredFeatures", - "specularconstant": "specularConstant", - "specularexponent": "specularExponent", - "spreadmethod": "spreadMethod", - "startoffset": "startOffset", - "stddeviation": "stdDeviation", - "stitchtiles": "stitchTiles", - "surfacescale": "surfaceScale", - "systemlanguage": "systemLanguage", - "tablevalues": "tableValues", - "targetx": "targetX", - "targety": "targetY", - "textlength": "textLength", - "viewbox": "viewBox", - "viewtarget": "viewTarget", - "xchannelselector": "xChannelSelector", - "ychannelselector": "yChannelSelector", - "zoomandpan": "zoomAndPan", -} diff --git a/vendor/golang.org/x/net/html/node.go b/vendor/golang.org/x/net/html/node.go deleted file mode 100644 index 26b657aec8..0000000000 --- a/vendor/golang.org/x/net/html/node.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "golang.org/x/net/html/atom" -) - -// A NodeType is the type of a Node. -type NodeType uint32 - -const ( - ErrorNode NodeType = iota - TextNode - DocumentNode - ElementNode - CommentNode - DoctypeNode - scopeMarkerNode -) - -// Section 12.2.3.3 says "scope markers are inserted when entering applet -// elements, buttons, object elements, marquees, table cells, and table -// captions, and are used to prevent formatting from 'leaking'". -var scopeMarker = Node{Type: scopeMarkerNode} - -// A Node consists of a NodeType and some Data (tag name for element nodes, -// content for text) and are part of a tree of Nodes. Element nodes may also -// have a Namespace and contain a slice of Attributes. Data is unescaped, so -// that it looks like "a 0 { - return (*s)[i-1] - } - return nil -} - -// index returns the index of the top-most occurrence of n in the stack, or -1 -// if n is not present. -func (s *nodeStack) index(n *Node) int { - for i := len(*s) - 1; i >= 0; i-- { - if (*s)[i] == n { - return i - } - } - return -1 -} - -// insert inserts a node at the given index. -func (s *nodeStack) insert(i int, n *Node) { - (*s) = append(*s, nil) - copy((*s)[i+1:], (*s)[i:]) - (*s)[i] = n -} - -// remove removes a node from the stack. It is a no-op if n is not present. -func (s *nodeStack) remove(n *Node) { - i := s.index(n) - if i == -1 { - return - } - copy((*s)[i:], (*s)[i+1:]) - j := len(*s) - 1 - (*s)[j] = nil - *s = (*s)[:j] -} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go deleted file mode 100644 index be4b2bf5aa..0000000000 --- a/vendor/golang.org/x/net/html/parse.go +++ /dev/null @@ -1,2094 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package html - -import ( - "errors" - "fmt" - "io" - "strings" - - a "golang.org/x/net/html/atom" -) - -// A parser implements the HTML5 parsing algorithm: -// https://html.spec.whatwg.org/multipage/syntax.html#tree-construction -type parser struct { - // tokenizer provides the tokens for the parser. - tokenizer *Tokenizer - // tok is the most recently read token. - tok Token - // Self-closing tags like
are treated as start tags, except that - // hasSelfClosingToken is set while they are being processed. - hasSelfClosingToken bool - // doc is the document root element. - doc *Node - // The stack of open elements (section 12.2.3.2) and active formatting - // elements (section 12.2.3.3). - oe, afe nodeStack - // Element pointers (section 12.2.3.4). - head, form *Node - // Other parsing state flags (section 12.2.3.5). - scripting, framesetOK bool - // im is the current insertion mode. - im insertionMode - // originalIM is the insertion mode to go back to after completing a text - // or inTableText insertion mode. - originalIM insertionMode - // fosterParenting is whether new elements should be inserted according to - // the foster parenting rules (section 12.2.5.3). - fosterParenting bool - // quirks is whether the parser is operating in "quirks mode." - quirks bool - // fragment is whether the parser is parsing an HTML fragment. - fragment bool - // context is the context element when parsing an HTML fragment - // (section 12.4). - context *Node -} - -func (p *parser) top() *Node { - if n := p.oe.top(); n != nil { - return n - } - return p.doc -} - -// Stop tags for use in popUntil. These come from section 12.2.3.2. -var ( - defaultScopeStopTags = map[string][]a.Atom{ - "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, - "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, - "svg": {a.Desc, a.ForeignObject, a.Title}, - } -) - -type scope int - -const ( - defaultScope scope = iota - listItemScope - buttonScope - tableScope - tableRowScope - tableBodyScope - selectScope -) - -// popUntil pops the stack of open elements at the highest element whose tag -// is in matchTags, provided there is no higher element in the scope's stop -// tags (as defined in section 12.2.3.2). It returns whether or not there was -// such an element. If there was not, popUntil leaves the stack unchanged. -// -// For example, the set of stop tags for table scope is: "html", "table". If -// the stack was: -// ["html", "body", "font", "table", "b", "i", "u"] -// then popUntil(tableScope, "font") would return false, but -// popUntil(tableScope, "i") would return true and the stack would become: -// ["html", "body", "font", "table", "b"] -// -// If an element's tag is in both the stop tags and matchTags, then the stack -// will be popped and the function returns true (provided, of course, there was -// no higher element in the stack that was also in the stop tags). For example, -// popUntil(tableScope, "table") returns true and leaves: -// ["html", "body", "font"] -func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { - if i := p.indexOfElementInScope(s, matchTags...); i != -1 { - p.oe = p.oe[:i] - return true - } - return false -} - -// indexOfElementInScope returns the index in p.oe of the highest element whose -// tag is in matchTags that is in scope. If no matching element is in scope, it -// returns -1. -func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { - for i := len(p.oe) - 1; i >= 0; i-- { - tagAtom := p.oe[i].DataAtom - if p.oe[i].Namespace == "" { - for _, t := range matchTags { - if t == tagAtom { - return i - } - } - switch s { - case defaultScope: - // No-op. - case listItemScope: - if tagAtom == a.Ol || tagAtom == a.Ul { - return -1 - } - case buttonScope: - if tagAtom == a.Button { - return -1 - } - case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { - return -1 - } - case selectScope: - if tagAtom != a.Optgroup && tagAtom != a.Option { - return -1 - } - default: - panic("unreachable") - } - } - switch s { - case defaultScope, listItemScope, buttonScope: - for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { - if t == tagAtom { - return -1 - } - } - } - } - return -1 -} - -// elementInScope is like popUntil, except that it doesn't modify the stack of -// open elements. -func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { - return p.indexOfElementInScope(s, matchTags...) != -1 -} - -// clearStackToContext pops elements off the stack of open elements until a -// scope-defined element is found. -func (p *parser) clearStackToContext(s scope) { - for i := len(p.oe) - 1; i >= 0; i-- { - tagAtom := p.oe[i].DataAtom - switch s { - case tableScope: - if tagAtom == a.Html || tagAtom == a.Table { - p.oe = p.oe[:i+1] - return - } - case tableRowScope: - if tagAtom == a.Html || tagAtom == a.Tr { - p.oe = p.oe[:i+1] - return - } - case tableBodyScope: - if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { - p.oe = p.oe[:i+1] - return - } - default: - panic("unreachable") - } - } -} - -// generateImpliedEndTags pops nodes off the stack of open elements as long as -// the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. -// If exceptions are specified, nodes with that name will not be popped off. -func (p *parser) generateImpliedEndTags(exceptions ...string) { - var i int -loop: - for i = len(p.oe) - 1; i >= 0; i-- { - n := p.oe[i] - if n.Type == ElementNode { - switch n.DataAtom { - case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: - for _, except := range exceptions { - if n.Data == except { - break loop - } - } - continue - } - } - break - } - - p.oe = p.oe[:i+1] -} - -// addChild adds a child node n to the top element, and pushes n onto the stack -// of open elements if it is an element node. -func (p *parser) addChild(n *Node) { - if p.shouldFosterParent() { - p.fosterParent(n) - } else { - p.top().AppendChild(n) - } - - if n.Type == ElementNode { - p.oe = append(p.oe, n) - } -} - -// shouldFosterParent returns whether the next node to be added should be -// foster parented. -func (p *parser) shouldFosterParent() bool { - if p.fosterParenting { - switch p.top().DataAtom { - case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: - return true - } - } - return false -} - -// fosterParent adds a child node according to the foster parenting rules. -// Section 12.2.5.3, "foster parenting". -func (p *parser) fosterParent(n *Node) { - var table, parent, prev *Node - var i int - for i = len(p.oe) - 1; i >= 0; i-- { - if p.oe[i].DataAtom == a.Table { - table = p.oe[i] - break - } - } - - if table == nil { - // The foster parent is the html element. - parent = p.oe[0] - } else { - parent = table.Parent - } - if parent == nil { - parent = p.oe[i-1] - } - - if table != nil { - prev = table.PrevSibling - } else { - prev = parent.LastChild - } - if prev != nil && prev.Type == TextNode && n.Type == TextNode { - prev.Data += n.Data - return - } - - parent.InsertBefore(n, table) -} - -// addText adds text to the preceding node if it is a text node, or else it -// calls addChild with a new text node. -func (p *parser) addText(text string) { - if text == "" { - return - } - - if p.shouldFosterParent() { - p.fosterParent(&Node{ - Type: TextNode, - Data: text, - }) - return - } - - t := p.top() - if n := t.LastChild; n != nil && n.Type == TextNode { - n.Data += text - return - } - p.addChild(&Node{ - Type: TextNode, - Data: text, - }) -} - -// addElement adds a child element based on the current token. -func (p *parser) addElement() { - p.addChild(&Node{ - Type: ElementNode, - DataAtom: p.tok.DataAtom, - Data: p.tok.Data, - Attr: p.tok.Attr, - }) -} - -// Section 12.2.3.3. -func (p *parser) addFormattingElement() { - tagAtom, attr := p.tok.DataAtom, p.tok.Attr - p.addElement() - - // Implement the Noah's Ark clause, but with three per family instead of two. - identicalElements := 0 -findIdenticalElements: - for i := len(p.afe) - 1; i >= 0; i-- { - n := p.afe[i] - if n.Type == scopeMarkerNode { - break - } - if n.Type != ElementNode { - continue - } - if n.Namespace != "" { - continue - } - if n.DataAtom != tagAtom { - continue - } - if len(n.Attr) != len(attr) { - continue - } - compareAttributes: - for _, t0 := range n.Attr { - for _, t1 := range attr { - if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val { - // Found a match for this attribute, continue with the next attribute. - continue compareAttributes - } - } - // If we get here, there is no attribute that matches a. - // Therefore the element is not identical to the new one. - continue findIdenticalElements - } - - identicalElements++ - if identicalElements >= 3 { - p.afe.remove(n) - } - } - - p.afe = append(p.afe, p.top()) -} - -// Section 12.2.3.3. -func (p *parser) clearActiveFormattingElements() { - for { - n := p.afe.pop() - if len(p.afe) == 0 || n.Type == scopeMarkerNode { - return - } - } -} - -// Section 12.2.3.3. -func (p *parser) reconstructActiveFormattingElements() { - n := p.afe.top() - if n == nil { - return - } - if n.Type == scopeMarkerNode || p.oe.index(n) != -1 { - return - } - i := len(p.afe) - 1 - for n.Type != scopeMarkerNode && p.oe.index(n) == -1 { - if i == 0 { - i = -1 - break - } - i-- - n = p.afe[i] - } - for { - i++ - clone := p.afe[i].clone() - p.addChild(clone) - p.afe[i] = clone - if i == len(p.afe)-1 { - break - } - } -} - -// Section 12.2.4. -func (p *parser) acknowledgeSelfClosingTag() { - p.hasSelfClosingToken = false -} - -// An insertion mode (section 12.2.3.1) is the state transition function from -// a particular state in the HTML5 parser's state machine. It updates the -// parser's fields depending on parser.tok (where ErrorToken means EOF). -// It returns whether the token was consumed. -type insertionMode func(*parser) bool - -// setOriginalIM sets the insertion mode to return to after completing a text or -// inTableText insertion mode. -// Section 12.2.3.1, "using the rules for". -func (p *parser) setOriginalIM() { - if p.originalIM != nil { - panic("html: bad parser state: originalIM was set twice") - } - p.originalIM = p.im -} - -// Section 12.2.3.1, "reset the insertion mode". -func (p *parser) resetInsertionMode() { - for i := len(p.oe) - 1; i >= 0; i-- { - n := p.oe[i] - if i == 0 && p.context != nil { - n = p.context - } - - switch n.DataAtom { - case a.Select: - p.im = inSelectIM - case a.Td, a.Th: - p.im = inCellIM - case a.Tr: - p.im = inRowIM - case a.Tbody, a.Thead, a.Tfoot: - p.im = inTableBodyIM - case a.Caption: - p.im = inCaptionIM - case a.Colgroup: - p.im = inColumnGroupIM - case a.Table: - p.im = inTableIM - case a.Head: - p.im = inBodyIM - case a.Body: - p.im = inBodyIM - case a.Frameset: - p.im = inFramesetIM - case a.Html: - p.im = beforeHeadIM - default: - continue - } - return - } - p.im = inBodyIM -} - -const whitespace = " \t\r\n\f" - -// Section 12.2.5.4.1. -func initialIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case CommentToken: - p.doc.AppendChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - n, quirks := parseDoctype(p.tok.Data) - p.doc.AppendChild(n) - p.quirks = quirks - p.im = beforeHTMLIM - return true - } - p.quirks = true - p.im = beforeHTMLIM - return false -} - -// Section 12.2.5.4.2. -func beforeHTMLIM(p *parser) bool { - switch p.tok.Type { - case DoctypeToken: - // Ignore the token. - return true - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case StartTagToken: - if p.tok.DataAtom == a.Html { - p.addElement() - p.im = beforeHeadIM - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head, a.Body, a.Html, a.Br: - p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) - return false - default: - // Ignore the token. - return true - } - case CommentToken: - p.doc.AppendChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - } - p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) - return false -} - -// Section 12.2.5.4.3. -func beforeHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) - if len(p.tok.Data) == 0 { - // It was all whitespace, so ignore it. - return true - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Head: - p.addElement() - p.head = p.top() - p.im = inHeadIM - return true - case a.Html: - return inBodyIM(p) - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head, a.Body, a.Html, a.Br: - p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) - return false - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) - return false -} - -// Section 12.2.5.4.4. -func inHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - s := strings.TrimLeft(p.tok.Data, whitespace) - if len(s) < len(p.tok.Data) { - // Add the initial whitespace to the current node. - p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) - if s == "" { - return true - } - p.tok.Data = s - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Html: - return inBodyIM(p) - case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta: - p.addElement() - p.oe.pop() - p.acknowledgeSelfClosingTag() - return true - case a.Script, a.Title, a.Noscript, a.Noframes, a.Style: - p.addElement() - p.setOriginalIM() - p.im = textIM - return true - case a.Head: - // Ignore the token. - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Head: - n := p.oe.pop() - if n.DataAtom != a.Head { - panic("html: bad parser state: element not found, in the in-head insertion mode") - } - p.im = afterHeadIM - return true - case a.Body, a.Html, a.Br: - p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) - return false - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) - return false -} - -// Section 12.2.5.4.6. -func afterHeadIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - s := strings.TrimLeft(p.tok.Data, whitespace) - if len(s) < len(p.tok.Data) { - // Add the initial whitespace to the current node. - p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) - if s == "" { - return true - } - p.tok.Data = s - } - case StartTagToken: - switch p.tok.DataAtom { - case a.Html: - return inBodyIM(p) - case a.Body: - p.addElement() - p.framesetOK = false - p.im = inBodyIM - return true - case a.Frameset: - p.addElement() - p.im = inFramesetIM - return true - case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: - p.oe = append(p.oe, p.head) - defer p.oe.remove(p.head) - return inHeadIM(p) - case a.Head: - // Ignore the token. - return true - } - case EndTagToken: - switch p.tok.DataAtom { - case a.Body, a.Html, a.Br: - // Drop down to creating an implied tag. - default: - // Ignore the token. - return true - } - case CommentToken: - p.addChild(&Node{ - Type: CommentNode, - Data: p.tok.Data, - }) - return true - case DoctypeToken: - // Ignore the token. - return true - } - - p.parseImpliedToken(StartTagToken, a.Body, a.Body.String()) - p.framesetOK = true - return false -} - -// copyAttributes copies attributes of src not found on dst to dst. -func copyAttributes(dst *Node, src Token) { - if len(src.Attr) == 0 { - return - } - attr := map[string]string{} - for _, t := range dst.Attr { - attr[t.Key] = t.Val - } - for _, t := range src.Attr { - if _, ok := attr[t.Key]; !ok { - dst.Attr = append(dst.Attr, t) - attr[t.Key] = t.Val - } - } -} - -// Section 12.2.5.4.7. -func inBodyIM(p *parser) bool { - switch p.tok.Type { - case TextToken: - d := p.tok.Data - switch n := p.oe.top(); n.DataAtom { - case a.Pre, a.Listing: - if n.FirstChild == nil { - // Ignore a newline at the start of a
 block.
-				if d != "" && d[0] == '\r' {
-					d = d[1:]
-				}
-				if d != "" && d[0] == '\n' {
-					d = d[1:]
-				}
-			}
-		}
-		d = strings.Replace(d, "\x00", "", -1)
-		if d == "" {
-			return true
-		}
-		p.reconstructActiveFormattingElements()
-		p.addText(d)
-		if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
-			// There were non-whitespace characters inserted.
-			p.framesetOK = false
-		}
-	case StartTagToken:
-		switch p.tok.DataAtom {
-		case a.Html:
-			copyAttributes(p.oe[0], p.tok)
-		case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title:
-			return inHeadIM(p)
-		case a.Body:
-			if len(p.oe) >= 2 {
-				body := p.oe[1]
-				if body.Type == ElementNode && body.DataAtom == a.Body {
-					p.framesetOK = false
-					copyAttributes(body, p.tok)
-				}
-			}
-		case a.Frameset:
-			if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
-				// Ignore the token.
-				return true
-			}
-			body := p.oe[1]
-			if body.Parent != nil {
-				body.Parent.RemoveChild(body)
-			}
-			p.oe = p.oe[:1]
-			p.addElement()
-			p.im = inFramesetIM
-			return true
-		case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-			p.popUntil(buttonScope, a.P)
-			switch n := p.top(); n.DataAtom {
-			case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-				p.oe.pop()
-			}
-			p.addElement()
-		case a.Pre, a.Listing:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-			// The newline, if any, will be dealt with by the TextToken case.
-			p.framesetOK = false
-		case a.Form:
-			if p.form == nil {
-				p.popUntil(buttonScope, a.P)
-				p.addElement()
-				p.form = p.top()
-			}
-		case a.Li:
-			p.framesetOK = false
-			for i := len(p.oe) - 1; i >= 0; i-- {
-				node := p.oe[i]
-				switch node.DataAtom {
-				case a.Li:
-					p.oe = p.oe[:i]
-				case a.Address, a.Div, a.P:
-					continue
-				default:
-					if !isSpecialElement(node) {
-						continue
-					}
-				}
-				break
-			}
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Dd, a.Dt:
-			p.framesetOK = false
-			for i := len(p.oe) - 1; i >= 0; i-- {
-				node := p.oe[i]
-				switch node.DataAtom {
-				case a.Dd, a.Dt:
-					p.oe = p.oe[:i]
-				case a.Address, a.Div, a.P:
-					continue
-				default:
-					if !isSpecialElement(node) {
-						continue
-					}
-				}
-				break
-			}
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Plaintext:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-		case a.Button:
-			p.popUntil(defaultScope, a.Button)
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.framesetOK = false
-		case a.A:
-			for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
-				if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
-					p.inBodyEndTagFormatting(a.A)
-					p.oe.remove(n)
-					p.afe.remove(n)
-					break
-				}
-			}
-			p.reconstructActiveFormattingElements()
-			p.addFormattingElement()
-		case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
-			p.reconstructActiveFormattingElements()
-			p.addFormattingElement()
-		case a.Nobr:
-			p.reconstructActiveFormattingElements()
-			if p.elementInScope(defaultScope, a.Nobr) {
-				p.inBodyEndTagFormatting(a.Nobr)
-				p.reconstructActiveFormattingElements()
-			}
-			p.addFormattingElement()
-		case a.Applet, a.Marquee, a.Object:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.afe = append(p.afe, &scopeMarker)
-			p.framesetOK = false
-		case a.Table:
-			if !p.quirks {
-				p.popUntil(buttonScope, a.P)
-			}
-			p.addElement()
-			p.framesetOK = false
-			p.im = inTableIM
-			return true
-		case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-			if p.tok.DataAtom == a.Input {
-				for _, t := range p.tok.Attr {
-					if t.Key == "type" {
-						if strings.ToLower(t.Val) == "hidden" {
-							// Skip setting framesetOK = false
-							return true
-						}
-					}
-				}
-			}
-			p.framesetOK = false
-		case a.Param, a.Source, a.Track:
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-		case a.Hr:
-			p.popUntil(buttonScope, a.P)
-			p.addElement()
-			p.oe.pop()
-			p.acknowledgeSelfClosingTag()
-			p.framesetOK = false
-		case a.Image:
-			p.tok.DataAtom = a.Img
-			p.tok.Data = a.Img.String()
-			return false
-		case a.Isindex:
-			if p.form != nil {
-				// Ignore the token.
-				return true
-			}
-			action := ""
-			prompt := "This is a searchable index. Enter search keywords: "
-			attr := []Attribute{{Key: "name", Val: "isindex"}}
-			for _, t := range p.tok.Attr {
-				switch t.Key {
-				case "action":
-					action = t.Val
-				case "name":
-					// Ignore the attribute.
-				case "prompt":
-					prompt = t.Val
-				default:
-					attr = append(attr, t)
-				}
-			}
-			p.acknowledgeSelfClosingTag()
-			p.popUntil(buttonScope, a.P)
-			p.parseImpliedToken(StartTagToken, a.Form, a.Form.String())
-			if action != "" {
-				p.form.Attr = []Attribute{{Key: "action", Val: action}}
-			}
-			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
-			p.parseImpliedToken(StartTagToken, a.Label, a.Label.String())
-			p.addText(prompt)
-			p.addChild(&Node{
-				Type:     ElementNode,
-				DataAtom: a.Input,
-				Data:     a.Input.String(),
-				Attr:     attr,
-			})
-			p.oe.pop()
-			p.parseImpliedToken(EndTagToken, a.Label, a.Label.String())
-			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
-			p.parseImpliedToken(EndTagToken, a.Form, a.Form.String())
-		case a.Textarea:
-			p.addElement()
-			p.setOriginalIM()
-			p.framesetOK = false
-			p.im = textIM
-		case a.Xmp:
-			p.popUntil(buttonScope, a.P)
-			p.reconstructActiveFormattingElements()
-			p.framesetOK = false
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Iframe:
-			p.framesetOK = false
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Noembed, a.Noscript:
-			p.addElement()
-			p.setOriginalIM()
-			p.im = textIM
-		case a.Select:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-			p.framesetOK = false
-			p.im = inSelectIM
-			return true
-		case a.Optgroup, a.Option:
-			if p.top().DataAtom == a.Option {
-				p.oe.pop()
-			}
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-		case a.Rp, a.Rt:
-			if p.elementInScope(defaultScope, a.Ruby) {
-				p.generateImpliedEndTags()
-			}
-			p.addElement()
-		case a.Math, a.Svg:
-			p.reconstructActiveFormattingElements()
-			if p.tok.DataAtom == a.Math {
-				adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
-			} else {
-				adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
-			}
-			adjustForeignAttributes(p.tok.Attr)
-			p.addElement()
-			p.top().Namespace = p.tok.Data
-			if p.hasSelfClosingToken {
-				p.oe.pop()
-				p.acknowledgeSelfClosingTag()
-			}
-			return true
-		case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
-			// Ignore the token.
-		default:
-			p.reconstructActiveFormattingElements()
-			p.addElement()
-		}
-	case EndTagToken:
-		switch p.tok.DataAtom {
-		case a.Body:
-			if p.elementInScope(defaultScope, a.Body) {
-				p.im = afterBodyIM
-			}
-		case a.Html:
-			if p.elementInScope(defaultScope, a.Body) {
-				p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
-				return false
-			}
-			return true
-		case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
-			p.popUntil(defaultScope, p.tok.DataAtom)
-		case a.Form:
-			node := p.form
-			p.form = nil
-			i := p.indexOfElementInScope(defaultScope, a.Form)
-			if node == nil || i == -1 || p.oe[i] != node {
-				// Ignore the token.
-				return true
-			}
-			p.generateImpliedEndTags()
-			p.oe.remove(node)
-		case a.P:
-			if !p.elementInScope(buttonScope, a.P) {
-				p.parseImpliedToken(StartTagToken, a.P, a.P.String())
-			}
-			p.popUntil(buttonScope, a.P)
-		case a.Li:
-			p.popUntil(listItemScope, a.Li)
-		case a.Dd, a.Dt:
-			p.popUntil(defaultScope, p.tok.DataAtom)
-		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
-			p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
-		case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
-			p.inBodyEndTagFormatting(p.tok.DataAtom)
-		case a.Applet, a.Marquee, a.Object:
-			if p.popUntil(defaultScope, p.tok.DataAtom) {
-				p.clearActiveFormattingElements()
-			}
-		case a.Br:
-			p.tok.Type = StartTagToken
-			return false
-		default:
-			p.inBodyEndTagOther(p.tok.DataAtom)
-		}
-	case CommentToken:
-		p.addChild(&Node{
-			Type: CommentNode,
-			Data: p.tok.Data,
-		})
-	}
-
-	return true
-}
-
-func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
-	// This is the "adoption agency" algorithm, described at
-	// https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency
-
-	// TODO: this is a fairly literal line-by-line translation of that algorithm.
-	// Once the code successfully parses the comprehensive test suite, we should
-	// refactor this code to be more idiomatic.
-
-	// Steps 1-4. The outer loop.
-	for i := 0; i < 8; i++ {
-		// Step 5. Find the formatting element.
-		var formattingElement *Node
-		for j := len(p.afe) - 1; j >= 0; j-- {
-			if p.afe[j].Type == scopeMarkerNode {
-				break
-			}
-			if p.afe[j].DataAtom == tagAtom {
-				formattingElement = p.afe[j]
-				break
-			}
-		}
-		if formattingElement == nil {
-			p.inBodyEndTagOther(tagAtom)
-			return
-		}
-		feIndex := p.oe.index(formattingElement)
-		if feIndex == -1 {
-			p.afe.remove(formattingElement)
-			return
-		}
-		if !p.elementInScope(defaultScope, tagAtom) {
-			// Ignore the tag.
-			return
-		}
-
-		// Steps 9-10. Find the furthest block.
-		var furthestBlock *Node
-		for _, e := range p.oe[feIndex:] {
-			if isSpecialElement(e) {
-				furthestBlock = e
-				break
-			}
-		}
-		if furthestBlock == nil {
-			e := p.oe.pop()
-			for e != formattingElement {
-				e = p.oe.pop()
-			}
-			p.afe.remove(e)
-			return
-		}
-
-		// Steps 11-12. Find the common ancestor and bookmark node.
-		commonAncestor := p.oe[feIndex-1]
-		bookmark := p.afe.index(formattingElement)
-
-		// Step 13. The inner loop. Find the lastNode to reparent.
-		lastNode := furthestBlock
-		node := furthestBlock
-		x := p.oe.index(node)
-		// Steps 13.1-13.2
-		for j := 0; j < 3; j++ {
-			// Step 13.3.
-			x--
-			node = p.oe[x]
-			// Step 13.4 - 13.5.
-			if p.afe.index(node) == -1 {
-				p.oe.remove(node)
-				continue
-			}
-			// Step 13.6.
-			if node == formattingElement {
-				break
-			}
-			// Step 13.7.
-			clone := node.clone()
-			p.afe[p.afe.index(node)] = clone
-			p.oe[p.oe.index(node)] = clone
-			node = clone
-			// Step 13.8.
-			if lastNode == furthestBlock {
-				bookmark = p.afe.index(node) + 1
-			}
-			// Step 13.9.
-			if lastNode.Parent != nil {
-				lastNode.Parent.RemoveChild(lastNode)
-			}
-			node.AppendChild(lastNode)
-			// Step 13.10.
-			lastNode = node
-		}
-
-		// Step 14. Reparent lastNode to the common ancestor,
-		// or for misnested table nodes, to the foster parent.
-		if lastNode.Parent != nil {
-			lastNode.Parent.RemoveChild(lastNode)
-		}
-		switch commonAncestor.DataAtom {
-		case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
-			p.fosterParent(lastNode)
-		default:
-			commonAncestor.AppendChild(lastNode)
-		}
-
-		// Steps 15-17. Reparent nodes from the furthest block's children
-		// to a clone of the formatting element.
-		clone := formattingElement.clone()
-		reparentChildren(clone, furthestBlock)
-		furthestBlock.AppendChild(clone)
-
-		// Step 18. Fix up the list of active formatting elements.
-		if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
-			// Move the bookmark with the rest of the list.
-			bookmark--
-		}
-		p.afe.remove(formattingElement)
-		p.afe.insert(bookmark, clone)
-
-		// Step 19. Fix up the stack of open elements.
-		p.oe.remove(formattingElement)
-		p.oe.insert(p.oe.index(furthestBlock)+1, clone)
-	}
-}
-
-// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
-// "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content
-// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
-func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
-	for i := len(p.oe) - 1; i >= 0; i-- {
-		if p.oe[i].DataAtom == tagAtom {
-			p.oe = p.oe[:i]
-			break
-		}
-		if isSpecialElement(p.oe[i]) {
-			break
-		}
-	}
-}
-
-// Section 12.2.5.4.8.
-func textIM(p *parser) bool {
-	switch p.tok.Type {
-	case ErrorToken:
-		p.oe.pop()
-	case TextToken:
-		d := p.tok.Data
-		if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
-			// Ignore a newline at the start of a